@opentiny/next-sdk 0.3.0-alpha.0 → 0.3.1

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,56 +1,56 @@
1
- (function(me,Vn){typeof exports=="object"&&typeof module<"u"?Vn(exports):typeof define=="function"&&define.amd?define(["exports"],Vn):(me=typeof globalThis<"u"?globalThis:me||self,Vn(me.WebMCP={}))})(this,(function(me){"use strict";function Vn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Za={exports:{}},dc={},nn={},Hn={},pc={},fc={},hc={},nf;function Fa(){return nf||(nf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(v){if(super(),!e.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((g,S)=>`${g}${S}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((g,S)=>(S instanceof r&&(g[S.str]=(g[S.str]||0)+1),g),{})}}e._Code=n,e.nil=new n("");function o(w,...v){const g=[w[0]];let S=0;for(;S<v.length;)i(g,v[S]),g.push(w[++S]);return new n(g)}e._=o;const s=new n("+");function a(w,...v){const g=[h(w[0])];let S=0;for(;S<v.length;)g.push(s),i(g,v[S]),g.push(s,h(w[++S]));return l(g),new n(g)}e.str=a;function i(w,v){v instanceof n?w.push(...v._items):v instanceof r?w.push(v):w.push(f(v))}e.addCodeArg=i;function l(w){let v=1;for(;v<w.length-1;){if(w[v]===s){const g=c(w[v-1],w[v+1]);if(g!==void 0){w.splice(v-1,3,g);continue}w[v++]="+"}v++}}function c(w,v){if(v==='""')return w;if(w==='""')return v;if(typeof w=="string")return v instanceof r||w[w.length-1]!=='"'?void 0:typeof v!="string"?`${w.slice(0,-1)}${v}"`:v[0]==='"'?w.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(w instanceof r))return`"${w}${v.slice(1)}`}function u(w,v){return v.emptyStr()?w:w.emptyStr()?v:a`${w}${v}`}e.strConcat=u;function f(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:h(Array.isArray(w)?w.join(","):w)}function p(w){return new n(h(w))}e.stringify=p;function h(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function m(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=m;function _(w){if(typeof w=="string"&&e.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}e.getEsmExportName=_;function y(w){return new n(w.toString())}e.regexpCode=y})(hc)),hc}var mc={},of;function sf(){return of||(of=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Fa();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,f;if(!((f=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||f===void 0)&&f.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:f}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${f}]`}}e.ValueScopeName=s;const a=(0,t._)`\n`;class i extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var f;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:h}=p,m=(f=u.key)!==null&&f!==void 0?f:u.ref;let _=this._values[h];if(_){const v=_.get(m);if(v)return v}else _=this._values[h]=new Map;_.set(m,p);const y=this._scope[h]||(this._scope[h]=[]),w=y.length;return y[w]=u.ref,p.setValue(u,{property:h,itemIndex:w}),p}getValue(c,u){const f=this._values[c];if(f)return f.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,t._)`${c}${f.scopePath}`})}scopeCode(c=this._values,u,f){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,f)}_reduceValues(c,u,f={},p){let h=t.nil;for(const m in c){const _=c[m];if(!_)continue;const y=f[m]=f[m]||new Map;_.forEach(w=>{if(y.has(w))return;y.set(w,n.Started);let v=u(w);if(v){const g=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${g} ${w} = ${v};${this.opts._n}`}else if(v=p?.(w))h=(0,t._)`${h}${v}${this.opts._n}`;else throw new r(w);y.set(w,n.Completed)})}return h}}e.ValueScope=i})(mc)),mc}var af;function Ne(){return af||(af=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=Fa(),r=sf();var n=Fa();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=sf();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(x,M){return this}}class a extends s{constructor(x,M,W){super(),this.varKind=x,this.name=M,this.rhs=W}render({es5:x,_n:M}){const W=x?r.varKinds.var:this.varKind,oe=this.rhs===void 0?"":` = ${this.rhs}`;return`${W} ${this.name}${oe};`+M}optimizeNames(x,M){if(x[this.name.str])return this.rhs&&(this.rhs=H(this.rhs,x,M)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(x,M,W){super(),this.lhs=x,this.rhs=M,this.sideEffects=W}render({_n:x}){return`${this.lhs} = ${this.rhs};`+x}optimizeNames(x,M){if(!(this.lhs instanceof t.Name&&!x[this.lhs.str]&&!this.sideEffects))return this.rhs=H(this.rhs,x,M),this}get names(){const x=this.lhs instanceof t.Name?{}:{...this.lhs.names};return z(x,this.rhs)}}class l extends i{constructor(x,M,W,oe){super(x,W,oe),this.op=M}render({_n:x}){return`${this.lhs} ${this.op}= ${this.rhs};`+x}}class c extends s{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`${this.label}:`+x}}class u extends s{constructor(x){super(),this.label=x,this.names={}}render({_n:x}){return`break${this.label?` ${this.label}`:""};`+x}}class f extends s{constructor(x){super(),this.error=x}render({_n:x}){return`throw ${this.error};`+x}get names(){return this.error.names}}class p extends s{constructor(x){super(),this.code=x}render({_n:x}){return`${this.code};`+x}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(x,M){return this.code=H(this.code,x,M),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(x=[]){super(),this.nodes=x}render(x){return this.nodes.reduce((M,W)=>M+W.render(x),"")}optimizeNodes(){const{nodes:x}=this;let M=x.length;for(;M--;){const W=x[M].optimizeNodes();Array.isArray(W)?x.splice(M,1,...W):W?x[M]=W:x.splice(M,1)}return x.length>0?this:void 0}optimizeNames(x,M){const{nodes:W}=this;let oe=W.length;for(;oe--;){const ne=W[oe];ne.optimizeNames(x,M)||(ee(x,ne.names),W.splice(oe,1))}return W.length>0?this:void 0}get names(){return this.nodes.reduce((x,M)=>L(x,M.names),{})}}class m extends h{render(x){return"{"+x._n+super.render(x)+"}"+x._n}}class _ extends h{}class y extends m{}y.kind="else";class w extends m{constructor(x,M){super(M),this.condition=x}render(x){let M=`if(${this.condition})`+super.render(x);return this.else&&(M+="else "+this.else.render(x)),M}optimizeNodes(){super.optimizeNodes();const x=this.condition;if(x===!0)return this.nodes;let M=this.else;if(M){const W=M.optimizeNodes();M=this.else=Array.isArray(W)?new y(W):W}if(M)return x===!1?M instanceof w?M:M.nodes:this.nodes.length?this:new w(te(x),M instanceof w?[M]:M.nodes);if(!(x===!1||!this.nodes.length))return this}optimizeNames(x,M){var W;if(this.else=(W=this.else)===null||W===void 0?void 0:W.optimizeNames(x,M),!!(super.optimizeNames(x,M)||this.else))return this.condition=H(this.condition,x,M),this}get names(){const x=super.names;return z(x,this.condition),this.else&&L(x,this.else.names),x}}w.kind="if";class v extends m{}v.kind="for";class g extends v{constructor(x){super(),this.iteration=x}render(x){return`for(${this.iteration})`+super.render(x)}optimizeNames(x,M){if(super.optimizeNames(x,M))return this.iteration=H(this.iteration,x,M),this}get names(){return L(super.names,this.iteration.names)}}class S extends v{constructor(x,M,W,oe){super(),this.varKind=x,this.name=M,this.from=W,this.to=oe}render(x){const M=x.es5?r.varKinds.var:this.varKind,{name:W,from:oe,to:ne}=this;return`for(${M} ${W}=${oe}; ${W}<${ne}; ${W}++)`+super.render(x)}get names(){const x=z(super.names,this.from);return z(x,this.to)}}class b extends v{constructor(x,M,W,oe){super(),this.loop=x,this.varKind=M,this.name=W,this.iterable=oe}render(x){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(x)}optimizeNames(x,M){if(super.optimizeNames(x,M))return this.iterable=H(this.iterable,x,M),this}get names(){return L(super.names,this.iterable.names)}}class k extends m{constructor(x,M,W){super(),this.name=x,this.args=M,this.async=W}render(x){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(x)}}k.kind="func";class C extends h{render(x){return"return "+super.render(x)}}C.kind="return";class R extends m{render(x){let M="try"+super.render(x);return this.catch&&(M+=this.catch.render(x)),this.finally&&(M+=this.finally.render(x)),M}optimizeNodes(){var x,M;return super.optimizeNodes(),(x=this.catch)===null||x===void 0||x.optimizeNodes(),(M=this.finally)===null||M===void 0||M.optimizeNodes(),this}optimizeNames(x,M){var W,oe;return super.optimizeNames(x,M),(W=this.catch)===null||W===void 0||W.optimizeNames(x,M),(oe=this.finally)===null||oe===void 0||oe.optimizeNames(x,M),this}get names(){const x=super.names;return this.catch&&L(x,this.catch.names),this.finally&&L(x,this.finally.names),x}}class I extends m{constructor(x){super(),this.error=x}render(x){return`catch(${this.error})`+super.render(x)}}I.kind="catch";class j extends m{render(x){return"finally"+super.render(x)}}j.kind="finally";class N{constructor(x,M={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...M,_n:M.lines?`
2
- `:""},this._extScope=x,this._scope=new r.Scope({parent:x}),this._nodes=[new _]}toString(){return this._root.render(this.opts)}name(x){return this._scope.name(x)}scopeName(x){return this._extScope.name(x)}scopeValue(x,M){const W=this._extScope.value(x,M);return(this._values[W.prefix]||(this._values[W.prefix]=new Set)).add(W),W}getScopeValue(x,M){return this._extScope.getValue(x,M)}scopeRefs(x){return this._extScope.scopeRefs(x,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(x,M,W,oe){const ne=this._scope.toName(M);return W!==void 0&&oe&&(this._constants[ne.str]=W),this._leafNode(new a(x,ne,W)),ne}const(x,M,W){return this._def(r.varKinds.const,x,M,W)}let(x,M,W){return this._def(r.varKinds.let,x,M,W)}var(x,M,W){return this._def(r.varKinds.var,x,M,W)}assign(x,M,W){return this._leafNode(new i(x,M,W))}add(x,M){return this._leafNode(new l(x,e.operators.ADD,M))}code(x){return typeof x=="function"?x():x!==t.nil&&this._leafNode(new p(x)),this}object(...x){const M=["{"];for(const[W,oe]of x)M.length>1&&M.push(","),M.push(W),(W!==oe||this.opts.es5)&&(M.push(":"),(0,t.addCodeArg)(M,oe));return M.push("}"),new t._Code(M)}if(x,M,W){if(this._blockNode(new w(x)),M&&W)this.code(M).else().code(W).endIf();else if(M)this.code(M).endIf();else if(W)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(x){return this._elseNode(new w(x))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode(w,y)}_for(x,M){return this._blockNode(x),M&&this.code(M).endFor(),this}for(x,M){return this._for(new g(x),M)}forRange(x,M,W,oe,ne=this.opts.es5?r.varKinds.var:r.varKinds.let){const we=this._scope.toName(x);return this._for(new S(ne,we,M,W),()=>oe(we))}forOf(x,M,W,oe=r.varKinds.const){const ne=this._scope.toName(x);if(this.opts.es5){const we=M instanceof t.Name?M:this.var("_arr",M);return this.forRange("_i",0,(0,t._)`${we}.length`,K=>{this.var(ne,(0,t._)`${we}[${K}]`),W(ne)})}return this._for(new b("of",oe,ne,M),()=>W(ne))}forIn(x,M,W,oe=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(x,(0,t._)`Object.keys(${M})`,W);const ne=this._scope.toName(x);return this._for(new b("in",oe,ne,M),()=>W(ne))}endFor(){return this._endBlockNode(v)}label(x){return this._leafNode(new c(x))}break(x){return this._leafNode(new u(x))}return(x){const M=new C;if(this._blockNode(M),this.code(x),M.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(C)}try(x,M,W){if(!M&&!W)throw new Error('CodeGen: "try" without "catch" and "finally"');const oe=new R;if(this._blockNode(oe),this.code(x),M){const ne=this.name("e");this._currNode=oe.catch=new I(ne),M(ne)}return W&&(this._currNode=oe.finally=new j,this.code(W)),this._endBlockNode(I,j)}throw(x){return this._leafNode(new f(x))}block(x,M){return this._blockStarts.push(this._nodes.length),x&&this.code(x).endBlock(M),this}endBlock(x){const M=this._blockStarts.pop();if(M===void 0)throw new Error("CodeGen: not in self-balancing block");const W=this._nodes.length-M;if(W<0||x!==void 0&&W!==x)throw new Error(`CodeGen: wrong number of nodes: ${W} vs ${x} expected`);return this._nodes.length=M,this}func(x,M=t.nil,W,oe){return this._blockNode(new k(x,M,W)),oe&&this.code(oe).endFunc(),this}endFunc(){return this._endBlockNode(k)}optimize(x=1){for(;x-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(x){return this._currNode.nodes.push(x),this}_blockNode(x){this._currNode.nodes.push(x),this._nodes.push(x)}_endBlockNode(x,M){const W=this._currNode;if(W instanceof x||M&&W instanceof M)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${M?`${x.kind}/${M.kind}`:x.kind}"`)}_elseNode(x){const M=this._currNode;if(!(M instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=M.else=x,this}get _root(){return this._nodes[0]}get _currNode(){const x=this._nodes;return x[x.length-1]}set _currNode(x){const M=this._nodes;M[M.length-1]=x}}e.CodeGen=N;function L(Z,x){for(const M in x)Z[M]=(Z[M]||0)+(x[M]||0);return Z}function z(Z,x){return x instanceof t._CodeOrName?L(Z,x.names):Z}function H(Z,x,M){if(Z instanceof t.Name)return W(Z);if(!oe(Z))return Z;return new t._Code(Z._items.reduce((ne,we)=>(we instanceof t.Name&&(we=W(we)),we instanceof t._Code?ne.push(...we._items):ne.push(we),ne),[]));function W(ne){const we=M[ne.str];return we===void 0||x[ne.str]!==1?ne:(delete x[ne.str],we)}function oe(ne){return ne instanceof t._Code&&ne._items.some(we=>we instanceof t.Name&&x[we.str]===1&&M[we.str]!==void 0)}}function ee(Z,x){for(const M in x)Z[M]=(Z[M]||0)-(x[M]||0)}function te(Z){return typeof Z=="boolean"||typeof Z=="number"||Z===null?!Z:(0,t._)`!${U(Z)}`}e.not=te;const X=E(e.operators.AND);function V(...Z){return Z.reduce(X)}e.and=V;const se=E(e.operators.OR);function D(...Z){return Z.reduce(se)}e.or=D;function E(Z){return(x,M)=>x===t.nil?M:M===t.nil?x:(0,t._)`${U(x)} ${Z} ${U(M)}`}function U(Z){return Z instanceof t.Name?Z:(0,t._)`(${Z})`}})(fc)),fc}var Oe={},lf;function Ze(){if(lf)return Oe;lf=1,Object.defineProperty(Oe,"__esModule",{value:!0}),Oe.checkStrictMode=Oe.getErrorPath=Oe.Type=Oe.useFunc=Oe.setEvaluated=Oe.evaluatedPropsToName=Oe.mergeEvaluated=Oe.eachItem=Oe.unescapeJsonPointer=Oe.escapeJsonPointer=Oe.escapeFragment=Oe.unescapeFragment=Oe.schemaRefOrVal=Oe.schemaHasRulesButRef=Oe.schemaHasRules=Oe.checkUnknownRules=Oe.alwaysValidSchema=Oe.toHash=void 0;const e=Ne(),t=Fa();function r(b){const k={};for(const C of b)k[C]=!0;return k}Oe.toHash=r;function n(b,k){return typeof k=="boolean"?k:Object.keys(k).length===0?!0:(o(b,k),!s(k,b.self.RULES.all))}Oe.alwaysValidSchema=n;function o(b,k=b.schema){const{opts:C,self:R}=b;if(!C.strictSchema||typeof k=="boolean")return;const I=R.RULES.keywords;for(const j in k)I[j]||S(b,`unknown keyword: "${j}"`)}Oe.checkUnknownRules=o;function s(b,k){if(typeof b=="boolean")return!b;for(const C in b)if(k[C])return!0;return!1}Oe.schemaHasRules=s;function a(b,k){if(typeof b=="boolean")return!b;for(const C in b)if(C!=="$ref"&&k.all[C])return!0;return!1}Oe.schemaHasRulesButRef=a;function i({topSchemaRef:b,schemaPath:k},C,R,I){if(!I){if(typeof C=="number"||typeof C=="boolean")return C;if(typeof C=="string")return(0,e._)`${C}`}return(0,e._)`${b}${k}${(0,e.getProperty)(R)}`}Oe.schemaRefOrVal=i;function l(b){return f(decodeURIComponent(b))}Oe.unescapeFragment=l;function c(b){return encodeURIComponent(u(b))}Oe.escapeFragment=c;function u(b){return typeof b=="number"?`${b}`:b.replace(/~/g,"~0").replace(/\//g,"~1")}Oe.escapeJsonPointer=u;function f(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}Oe.unescapeJsonPointer=f;function p(b,k){if(Array.isArray(b))for(const C of b)k(C);else k(b)}Oe.eachItem=p;function h({mergeNames:b,mergeToName:k,mergeValues:C,resultToName:R}){return(I,j,N,L)=>{const z=N===void 0?j:N instanceof e.Name?(j instanceof e.Name?b(I,j,N):k(I,j,N),N):j instanceof e.Name?(k(I,N,j),j):C(j,N);return L===e.Name&&!(z instanceof e.Name)?R(I,z):z}}Oe.mergeEvaluated={props:h({mergeNames:(b,k,C)=>b.if((0,e._)`${C} !== true && ${k} !== undefined`,()=>{b.if((0,e._)`${k} === true`,()=>b.assign(C,!0),()=>b.assign(C,(0,e._)`${C} || {}`).code((0,e._)`Object.assign(${C}, ${k})`))}),mergeToName:(b,k,C)=>b.if((0,e._)`${C} !== true`,()=>{k===!0?b.assign(C,!0):(b.assign(C,(0,e._)`${C} || {}`),_(b,C,k))}),mergeValues:(b,k)=>b===!0?!0:{...b,...k},resultToName:m}),items:h({mergeNames:(b,k,C)=>b.if((0,e._)`${C} !== true && ${k} !== undefined`,()=>b.assign(C,(0,e._)`${k} === true ? true : ${C} > ${k} ? ${C} : ${k}`)),mergeToName:(b,k,C)=>b.if((0,e._)`${C} !== true`,()=>b.assign(C,k===!0?!0:(0,e._)`${C} > ${k} ? ${C} : ${k}`)),mergeValues:(b,k)=>b===!0?!0:Math.max(b,k),resultToName:(b,k)=>b.var("items",k)})};function m(b,k){if(k===!0)return b.var("props",!0);const C=b.var("props",(0,e._)`{}`);return k!==void 0&&_(b,C,k),C}Oe.evaluatedPropsToName=m;function _(b,k,C){Object.keys(C).forEach(R=>b.assign((0,e._)`${k}${(0,e.getProperty)(R)}`,!0))}Oe.setEvaluated=_;const y={};function w(b,k){return b.scopeValue("func",{ref:k,code:y[k.code]||(y[k.code]=new t._Code(k.code))})}Oe.useFunc=w;var v;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(v||(Oe.Type=v={}));function g(b,k,C){if(b instanceof e.Name){const R=k===v.Num;return C?R?(0,e._)`"[" + ${b} + "]"`:(0,e._)`"['" + ${b} + "']"`:R?(0,e._)`"/" + ${b}`:(0,e._)`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return C?(0,e.getProperty)(b).toString():"/"+u(b)}Oe.getErrorPath=g;function S(b,k,C=b.opts.strictSchema){if(C){if(k=`strict mode: ${k}`,C===!0)throw new Error(k);b.self.logger.warn(k)}}return Oe.checkStrictMode=S,Oe}var Va={},cf;function Tn(){if(cf)return Va;cf=1,Object.defineProperty(Va,"__esModule",{value:!0});const e=Ne(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Va.default=t,Va}var uf;function Ha(){return uf||(uf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Ne(),r=Ze(),n=Tn();e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:w})=>w?(0,t.str)`"${y}" keyword must be ${w} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,w=e.keywordError,v,g){const{it:S}=y,{gen:b,compositeRule:k,allErrors:C}=S,R=f(y,w,v);g??(k||C)?l(b,R):c(S,(0,t._)`[${R}]`)}e.reportError=o;function s(y,w=e.keywordError,v){const{it:g}=y,{gen:S,compositeRule:b,allErrors:k}=g,C=f(y,w,v);l(S,C),b||k||c(g,n.default.vErrors)}e.reportExtraError=s;function a(y,w){y.assign(n.default.errors,w),y.if((0,t._)`${n.default.vErrors} !== null`,()=>y.if(w,()=>y.assign((0,t._)`${n.default.vErrors}.length`,w),()=>y.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:y,keyword:w,schemaValue:v,data:g,errsCount:S,it:b}){if(S===void 0)throw new Error("ajv implementation error");const k=y.name("err");y.forRange("i",S,n.default.errors,C=>{y.const(k,(0,t._)`${n.default.vErrors}[${C}]`),y.if((0,t._)`${k}.instancePath === undefined`,()=>y.assign((0,t._)`${k}.instancePath`,(0,t.strConcat)(n.default.instancePath,b.errorPath))),y.assign((0,t._)`${k}.schemaPath`,(0,t.str)`${b.errSchemaPath}/${w}`),b.opts.verbose&&(y.assign((0,t._)`${k}.schema`,v),y.assign((0,t._)`${k}.data`,g))})}e.extendErrors=i;function l(y,w){const v=y.const("err",w);y.if((0,t._)`${n.default.vErrors} === null`,()=>y.assign(n.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${n.default.vErrors}.push(${v})`),y.code((0,t._)`${n.default.errors}++`)}function c(y,w){const{gen:v,validateName:g,schemaEnv:S}=y;S.$async?v.throw((0,t._)`new ${y.ValidationError}(${w})`):(v.assign((0,t._)`${g}.errors`,w),v.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function f(y,w,v){const{createErrors:g}=y.it;return g===!1?(0,t._)`{}`:p(y,w,v)}function p(y,w,v={}){const{gen:g,it:S}=y,b=[h(S,v),m(y,v)];return _(y,w,b),g.object(...b)}function h({errorPath:y},{instancePath:w}){const v=w?(0,t.str)`${y}${(0,r.getErrorPath)(w,r.Type.Str)}`:y;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,v)]}function m({keyword:y,it:{errSchemaPath:w}},{schemaPath:v,parentSchema:g}){let S=g?w:(0,t.str)`${w}/${y}`;return v&&(S=(0,t.str)`${S}${(0,r.getErrorPath)(v,r.Type.Str)}`),[u.schemaPath,S]}function _(y,{params:w,message:v},g){const{keyword:S,data:b,schemaValue:k,it:C}=y,{opts:R,propertyName:I,topSchemaRef:j,schemaPath:N}=C;g.push([u.keyword,S],[u.params,typeof w=="function"?w(y):w||(0,t._)`{}`]),R.messages&&g.push([u.message,typeof v=="function"?v(y):v]),R.verbose&&g.push([u.schema,k],[u.parentSchema,(0,t._)`${j}${N}`],[n.default.data,b]),I&&g.push([u.propertyName,I])}})(pc)),pc}var df;function Qw(){if(df)return Hn;df=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.boolOrEmptySchema=Hn.topBoolOrEmptySchema=void 0;const e=Ha(),t=Ne(),r=Tn(),n={message:"boolean schema is false"};function o(i){const{gen:l,schema:c,validateName:u}=i;c===!1?a(i,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}Hn.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}Hn.boolOrEmptySchema=s;function a(i,l){const{gen:c,data:u}=i,f={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,e.reportError)(f,n,void 0,l)}return Hn}var Mt={},Bn={},pf;function ff(){if(pf)return Bn;pf=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.getRules=Bn.isJSONType=void 0;const e=["string","number","integer","boolean","null","object","array"],t=new Set(e);function r(o){return typeof o=="string"&&t.has(o)}Bn.isJSONType=r;function n(){const o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}return Bn.getRules=n,Bn}var on={},hf;function mf(){if(hf)return on;hf=1,Object.defineProperty(on,"__esModule",{value:!0}),on.shouldUseRule=on.shouldUseGroup=on.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}on.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}on.shouldUseGroup=t;function r(n,o){var s;return n[o.keyword]!==void 0||((s=o.definition.implements)===null||s===void 0?void 0:s.some(a=>n[a]!==void 0))}return on.shouldUseRule=r,on}var gf;function Ba(){if(gf)return Mt;gf=1,Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.reportTypeError=Mt.checkDataTypes=Mt.checkDataType=Mt.coerceAndCheckDataType=Mt.getJSONTypes=Mt.getSchemaTypes=Mt.DataType=void 0;const e=ff(),t=mf(),r=Ha(),n=Ne(),o=Ze();var s;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(s||(Mt.DataType=s={}));function a(v){const g=i(v.type);if(g.includes("null")){if(v.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!g.length&&v.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');v.nullable===!0&&g.push("null")}return g}Mt.getSchemaTypes=a;function i(v){const g=Array.isArray(v)?v:v?[v]:[];if(g.every(e.isJSONType))return g;throw new Error("type must be JSONType or JSONType[]: "+g.join(","))}Mt.getJSONTypes=i;function l(v,g){const{gen:S,data:b,opts:k}=v,C=u(g,k.coerceTypes),R=g.length>0&&!(C.length===0&&g.length===1&&(0,t.schemaHasRulesForType)(v,g[0]));if(R){const I=m(g,b,k.strictNumbers,s.Wrong);S.if(I,()=>{C.length?f(v,g,C):y(v)})}return R}Mt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(v,g){return g?v.filter(S=>c.has(S)||g==="array"&&S==="array"):[]}function f(v,g,S){const{gen:b,data:k,opts:C}=v,R=b.let("dataType",(0,n._)`typeof ${k}`),I=b.let("coerced",(0,n._)`undefined`);C.coerceTypes==="array"&&b.if((0,n._)`${R} == 'object' && Array.isArray(${k}) && ${k}.length == 1`,()=>b.assign(k,(0,n._)`${k}[0]`).assign(R,(0,n._)`typeof ${k}`).if(m(g,k,C.strictNumbers),()=>b.assign(I,k))),b.if((0,n._)`${I} !== undefined`);for(const N of S)(c.has(N)||N==="array"&&C.coerceTypes==="array")&&j(N);b.else(),y(v),b.endIf(),b.if((0,n._)`${I} !== undefined`,()=>{b.assign(k,I),p(v,I)});function j(N){switch(N){case"string":b.elseIf((0,n._)`${R} == "number" || ${R} == "boolean"`).assign(I,(0,n._)`"" + ${k}`).elseIf((0,n._)`${k} === null`).assign(I,(0,n._)`""`);return;case"number":b.elseIf((0,n._)`${R} == "boolean" || ${k} === null
3
- || (${R} == "string" && ${k} && ${k} == +${k})`).assign(I,(0,n._)`+${k}`);return;case"integer":b.elseIf((0,n._)`${R} === "boolean" || ${k} === null
4
- || (${R} === "string" && ${k} && ${k} == +${k} && !(${k} % 1))`).assign(I,(0,n._)`+${k}`);return;case"boolean":b.elseIf((0,n._)`${k} === "false" || ${k} === 0 || ${k} === null`).assign(I,!1).elseIf((0,n._)`${k} === "true" || ${k} === 1`).assign(I,!0);return;case"null":b.elseIf((0,n._)`${k} === "" || ${k} === 0 || ${k} === false`),b.assign(I,null);return;case"array":b.elseIf((0,n._)`${R} === "string" || ${R} === "number"
5
- || ${R} === "boolean" || ${k} === null`).assign(I,(0,n._)`[${k}]`)}}}function p({gen:v,parentData:g,parentDataProperty:S},b){v.if((0,n._)`${g} !== undefined`,()=>v.assign((0,n._)`${g}[${S}]`,b))}function h(v,g,S,b=s.Correct){const k=b===s.Correct?n.operators.EQ:n.operators.NEQ;let C;switch(v){case"null":return(0,n._)`${g} ${k} null`;case"array":C=(0,n._)`Array.isArray(${g})`;break;case"object":C=(0,n._)`${g} && typeof ${g} == "object" && !Array.isArray(${g})`;break;case"integer":C=R((0,n._)`!(${g} % 1) && !isNaN(${g})`);break;case"number":C=R();break;default:return(0,n._)`typeof ${g} ${k} ${v}`}return b===s.Correct?C:(0,n.not)(C);function R(I=n.nil){return(0,n.and)((0,n._)`typeof ${g} == "number"`,I,S?(0,n._)`isFinite(${g})`:n.nil)}}Mt.checkDataType=h;function m(v,g,S,b){if(v.length===1)return h(v[0],g,S,b);let k;const C=(0,o.toHash)(v);if(C.array&&C.object){const R=(0,n._)`typeof ${g} != "object"`;k=C.null?R:(0,n._)`!${g} || ${R}`,delete C.null,delete C.array,delete C.object}else k=n.nil;C.number&&delete C.integer;for(const R in C)k=(0,n.and)(k,h(R,g,S,b));return k}Mt.checkDataTypes=m;const _={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:g})=>typeof v=="string"?(0,n._)`{type: ${v}}`:(0,n._)`{type: ${g}}`};function y(v){const g=w(v);(0,r.reportError)(g,_)}Mt.reportTypeError=y;function w(v){const{gen:g,data:S,schema:b}=v,k=(0,o.schemaRefOrVal)(v,b,"type");return{gen:g,keyword:"type",data:S,schema:b.type,schemaCode:k,schemaValue:k,parentSchema:b,params:{},it:v}}return Mt}var us={},yf;function Xw(){if(yf)return us;yf=1,Object.defineProperty(us,"__esModule",{value:!0}),us.assignDefaults=void 0;const e=Ne(),t=Ze();function r(o,s){const{properties:a,items:i}=o.schema;if(s==="object"&&a)for(const l in a)n(o,l,a[l].default);else s==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(o,c,l.default))}us.assignDefaults=r;function n(o,s,a){const{gen:i,compositeRule:l,data:c,opts:u}=o;if(a===void 0)return;const f=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${f}`);return}let p=(0,e._)`${f} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${f} === null || ${f} === ""`),i.if(p,(0,e._)`${f} = ${(0,e.stringify)(a)}`)}return us}var Rr={},Ke={},vf;function Pr(){if(vf)return Ke;vf=1,Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.validateUnion=Ke.validateArray=Ke.usePattern=Ke.callValidateCode=Ke.schemaProperties=Ke.allSchemaProperties=Ke.noPropertyInData=Ke.propertyInData=Ke.isOwnProperty=Ke.hasPropFunc=Ke.reportMissingProp=Ke.checkMissingProp=Ke.checkReportMissingProp=void 0;const e=Ne(),t=Ze(),r=Tn(),n=Ze();function o(v,g){const{gen:S,data:b,it:k}=v;S.if(u(S,b,g,k.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${g}`},!0),v.error()})}Ke.checkReportMissingProp=o;function s({gen:v,data:g,it:{opts:S}},b,k){return(0,e.or)(...b.map(C=>(0,e.and)(u(v,g,C,S.ownProperties),(0,e._)`${k} = ${C}`)))}Ke.checkMissingProp=s;function a(v,g){v.setParams({missingProperty:g},!0),v.error()}Ke.reportMissingProp=a;function i(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}Ke.hasPropFunc=i;function l(v,g,S){return(0,e._)`${i(v)}.call(${g}, ${S})`}Ke.isOwnProperty=l;function c(v,g,S,b){const k=(0,e._)`${g}${(0,e.getProperty)(S)} !== undefined`;return b?(0,e._)`${k} && ${l(v,g,S)}`:k}Ke.propertyInData=c;function u(v,g,S,b){const k=(0,e._)`${g}${(0,e.getProperty)(S)} === undefined`;return b?(0,e.or)(k,(0,e.not)(l(v,g,S))):k}Ke.noPropertyInData=u;function f(v){return v?Object.keys(v).filter(g=>g!=="__proto__"):[]}Ke.allSchemaProperties=f;function p(v,g){return f(g).filter(S=>!(0,t.alwaysValidSchema)(v,g[S]))}Ke.schemaProperties=p;function h({schemaCode:v,data:g,it:{gen:S,topSchemaRef:b,schemaPath:k,errorPath:C},it:R},I,j,N){const L=N?(0,e._)`${v}, ${g}, ${b}${k}`:g,z=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,C)],[r.default.parentData,R.parentData],[r.default.parentDataProperty,R.parentDataProperty],[r.default.rootData,r.default.rootData]];R.opts.dynamicRef&&z.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const H=(0,e._)`${L}, ${S.object(...z)}`;return j!==e.nil?(0,e._)`${I}.call(${j}, ${H})`:(0,e._)`${I}(${H})`}Ke.callValidateCode=h;const m=(0,e._)`new RegExp`;function _({gen:v,it:{opts:g}},S){const b=g.unicodeRegExp?"u":"",{regExp:k}=g.code,C=k(S,b);return v.scopeValue("pattern",{key:C.toString(),ref:C,code:(0,e._)`${k.code==="new RegExp"?m:(0,n.useFunc)(v,k)}(${S}, ${b})`})}Ke.usePattern=_;function y(v){const{gen:g,data:S,keyword:b,it:k}=v,C=g.name("valid");if(k.allErrors){const I=g.let("valid",!0);return R(()=>g.assign(I,!1)),I}return g.var(C,!0),R(()=>g.break()),C;function R(I){const j=g.const("len",(0,e._)`${S}.length`);g.forRange("i",0,j,N=>{v.subschema({keyword:b,dataProp:N,dataPropType:t.Type.Num},C),g.if((0,e.not)(C),I)})}}Ke.validateArray=y;function w(v){const{gen:g,schema:S,keyword:b,it:k}=v;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(j=>(0,t.alwaysValidSchema)(k,j))&&!k.opts.unevaluated)return;const R=g.let("valid",!1),I=g.name("_valid");g.block(()=>S.forEach((j,N)=>{const L=v.subschema({keyword:b,schemaProp:N,compositeRule:!0},I);g.assign(R,(0,e._)`${R} || ${I}`),v.mergeValidEvaluated(L,I)||g.if((0,e.not)(R))})),v.result(R,()=>v.reset(),()=>v.error(!0))}return Ke.validateUnion=w,Ke}var _f;function eb(){if(_f)return Rr;_f=1,Object.defineProperty(Rr,"__esModule",{value:!0}),Rr.validateKeywordUsage=Rr.validSchemaType=Rr.funcKeywordCode=Rr.macroKeywordCode=void 0;const e=Ne(),t=Tn(),r=Pr(),n=Ha();function o(p,h){const{gen:m,keyword:_,schema:y,parentSchema:w,it:v}=p,g=h.macro.call(v.self,y,w,v),S=c(m,_,g);v.opts.validateSchema!==!1&&v.self.validateSchema(g,!0);const b=m.name("valid");p.subschema({schema:g,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${_}`,topSchemaRef:S,compositeRule:!0},b),p.pass(b,()=>p.error(!0))}Rr.macroKeywordCode=o;function s(p,h){var m;const{gen:_,keyword:y,schema:w,parentSchema:v,$data:g,it:S}=p;l(S,h);const b=!g&&h.compile?h.compile.call(S.self,w,v,S):h.validate,k=c(_,y,b),C=_.let("valid");p.block$data(C,R),p.ok((m=h.valid)!==null&&m!==void 0?m:C);function R(){if(h.errors===!1)N(),h.modifying&&a(p),L(()=>p.error());else{const z=h.async?I():j();h.modifying&&a(p),L(()=>i(p,z))}}function I(){const z=_.let("ruleErrs",null);return _.try(()=>N((0,e._)`await `),H=>_.assign(C,!1).if((0,e._)`${H} instanceof ${S.ValidationError}`,()=>_.assign(z,(0,e._)`${H}.errors`),()=>_.throw(H))),z}function j(){const z=(0,e._)`${k}.errors`;return _.assign(z,null),N(e.nil),z}function N(z=h.async?(0,e._)`await `:e.nil){const H=S.opts.passContext?t.default.this:t.default.self,ee=!("compile"in h&&!g||h.schema===!1);_.assign(C,(0,e._)`${z}${(0,r.callValidateCode)(p,k,H,ee)}`,h.modifying)}function L(z){var H;_.if((0,e.not)((H=h.valid)!==null&&H!==void 0?H:C),z)}}Rr.funcKeywordCode=s;function a(p){const{gen:h,data:m,it:_}=p;h.if(_.parentData,()=>h.assign(m,(0,e._)`${_.parentData}[${_.parentDataProperty}]`))}function i(p,h){const{gen:m}=p;m.if((0,e._)`Array.isArray(${h})`,()=>{m.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${h} : ${t.default.vErrors}.concat(${h})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},h){if(h.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,h,m){if(m===void 0)throw new Error(`keyword "${h}" failed to compile`);return p.scopeValue("keyword",typeof m=="function"?{ref:m}:{ref:m,code:(0,e.stringify)(m)})}function u(p,h,m=!1){return!h.length||h.some(_=>_==="array"?Array.isArray(p):_==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==_||m&&typeof p>"u")}Rr.validSchemaType=u;function f({schema:p,opts:h,self:m,errSchemaPath:_},y,w){if(Array.isArray(y.keyword)?!y.keyword.includes(w):y.keyword!==w)throw new Error("ajv implementation error");const v=y.dependencies;if(v?.some(g=>!Object.prototype.hasOwnProperty.call(p,g)))throw new Error(`parent schema must have dependencies of ${w}: ${v.join(",")}`);if(y.validateSchema&&!y.validateSchema(p[w])){const S=`keyword "${w}" value is invalid at path "${_}": `+m.errorsText(y.validateSchema.errors);if(h.validateSchema==="log")m.logger.error(S);else throw new Error(S)}}return Rr.validateKeywordUsage=f,Rr}var sn={},wf;function tb(){if(wf)return sn;wf=1,Object.defineProperty(sn,"__esModule",{value:!0}),sn.extendSubschemaMode=sn.extendSubschemaData=sn.getSubschema=void 0;const e=Ne(),t=Ze();function r(s,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:f}){if(a!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const p=s.schema[a];return i===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${a}`}:{schema:p[i],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${a}/${(0,t.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||f===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:f,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}sn.getSubschema=r;function n(s,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:f}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=a;if(i!==void 0){const{errorPath:m,dataPathArr:_,opts:y}=a,w=p.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);h(w),s.errorPath=(0,e.str)`${m}${(0,t.getErrorPath)(i,l,y.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[..._,s.parentDataProperty]}if(c!==void 0){const m=c instanceof e.Name?c:p.let("data",c,!0);h(m),f!==void 0&&(s.propertyName=f)}u&&(s.dataTypes=u);function h(m){s.data=m,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,m]}}sn.extendSubschemaData=n;function o(s,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(s.compositeRule=l),c!==void 0&&(s.createErrors=c),u!==void 0&&(s.allErrors=u),s.jtdDiscriminator=a,s.jtdMetadata=i}return sn.extendSubschemaMode=o,sn}var Vt={},gc,bf;function Tf(){return bf||(bf=1,gc=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var a=s[o];if(!e(t[a],r[a]))return!1}return!0}return t!==t&&r!==r}),gc}var yc={exports:{}},kf;function rb(){if(kf)return yc.exports;kf=1;var e=yc.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var a=typeof s=="function"?s:s.pre||function(){},i=s.post||function(){};t(o,a,i,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t(n,o,s,a,i,l,c,u,f,p){if(a&&typeof a=="object"&&!Array.isArray(a)){o(a,i,l,c,u,f,p);for(var h in a){var m=a[h];if(Array.isArray(m)){if(h in e.arrayKeywords)for(var _=0;_<m.length;_++)t(n,o,s,m[_],i+"/"+h+"/"+_,l,i,h,a,_)}else if(h in e.propsKeywords){if(m&&typeof m=="object")for(var y in m)t(n,o,s,m[y],i+"/"+h+"/"+r(y),l,i,h,a,y)}else(h in e.keywords||n.allKeys&&!(h in e.skipKeywords))&&t(n,o,s,m,i+"/"+h,l,i,h,a)}s(a,i,l,c,u,f,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return yc.exports}var Sf;function Wa(){if(Sf)return Vt;Sf=1,Object.defineProperty(Vt,"__esModule",{value:!0}),Vt.getSchemaRefs=Vt.resolveUrl=Vt.normalizeId=Vt._getFullPath=Vt.getFullPath=Vt.inlineRef=void 0;const e=Ze(),t=Tf(),r=rb(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(_,y=!0){return typeof _=="boolean"?!0:y===!0?!a(_):y?i(_)<=y:!1}Vt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(_){for(const y in _){if(s.has(y))return!0;const w=_[y];if(Array.isArray(w)&&w.some(a)||typeof w=="object"&&a(w))return!0}return!1}function i(_){let y=0;for(const w in _){if(w==="$ref")return 1/0;if(y++,!n.has(w)&&(typeof _[w]=="object"&&(0,e.eachItem)(_[w],v=>y+=i(v)),y===1/0))return 1/0}return y}function l(_,y="",w){w!==!1&&(y=f(y));const v=_.parse(y);return c(_,v)}Vt.getFullPath=l;function c(_,y){return _.serialize(y).split("#")[0]+"#"}Vt._getFullPath=c;const u=/#\/?$/;function f(_){return _?_.replace(u,""):""}Vt.normalizeId=f;function p(_,y,w){return w=f(w),_.resolve(y,w)}Vt.resolveUrl=p;const h=/^[a-z_][-a-z0-9._]*$/i;function m(_,y){if(typeof _=="boolean")return{};const{schemaId:w,uriResolver:v}=this.opts,g=f(_[w]||y),S={"":g},b=l(v,g,!1),k={},C=new Set;return r(_,{allKeys:!0},(j,N,L,z)=>{if(z===void 0)return;const H=b+N;let ee=S[z];typeof j[w]=="string"&&(ee=te.call(this,j[w])),X.call(this,j.$anchor),X.call(this,j.$dynamicAnchor),S[N]=ee;function te(V){const se=this.opts.uriResolver.resolve;if(V=f(ee?se(ee,V):V),C.has(V))throw I(V);C.add(V);let D=this.refs[V];return typeof D=="string"&&(D=this.refs[D]),typeof D=="object"?R(j,D.schema,V):V!==f(H)&&(V[0]==="#"?(R(j,k[V],V),k[V]=j):this.refs[V]=H),V}function X(V){if(typeof V=="string"){if(!h.test(V))throw new Error(`invalid anchor "${V}"`);te.call(this,`#${V}`)}}}),k;function R(j,N,L){if(N!==void 0&&!t(j,N))throw I(L)}function I(j){return new Error(`reference "${j}" resolves to more than one schema`)}}return Vt.getSchemaRefs=m,Vt}var Cf;function Ga(){if(Cf)return nn;Cf=1,Object.defineProperty(nn,"__esModule",{value:!0}),nn.getData=nn.KeywordCxt=nn.validateFunctionCode=void 0;const e=Qw(),t=Ba(),r=mf(),n=Ba(),o=Xw(),s=eb(),a=tb(),i=Ne(),l=Tn(),c=Wa(),u=Ze(),f=Ha();function p(A){if(b(A)&&(C(A),S(A))){y(A);return}h(A,()=>(0,e.topBoolOrEmptySchema)(A))}nn.validateFunctionCode=p;function h({gen:A,validateName:F,schema:G,schemaEnv:Q,opts:pe},Ie){pe.code.es5?A.func(F,(0,i._)`${l.default.data}, ${l.default.valCxt}`,Q.$async,()=>{A.code((0,i._)`"use strict"; ${v(G,pe)}`),_(A,pe),A.code(Ie)}):A.func(F,(0,i._)`${l.default.data}, ${m(pe)}`,Q.$async,()=>A.code(v(G,pe)).code(Ie))}function m(A){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${A.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function _(A,F){A.if(l.default.valCxt,()=>{A.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),A.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),A.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),A.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),F.dynamicRef&&A.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{A.var(l.default.instancePath,(0,i._)`""`),A.var(l.default.parentData,(0,i._)`undefined`),A.var(l.default.parentDataProperty,(0,i._)`undefined`),A.var(l.default.rootData,l.default.data),F.dynamicRef&&A.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function y(A){const{schema:F,opts:G,gen:Q}=A;h(A,()=>{G.$comment&&F.$comment&&z(A),j(A),Q.let(l.default.vErrors,null),Q.let(l.default.errors,0),G.unevaluated&&w(A),R(A),H(A)})}function w(A){const{gen:F,validateName:G}=A;A.evaluated=F.const("evaluated",(0,i._)`${G}.evaluated`),F.if((0,i._)`${A.evaluated}.dynamicProps`,()=>F.assign((0,i._)`${A.evaluated}.props`,(0,i._)`undefined`)),F.if((0,i._)`${A.evaluated}.dynamicItems`,()=>F.assign((0,i._)`${A.evaluated}.items`,(0,i._)`undefined`))}function v(A,F){const G=typeof A=="object"&&A[F.schemaId];return G&&(F.code.source||F.code.process)?(0,i._)`/*# sourceURL=${G} */`:i.nil}function g(A,F){if(b(A)&&(C(A),S(A))){k(A,F);return}(0,e.boolOrEmptySchema)(A,F)}function S({schema:A,self:F}){if(typeof A=="boolean")return!A;for(const G in A)if(F.RULES.all[G])return!0;return!1}function b(A){return typeof A.schema!="boolean"}function k(A,F){const{schema:G,gen:Q,opts:pe}=A;pe.$comment&&G.$comment&&z(A),N(A),L(A);const Ie=Q.const("_errs",l.default.errors);R(A,Ie),Q.var(F,(0,i._)`${Ie} === ${l.default.errors}`)}function C(A){(0,u.checkUnknownRules)(A),I(A)}function R(A,F){if(A.opts.jtd)return te(A,[],!1,F);const G=(0,t.getSchemaTypes)(A.schema),Q=(0,t.coerceAndCheckDataType)(A,G);te(A,G,!Q,F)}function I(A){const{schema:F,errSchemaPath:G,opts:Q,self:pe}=A;F.$ref&&Q.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(F,pe.RULES)&&pe.logger.warn(`$ref: keywords ignored in schema at path "${G}"`)}function j(A){const{schema:F,opts:G}=A;F.default!==void 0&&G.useDefaults&&G.strictSchema&&(0,u.checkStrictMode)(A,"default is ignored in the schema root")}function N(A){const F=A.schema[A.opts.schemaId];F&&(A.baseId=(0,c.resolveUrl)(A.opts.uriResolver,A.baseId,F))}function L(A){if(A.schema.$async&&!A.schemaEnv.$async)throw new Error("async schema in sync schema")}function z({gen:A,schemaEnv:F,schema:G,errSchemaPath:Q,opts:pe}){const Ie=G.$comment;if(pe.$comment===!0)A.code((0,i._)`${l.default.self}.logger.log(${Ie})`);else if(typeof pe.$comment=="function"){const Ge=(0,i.str)`${Q}/$comment`,dt=A.scopeValue("root",{ref:F.root});A.code((0,i._)`${l.default.self}.opts.$comment(${Ie}, ${Ge}, ${dt}.schema)`)}}function H(A){const{gen:F,schemaEnv:G,validateName:Q,ValidationError:pe,opts:Ie}=A;G.$async?F.if((0,i._)`${l.default.errors} === 0`,()=>F.return(l.default.data),()=>F.throw((0,i._)`new ${pe}(${l.default.vErrors})`)):(F.assign((0,i._)`${Q}.errors`,l.default.vErrors),Ie.unevaluated&&ee(A),F.return((0,i._)`${l.default.errors} === 0`))}function ee({gen:A,evaluated:F,props:G,items:Q}){G instanceof i.Name&&A.assign((0,i._)`${F}.props`,G),Q instanceof i.Name&&A.assign((0,i._)`${F}.items`,Q)}function te(A,F,G,Q){const{gen:pe,schema:Ie,data:Ge,allErrors:dt,opts:wt,self:st}=A,{RULES:it}=st;if(Ie.$ref&&(wt.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(Ie,it))){pe.block(()=>oe(A,"$ref",it.all.$ref.definition));return}wt.jtd||V(A,F),pe.block(()=>{for(const bt of it.rules)zt(bt);zt(it.post)});function zt(bt){(0,r.shouldUseGroup)(Ie,bt)&&(bt.type?(pe.if((0,n.checkDataType)(bt.type,Ge,wt.strictNumbers)),X(A,bt),F.length===1&&F[0]===bt.type&&G&&(pe.else(),(0,n.reportTypeError)(A)),pe.endIf()):X(A,bt),dt||pe.if((0,i._)`${l.default.errors} === ${Q||0}`))}}function X(A,F){const{gen:G,schema:Q,opts:{useDefaults:pe}}=A;pe&&(0,o.assignDefaults)(A,F.type),G.block(()=>{for(const Ie of F.rules)(0,r.shouldUseRule)(Q,Ie)&&oe(A,Ie.keyword,Ie.definition,F.type)})}function V(A,F){A.schemaEnv.meta||!A.opts.strictTypes||(se(A,F),A.opts.allowUnionTypes||D(A,F),E(A,A.dataTypes))}function se(A,F){if(F.length){if(!A.dataTypes.length){A.dataTypes=F;return}F.forEach(G=>{Z(A.dataTypes,G)||M(A,`type "${G}" not allowed by context "${A.dataTypes.join(",")}"`)}),x(A,F)}}function D(A,F){F.length>1&&!(F.length===2&&F.includes("null"))&&M(A,"use allowUnionTypes to allow union type keyword")}function E(A,F){const G=A.self.RULES.all;for(const Q in G){const pe=G[Q];if(typeof pe=="object"&&(0,r.shouldUseRule)(A.schema,pe)){const{type:Ie}=pe.definition;Ie.length&&!Ie.some(Ge=>U(F,Ge))&&M(A,`missing type "${Ie.join(",")}" for keyword "${Q}"`)}}}function U(A,F){return A.includes(F)||F==="number"&&A.includes("integer")}function Z(A,F){return A.includes(F)||F==="integer"&&A.includes("number")}function x(A,F){const G=[];for(const Q of A.dataTypes)Z(F,Q)?G.push(Q):F.includes("integer")&&Q==="number"&&G.push("integer");A.dataTypes=G}function M(A,F){const G=A.schemaEnv.baseId+A.errSchemaPath;F+=` at "${G}" (strictTypes)`,(0,u.checkStrictMode)(A,F,A.opts.strictTypes)}class W{constructor(F,G,Q){if((0,s.validateKeywordUsage)(F,G,Q),this.gen=F.gen,this.allErrors=F.allErrors,this.keyword=Q,this.data=F.data,this.schema=F.schema[Q],this.$data=G.$data&&F.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(F,this.schema,Q,this.$data),this.schemaType=G.schemaType,this.parentSchema=F.schema,this.params={},this.it=F,this.def=G,this.$data)this.schemaCode=F.gen.const("vSchema",K(this.$data,F));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,G.schemaType,G.allowUndefined))throw new Error(`${Q} value must be ${JSON.stringify(G.schemaType)}`);("code"in G?G.trackErrors:G.errors!==!1)&&(this.errsCount=F.gen.const("_errs",l.default.errors))}result(F,G,Q){this.failResult((0,i.not)(F),G,Q)}failResult(F,G,Q){this.gen.if(F),Q?Q():this.error(),G?(this.gen.else(),G(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(F,G){this.failResult((0,i.not)(F),void 0,G)}fail(F){if(F===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(F),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(F){if(!this.$data)return this.fail(F);const{schemaCode:G}=this;this.fail((0,i._)`${G} !== undefined && (${(0,i.or)(this.invalid$data(),F)})`)}error(F,G,Q){if(G){this.setParams(G),this._error(F,Q),this.setParams({});return}this._error(F,Q)}_error(F,G){(F?f.reportExtraError:f.reportError)(this,this.def.error,G)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(F){this.allErrors||this.gen.if(F)}setParams(F,G){G?Object.assign(this.params,F):this.params=F}block$data(F,G,Q=i.nil){this.gen.block(()=>{this.check$data(F,Q),G()})}check$data(F=i.nil,G=i.nil){if(!this.$data)return;const{gen:Q,schemaCode:pe,schemaType:Ie,def:Ge}=this;Q.if((0,i.or)((0,i._)`${pe} === undefined`,G)),F!==i.nil&&Q.assign(F,!0),(Ie.length||Ge.validateSchema)&&(Q.elseIf(this.invalid$data()),this.$dataError(),F!==i.nil&&Q.assign(F,!1)),Q.else()}invalid$data(){const{gen:F,schemaCode:G,schemaType:Q,def:pe,it:Ie}=this;return(0,i.or)(Ge(),dt());function Ge(){if(Q.length){if(!(G instanceof i.Name))throw new Error("ajv implementation error");const wt=Array.isArray(Q)?Q:[Q];return(0,i._)`${(0,n.checkDataTypes)(wt,G,Ie.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function dt(){if(pe.validateSchema){const wt=F.scopeValue("validate$data",{ref:pe.validateSchema});return(0,i._)`!${wt}(${G})`}return i.nil}}subschema(F,G){const Q=(0,a.getSubschema)(this.it,F);(0,a.extendSubschemaData)(Q,this.it,F),(0,a.extendSubschemaMode)(Q,F);const pe={...this.it,...Q,items:void 0,props:void 0};return g(pe,G),pe}mergeEvaluated(F,G){const{it:Q,gen:pe}=this;Q.opts.unevaluated&&(Q.props!==!0&&F.props!==void 0&&(Q.props=u.mergeEvaluated.props(pe,F.props,Q.props,G)),Q.items!==!0&&F.items!==void 0&&(Q.items=u.mergeEvaluated.items(pe,F.items,Q.items,G)))}mergeValidEvaluated(F,G){const{it:Q,gen:pe}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return pe.if(G,()=>this.mergeEvaluated(F,i.Name)),!0}}nn.KeywordCxt=W;function oe(A,F,G,Q){const pe=new W(A,G,F);"code"in G?G.code(pe,Q):pe.$data&&G.validate?(0,s.funcKeywordCode)(pe,G):"macro"in G?(0,s.macroKeywordCode)(pe,G):(G.compile||G.validate)&&(0,s.funcKeywordCode)(pe,G)}const ne=/^\/(?:[^~]|~0|~1)*$/,we=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function K(A,{dataLevel:F,dataNames:G,dataPathArr:Q}){let pe,Ie;if(A==="")return l.default.rootData;if(A[0]==="/"){if(!ne.test(A))throw new Error(`Invalid JSON-pointer: ${A}`);pe=A,Ie=l.default.rootData}else{const st=we.exec(A);if(!st)throw new Error(`Invalid JSON-pointer: ${A}`);const it=+st[1];if(pe=st[2],pe==="#"){if(it>=F)throw new Error(wt("property/index",it));return Q[F-it]}if(it>F)throw new Error(wt("data",it));if(Ie=G[F-it],!pe)return Ie}let Ge=Ie;const dt=pe.split("/");for(const st of dt)st&&(Ie=(0,i._)`${Ie}${(0,i.getProperty)((0,u.unescapeJsonPointer)(st))}`,Ge=(0,i._)`${Ge} && ${Ie}`);return Ge;function wt(st,it){return`Cannot access ${st} ${it} levels up, current level is ${F}`}}return nn.getData=K,nn}var Ja={},If;function vc(){if(If)return Ja;If=1,Object.defineProperty(Ja,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return Ja.default=e,Ja}var Ka={},xf;function Ya(){if(xf)return Ka;xf=1,Object.defineProperty(Ka,"__esModule",{value:!0});const e=Wa();class t extends Error{constructor(n,o,s,a){super(a||`can't resolve reference ${s} from id ${o}`),this.missingRef=(0,e.resolveUrl)(n,o,s),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(n,this.missingRef))}}return Ka.default=t,Ka}var lr={},Ef;function _c(){if(Ef)return lr;Ef=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.resolveSchema=lr.getCompilingSchema=lr.resolveRef=lr.compileSchema=lr.SchemaEnv=void 0;const e=Ne(),t=vc(),r=Tn(),n=Wa(),o=Ze(),s=Ga();class a{constructor(w){var v;this.refs={},this.dynamicAnchors={};let g;typeof w.schema=="object"&&(g=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(v=w.baseId)!==null&&v!==void 0?v:(0,n.normalizeId)(g?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=g?.$async,this.refs={}}}lr.SchemaEnv=a;function i(y){const w=u.call(this,y);if(w)return w;const v=(0,n.getFullPath)(this.opts.uriResolver,y.root.baseId),{es5:g,lines:S}=this.opts.code,{ownProperties:b}=this.opts,k=new e.CodeGen(this.scope,{es5:g,lines:S,ownProperties:b});let C;y.$async&&(C=k.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const R=k.scopeName("validate");y.validateName=R;const I={gen:k,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:k.scopeValue("schema",this.opts.code.source===!0?{ref:y.schema,code:(0,e.stringify)(y.schema)}:{ref:y.schema}),validateName:R,ValidationError:C,schema:y.schema,schemaEnv:y,rootId:v,baseId:y.baseId||v,schemaPath:e.nil,errSchemaPath:y.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let j;try{this._compilations.add(y),(0,s.validateFunctionCode)(I),k.optimize(this.opts.code.optimize);const N=k.toString();j=`${k.scopeRefs(r.default.scope)}return ${N}`,this.opts.code.process&&(j=this.opts.code.process(j,y));const z=new Function(`${r.default.self}`,`${r.default.scope}`,j)(this,this.scope.get());if(this.scope.value(R,{ref:z}),z.errors=null,z.schema=y.schema,z.schemaEnv=y,y.$async&&(z.$async=!0),this.opts.code.source===!0&&(z.source={validateName:R,validateCode:N,scopeValues:k._values}),this.opts.unevaluated){const{props:H,items:ee}=I;z.evaluated={props:H instanceof e.Name?void 0:H,items:ee instanceof e.Name?void 0:ee,dynamicProps:H instanceof e.Name,dynamicItems:ee instanceof e.Name},z.source&&(z.source.evaluated=(0,e.stringify)(z.evaluated))}return y.validate=z,y}catch(N){throw delete y.validate,delete y.validateName,j&&this.logger.error("Error compiling schema, function code:",j),N}finally{this._compilations.delete(y)}}lr.compileSchema=i;function l(y,w,v){var g;v=(0,n.resolveUrl)(this.opts.uriResolver,w,v);const S=y.refs[v];if(S)return S;let b=p.call(this,y,v);if(b===void 0){const k=(g=y.localRefs)===null||g===void 0?void 0:g[v],{schemaId:C}=this.opts;k&&(b=new a({schema:k,schemaId:C,root:y,baseId:w}))}if(b!==void 0)return y.refs[v]=c.call(this,b)}lr.resolveRef=l;function c(y){return(0,n.inlineRef)(y.schema,this.opts.inlineRefs)?y.schema:y.validate?y:i.call(this,y)}function u(y){for(const w of this._compilations)if(f(w,y))return w}lr.getCompilingSchema=u;function f(y,w){return y.schema===w.schema&&y.root===w.root&&y.baseId===w.baseId}function p(y,w){let v;for(;typeof(v=this.refs[w])=="string";)w=v;return v||this.schemas[w]||h.call(this,y,w)}function h(y,w){const v=this.opts.uriResolver.parse(w),g=(0,n._getFullPath)(this.opts.uriResolver,v);let S=(0,n.getFullPath)(this.opts.uriResolver,y.baseId,void 0);if(Object.keys(y.schema).length>0&&g===S)return _.call(this,v,y);const b=(0,n.normalizeId)(g),k=this.refs[b]||this.schemas[b];if(typeof k=="string"){const C=h.call(this,y,k);return typeof C?.schema!="object"?void 0:_.call(this,v,C)}if(typeof k?.schema=="object"){if(k.validate||i.call(this,k),b===(0,n.normalizeId)(w)){const{schema:C}=k,{schemaId:R}=this.opts,I=C[R];return I&&(S=(0,n.resolveUrl)(this.opts.uriResolver,S,I)),new a({schema:C,schemaId:R,root:y,baseId:S})}return _.call(this,v,k)}}lr.resolveSchema=h;const m=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _(y,{baseId:w,schema:v,root:g}){var S;if(((S=y.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(const C of y.fragment.slice(1).split("/")){if(typeof v=="boolean")return;const R=v[(0,o.unescapeFragment)(C)];if(R===void 0)return;v=R;const I=typeof v=="object"&&v[this.opts.schemaId];!m.has(C)&&I&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,I))}let b;if(typeof v!="boolean"&&v.$ref&&!(0,o.schemaHasRulesButRef)(v,this.RULES)){const C=(0,n.resolveUrl)(this.opts.uriResolver,w,v.$ref);b=h.call(this,g,C)}const{schemaId:k}=this.opts;if(b=b||new a({schema:v,schemaId:k,root:g,baseId:w}),b.schema!==b.root.schema)return b}return lr}const nb={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var Qa={},ds={exports:{}},wc,$f;function Rf(){if($f)return wc;$f=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(p){let h="",m=0,_=0;for(_=0;_<p.length;_++)if(m=p[_].charCodeAt(0),m!==48){if(!(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102))return"";h+=p[_];break}for(_+=1;_<p.length;_++){if(m=p[_].charCodeAt(0),!(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102))return"";h+=p[_]}return h}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(p){return p.length=0,!0}function s(p,h,m){if(p.length){const _=r(p);if(_!=="")h.push(_);else return m.error=!0,!1;p.length=0}return!0}function a(p){let h=0;const m={error:!1,address:"",zone:""},_=[],y=[];let w=!1,v=!1,g=s;for(let S=0;S<p.length;S++){const b=p[S];if(!(b==="["||b==="]"))if(b===":"){if(w===!0&&(v=!0),!g(y,_,m))break;if(++h>7){m.error=!0;break}S>0&&p[S-1]===":"&&(w=!0),_.push(":");continue}else if(b==="%"){if(!g(y,_,m))break;g=o}else{y.push(b);continue}}return y.length&&(g===o?m.zone=y.join(""):v?_.push(y.join("")):_.push(r(y))),m.address=_.join(""),m}function i(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const h=a(p);if(h.error)return{host:p,isIPV6:!1};{let m=h.address,_=h.address;return h.zone&&(m+="%"+h.zone,_+="%25"+h.zone),{host:m,isIPV6:!0,escapedHost:_}}}function l(p,h){let m=0;for(let _=0;_<p.length;_++)p[_]===h&&m++;return m}function c(p){let h=p;const m=[];let _=-1,y=0;for(;y=h.length;){if(y===1){if(h===".")break;if(h==="/"){m.push("/");break}else{m.push(h);break}}else if(y===2){if(h[0]==="."){if(h[1]===".")break;if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&(h[1]==="."||h[1]==="/")){m.push("/");break}}else if(y===3&&h==="/.."){m.length!==0&&m.pop(),m.push("/");break}if(h[0]==="."){if(h[1]==="."){if(h[2]==="/"){h=h.slice(3);continue}}else if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&h[1]==="."){if(h[2]==="/"){h=h.slice(2);continue}else if(h[2]==="."&&h[3]==="/"){h=h.slice(3),m.length!==0&&m.pop();continue}}if((_=h.indexOf("/",1))===-1){m.push(h);break}else m.push(h.slice(0,_)),h=h.slice(_)}return m.join("")}function u(p,h){const m=h!==!0?escape:unescape;return p.scheme!==void 0&&(p.scheme=m(p.scheme)),p.userinfo!==void 0&&(p.userinfo=m(p.userinfo)),p.host!==void 0&&(p.host=m(p.host)),p.path!==void 0&&(p.path=m(p.path)),p.query!==void 0&&(p.query=m(p.query)),p.fragment!==void 0&&(p.fragment=m(p.fragment)),p}function f(p){const h=[];if(p.userinfo!==void 0&&(h.push(p.userinfo),h.push("@")),p.host!==void 0){let m=unescape(p.host);if(!t(m)){const _=i(m);_.isIPV6===!0?m=`[${_.escapedHost}]`:m=p.host}h.push(m)}return(typeof p.port=="number"||typeof p.port=="string")&&(h.push(":"),h.push(String(p.port))),h.length?h.join(""):void 0}return wc={nonSimpleDomain:n,recomposeAuthority:f,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},wc}var bc,Pf;function ob(){if(Pf)return bc;Pf=1;const{isUUID:e}=Rf(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(b){return r.indexOf(b)!==-1}function o(b){return b.secure===!0?!0:b.secure===!1?!1:b.scheme?b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S"):!1}function s(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function a(b){const k=String(b.scheme).toLowerCase()==="https";return(b.port===(k?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function i(b){return b.secure=o(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function l(b){if((b.port===(o(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){const[k,C]=b.resourceName.split("?");b.path=k&&k!=="/"?k:void 0,b.query=C,b.resourceName=void 0}return b.fragment=void 0,b}function c(b,k){if(!b.path)return b.error="URN can not be parsed",b;const C=b.path.match(t);if(C){const R=k.scheme||b.scheme||"urn";b.nid=C[1].toLowerCase(),b.nss=C[2];const I=`${R}:${k.nid||b.nid}`,j=S(I);b.path=void 0,j&&(b=j.parse(b,k))}else b.error=b.error||"URN can not be parsed.";return b}function u(b,k){if(b.nid===void 0)throw new Error("URN without nid cannot be serialized");const C=k.scheme||b.scheme||"urn",R=b.nid.toLowerCase(),I=`${C}:${k.nid||R}`,j=S(I);j&&(b=j.serialize(b,k));const N=b,L=b.nss;return N.path=`${R||k.nid}:${L}`,k.skipEscape=!0,N}function f(b,k){const C=b;return C.uuid=C.nss,C.nss=void 0,!k.tolerant&&(!C.uuid||!e(C.uuid))&&(C.error=C.error||"UUID is not valid."),C}function p(b){const k=b;return k.nss=(b.uuid||"").toLowerCase(),k}const h={scheme:"http",domainHost:!0,parse:s,serialize:a},m={scheme:"https",domainHost:h.domainHost,parse:s,serialize:a},_={scheme:"ws",domainHost:!0,parse:i,serialize:l},y={scheme:"wss",domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},g={http:h,https:m,ws:_,wss:y,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:f,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(g,null);function S(b){return b&&(g[b]||g[b.toLowerCase()])||void 0}return bc={wsIsSecure:o,SCHEMES:g,isValidSchemeName:n,getSchemeHandler:S},bc}var Mf;function sb(){if(Mf)return ds.exports;Mf=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=Rf(),{SCHEMES:a,getSchemeHandler:i}=ob();function l(y,w){return typeof y=="string"?y=p(m(y,w),w):typeof y=="object"&&(y=m(p(y,w),w)),y}function c(y,w,v){const g=v?Object.assign({scheme:"null"},v):{scheme:"null"},S=u(m(y,g),m(w,g),g,!0);return g.skipEscape=!0,p(S,g)}function u(y,w,v,g){const S={};return g||(y=m(p(y,v),v),w=m(p(w,v),v)),v=v||{},!v.tolerant&&w.scheme?(S.scheme=w.scheme,S.userinfo=w.userinfo,S.host=w.host,S.port=w.port,S.path=t(w.path||""),S.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(S.userinfo=w.userinfo,S.host=w.host,S.port=w.port,S.path=t(w.path||""),S.query=w.query):(w.path?(w.path[0]==="/"?S.path=t(w.path):((y.userinfo!==void 0||y.host!==void 0||y.port!==void 0)&&!y.path?S.path="/"+w.path:y.path?S.path=y.path.slice(0,y.path.lastIndexOf("/")+1)+w.path:S.path=w.path,S.path=t(S.path)),S.query=w.query):(S.path=y.path,w.query!==void 0?S.query=w.query:S.query=y.query),S.userinfo=y.userinfo,S.host=y.host,S.port=y.port),S.scheme=y.scheme),S.fragment=w.fragment,S}function f(y,w,v){return typeof y=="string"?(y=unescape(y),y=p(n(m(y,v),!0),{...v,skipEscape:!0})):typeof y=="object"&&(y=p(n(y,!0),{...v,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(m(w,v),!0),{...v,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{...v,skipEscape:!0})),y.toLowerCase()===w.toLowerCase()}function p(y,w){const v={host:y.host,scheme:y.scheme,userinfo:y.userinfo,port:y.port,path:y.path,query:y.query,nid:y.nid,nss:y.nss,uuid:y.uuid,fragment:y.fragment,reference:y.reference,resourceName:y.resourceName,secure:y.secure,error:""},g=Object.assign({},w),S=[],b=i(g.scheme||v.scheme);b&&b.serialize&&b.serialize(v,g),v.path!==void 0&&(g.skipEscape?v.path=unescape(v.path):(v.path=escape(v.path),v.scheme!==void 0&&(v.path=v.path.split("%3A").join(":")))),g.reference!=="suffix"&&v.scheme&&S.push(v.scheme,":");const k=r(v);if(k!==void 0&&(g.reference!=="suffix"&&S.push("//"),S.push(k),v.path&&v.path[0]!=="/"&&S.push("/")),v.path!==void 0){let C=v.path;!g.absolutePath&&(!b||!b.absolutePath)&&(C=t(C)),k===void 0&&C[0]==="/"&&C[1]==="/"&&(C="/%2F"+C.slice(2)),S.push(C)}return v.query!==void 0&&S.push("?",v.query),v.fragment!==void 0&&S.push("#",v.fragment),S.join("")}const h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function m(y,w){const v=Object.assign({},w),g={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let S=!1;v.reference==="suffix"&&(v.scheme?y=v.scheme+":"+y:y="//"+y);const b=y.match(h);if(b){if(g.scheme=b[1],g.userinfo=b[3],g.host=b[4],g.port=parseInt(b[5],10),g.path=b[6]||"",g.query=b[7],g.fragment=b[8],isNaN(g.port)&&(g.port=b[5]),g.host)if(o(g.host)===!1){const R=e(g.host);g.host=R.host.toLowerCase(),S=R.isIPV6}else S=!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",v.reference&&v.reference!=="suffix"&&v.reference!==g.reference&&(g.error=g.error||"URI is not a "+v.reference+" reference.");const k=i(v.scheme||g.scheme);if(!v.unicodeSupport&&(!k||!k.unicodeSupport)&&g.host&&(v.domainHost||k&&k.domainHost)&&S===!1&&s(g.host))try{g.host=URL.domainToASCII(g.host.toLowerCase())}catch(C){g.error=g.error||"Host's domain name can not be converted to ASCII: "+C}(!k||k&&!k.skipNormalize)&&(y.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)))),k&&k.parse&&k.parse(g,v)}else g.error=g.error||"URI can not be parsed.";return g}const _={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:f,serialize:p,parse:m};return ds.exports=_,ds.exports.default=_,ds.exports.fastUri=_,ds.exports}var Nf;function ab(){if(Nf)return Qa;Nf=1,Object.defineProperty(Qa,"__esModule",{value:!0});const e=sb();return e.code='require("ajv/dist/runtime/uri").default',Qa.default=e,Qa}var Of;function ib(){return Of||(Of=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Ga();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Ne();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=vc(),o=Ya(),s=ff(),a=_c(),i=Ne(),l=Wa(),c=Ba(),u=Ze(),f=nb,p=ab(),h=(D,E)=>new RegExp(D,E);h.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function g(D){var E,U,Z,x,M,W,oe,ne,we,K,A,F,G,Q,pe,Ie,Ge,dt,wt,st,it,zt,bt,Br,ar;const et=D.strict,$r=(E=D.code)===null||E===void 0?void 0:E.optimize,$=$r===!0||$r===void 0?1:$r||0,Y=(Z=(U=D.code)===null||U===void 0?void 0:U.regExp)!==null&&Z!==void 0?Z:h,je=(x=D.uriResolver)!==null&&x!==void 0?x:p.default;return{strictSchema:(W=(M=D.strictSchema)!==null&&M!==void 0?M:et)!==null&&W!==void 0?W:!0,strictNumbers:(ne=(oe=D.strictNumbers)!==null&&oe!==void 0?oe:et)!==null&&ne!==void 0?ne:!0,strictTypes:(K=(we=D.strictTypes)!==null&&we!==void 0?we:et)!==null&&K!==void 0?K:"log",strictTuples:(F=(A=D.strictTuples)!==null&&A!==void 0?A:et)!==null&&F!==void 0?F:"log",strictRequired:(Q=(G=D.strictRequired)!==null&&G!==void 0?G:et)!==null&&Q!==void 0?Q:!1,code:D.code?{...D.code,optimize:$,regExp:Y}:{optimize:$,regExp:Y},loopRequired:(pe=D.loopRequired)!==null&&pe!==void 0?pe:v,loopEnum:(Ie=D.loopEnum)!==null&&Ie!==void 0?Ie:v,meta:(Ge=D.meta)!==null&&Ge!==void 0?Ge:!0,messages:(dt=D.messages)!==null&&dt!==void 0?dt:!0,inlineRefs:(wt=D.inlineRefs)!==null&&wt!==void 0?wt:!0,schemaId:(st=D.schemaId)!==null&&st!==void 0?st:"$id",addUsedSchema:(it=D.addUsedSchema)!==null&&it!==void 0?it:!0,validateSchema:(zt=D.validateSchema)!==null&&zt!==void 0?zt:!0,validateFormats:(bt=D.validateFormats)!==null&&bt!==void 0?bt:!0,unicodeRegExp:(Br=D.unicodeRegExp)!==null&&Br!==void 0?Br:!0,int32range:(ar=D.int32range)!==null&&ar!==void 0?ar:!0,uriResolver:je}}class S{constructor(E={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,E=this.opts={...E,...g(E)};const{es5:U,lines:Z}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:_,es5:U,lines:Z}),this.logger=L(E.logger);const x=E.validateFormats;E.validateFormats=!1,this.RULES=(0,s.getRules)(),b.call(this,y,E,"NOT SUPPORTED"),b.call(this,w,E,"DEPRECATED","warn"),this._metaOpts=j.call(this),E.formats&&R.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),E.keywords&&I.call(this,E.keywords),typeof E.meta=="object"&&this.addMetaSchema(E.meta),C.call(this),E.validateFormats=x}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:E,meta:U,schemaId:Z}=this.opts;let x=f;Z==="id"&&(x={...f},x.id=x.$id,delete x.$id),U&&E&&this.addMetaSchema(x,x[Z],!1)}defaultMeta(){const{meta:E,schemaId:U}=this.opts;return this.opts.defaultMeta=typeof E=="object"?E[U]||E:void 0}validate(E,U){let Z;if(typeof E=="string"){if(Z=this.getSchema(E),!Z)throw new Error(`no schema with key or ref "${E}"`)}else Z=this.compile(E);const x=Z(U);return"$async"in Z||(this.errors=Z.errors),x}compile(E,U){const Z=this._addSchema(E,U);return Z.validate||this._compileSchemaEnv(Z)}compileAsync(E,U){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:Z}=this.opts;return x.call(this,E,U);async function x(K,A){await M.call(this,K.$schema);const F=this._addSchema(K,A);return F.validate||W.call(this,F)}async function M(K){K&&!this.getSchema(K)&&await x.call(this,{$ref:K},!0)}async function W(K){try{return this._compileSchemaEnv(K)}catch(A){if(!(A instanceof o.default))throw A;return oe.call(this,A),await ne.call(this,A.missingSchema),W.call(this,K)}}function oe({missingSchema:K,missingRef:A}){if(this.refs[K])throw new Error(`AnySchema ${K} is loaded but ${A} cannot be resolved`)}async function ne(K){const A=await we.call(this,K);this.refs[K]||await M.call(this,A.$schema),this.refs[K]||this.addSchema(A,K,U)}async function we(K){const A=this._loading[K];if(A)return A;try{return await(this._loading[K]=Z(K))}finally{delete this._loading[K]}}}addSchema(E,U,Z,x=this.opts.validateSchema){if(Array.isArray(E)){for(const W of E)this.addSchema(W,void 0,Z,x);return this}let M;if(typeof E=="object"){const{schemaId:W}=this.opts;if(M=E[W],M!==void 0&&typeof M!="string")throw new Error(`schema ${W} must be string`)}return U=(0,l.normalizeId)(U||M),this._checkUnique(U),this.schemas[U]=this._addSchema(E,Z,U,x,!0),this}addMetaSchema(E,U,Z=this.opts.validateSchema){return this.addSchema(E,U,!0,Z),this}validateSchema(E,U){if(typeof E=="boolean")return!0;let Z;if(Z=E.$schema,Z!==void 0&&typeof Z!="string")throw new Error("$schema must be a string");if(Z=Z||this.opts.defaultMeta||this.defaultMeta(),!Z)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const x=this.validate(Z,E);if(!x&&U){const M="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(M);else throw new Error(M)}return x}getSchema(E){let U;for(;typeof(U=k.call(this,E))=="string";)E=U;if(U===void 0){const{schemaId:Z}=this.opts,x=new a.SchemaEnv({schema:{},schemaId:Z});if(U=a.resolveSchema.call(this,x,E),!U)return;this.refs[E]=U}return U.validate||this._compileSchemaEnv(U)}removeSchema(E){if(E instanceof RegExp)return this._removeAllSchemas(this.schemas,E),this._removeAllSchemas(this.refs,E),this;switch(typeof E){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const U=k.call(this,E);return typeof U=="object"&&this._cache.delete(U.schema),delete this.schemas[E],delete this.refs[E],this}case"object":{const U=E;this._cache.delete(U);let Z=E[this.opts.schemaId];return Z&&(Z=(0,l.normalizeId)(Z),delete this.schemas[Z],delete this.refs[Z]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(E){for(const U of E)this.addKeyword(U);return this}addKeyword(E,U){let Z;if(typeof E=="string")Z=E,typeof U=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),U.keyword=Z);else if(typeof E=="object"&&U===void 0){if(U=E,Z=U.keyword,Array.isArray(Z)&&!Z.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(H.call(this,Z,U),!U)return(0,u.eachItem)(Z,M=>ee.call(this,M)),this;X.call(this,U);const x={...U,type:(0,c.getJSONTypes)(U.type),schemaType:(0,c.getJSONTypes)(U.schemaType)};return(0,u.eachItem)(Z,x.type.length===0?M=>ee.call(this,M,x):M=>x.type.forEach(W=>ee.call(this,M,x,W))),this}getKeyword(E){const U=this.RULES.all[E];return typeof U=="object"?U.definition:!!U}removeKeyword(E){const{RULES:U}=this;delete U.keywords[E],delete U.all[E];for(const Z of U.rules){const x=Z.rules.findIndex(M=>M.keyword===E);x>=0&&Z.rules.splice(x,1)}return this}addFormat(E,U){return typeof U=="string"&&(U=new RegExp(U)),this.formats[E]=U,this}errorsText(E=this.errors,{separator:U=", ",dataVar:Z="data"}={}){return!E||E.length===0?"No errors":E.map(x=>`${Z}${x.instancePath} ${x.message}`).reduce((x,M)=>x+U+M)}$dataMetaSchema(E,U){const Z=this.RULES.all;E=JSON.parse(JSON.stringify(E));for(const x of U){const M=x.split("/").slice(1);let W=E;for(const oe of M)W=W[oe];for(const oe in Z){const ne=Z[oe];if(typeof ne!="object")continue;const{$data:we}=ne.definition,K=W[oe];we&&K&&(W[oe]=se(K))}}return E}_removeAllSchemas(E,U){for(const Z in E){const x=E[Z];(!U||U.test(Z))&&(typeof x=="string"?delete E[Z]:x&&!x.meta&&(this._cache.delete(x.schema),delete E[Z]))}}_addSchema(E,U,Z,x=this.opts.validateSchema,M=this.opts.addUsedSchema){let W;const{schemaId:oe}=this.opts;if(typeof E=="object")W=E[oe];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof E!="boolean")throw new Error("schema must be object or boolean")}let ne=this._cache.get(E);if(ne!==void 0)return ne;Z=(0,l.normalizeId)(W||Z);const we=l.getSchemaRefs.call(this,E,Z);return ne=new a.SchemaEnv({schema:E,schemaId:oe,meta:U,baseId:Z,localRefs:we}),this._cache.set(ne.schema,ne),M&&!Z.startsWith("#")&&(Z&&this._checkUnique(Z),this.refs[Z]=ne),x&&this.validateSchema(E,!0),ne}_checkUnique(E){if(this.schemas[E]||this.refs[E])throw new Error(`schema with key or id "${E}" already exists`)}_compileSchemaEnv(E){if(E.meta?this._compileMetaSchema(E):a.compileSchema.call(this,E),!E.validate)throw new Error("ajv implementation error");return E.validate}_compileMetaSchema(E){const U=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,E)}finally{this.opts=U}}}S.ValidationError=n.default,S.MissingRefError=o.default,e.default=S;function b(D,E,U,Z="error"){for(const x in D){const M=x;M in E&&this.logger[Z](`${U}: option ${x}. ${D[M]}`)}}function k(D){return D=(0,l.normalizeId)(D),this.schemas[D]||this.refs[D]}function C(){const D=this.opts.schemas;if(D)if(Array.isArray(D))this.addSchema(D);else for(const E in D)this.addSchema(D[E],E)}function R(){for(const D in this.opts.formats){const E=this.opts.formats[D];E&&this.addFormat(D,E)}}function I(D){if(Array.isArray(D)){this.addVocabulary(D);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const E in D){const U=D[E];U.keyword||(U.keyword=E),this.addKeyword(U)}}function j(){const D={...this.opts};for(const E of m)delete D[E];return D}const N={log(){},warn(){},error(){}};function L(D){if(D===!1)return N;if(D===void 0)return console;if(D.log&&D.warn&&D.error)return D;throw new Error("logger must implement log, warn and error methods")}const z=/^[a-z_$][a-z0-9_$:-]*$/i;function H(D,E){const{RULES:U}=this;if((0,u.eachItem)(D,Z=>{if(U.keywords[Z])throw new Error(`Keyword ${Z} is already defined`);if(!z.test(Z))throw new Error(`Keyword ${Z} has invalid name`)}),!!E&&E.$data&&!("code"in E||"validate"in E))throw new Error('$data keyword must have "code" or "validate" function')}function ee(D,E,U){var Z;const x=E?.post;if(U&&x)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:M}=this;let W=x?M.post:M.rules.find(({type:ne})=>ne===U);if(W||(W={type:U,rules:[]},M.rules.push(W)),M.keywords[D]=!0,!E)return;const oe={keyword:D,definition:{...E,type:(0,c.getJSONTypes)(E.type),schemaType:(0,c.getJSONTypes)(E.schemaType)}};E.before?te.call(this,W,oe,E.before):W.rules.push(oe),M.all[D]=oe,(Z=E.implements)===null||Z===void 0||Z.forEach(ne=>this.addKeyword(ne))}function te(D,E,U){const Z=D.rules.findIndex(x=>x.keyword===U);Z>=0?D.rules.splice(Z,0,E):(D.rules.push(E),this.logger.warn(`rule ${U} is not defined`))}function X(D){let{metaSchema:E}=D;E!==void 0&&(D.$data&&this.opts.$data&&(E=se(E)),D.validateSchema=this.compile(E,!0))}const V={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function se(D){return{anyOf:[D,V]}}})(dc)),dc}var Xa={},ei={},ti={},Af;function lb(){if(Af)return ti;Af=1,Object.defineProperty(ti,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return ti.default=e,ti}var kn={},qf;function cb(){if(qf)return kn;qf=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.callRef=kn.getValidate=void 0;const e=Ya(),t=Pr(),r=Ne(),n=Tn(),o=_c(),s=Ze(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:f,it:p}=c,{baseId:h,schemaEnv:m,validateName:_,opts:y,self:w}=p,{root:v}=m;if((f==="#"||f==="#/")&&h===v.baseId)return S();const g=o.resolveRef.call(w,v,h,f);if(g===void 0)throw new e.default(p.opts.uriResolver,h,f);if(g instanceof o.SchemaEnv)return b(g);return k(g);function S(){if(m===v)return l(c,_,m,m.$async);const C=u.scopeValue("root",{ref:v});return l(c,(0,r._)`${C}.validate`,v,v.$async)}function b(C){const R=i(c,C);l(c,R,C,C.$async)}function k(C){const R=u.scopeValue("schema",y.code.source===!0?{ref:C,code:(0,r.stringify)(C)}:{ref:C}),I=u.name("valid"),j=c.subschema({schema:C,dataTypes:[],schemaPath:r.nil,topSchemaRef:R,errSchemaPath:f},I);c.mergeEvaluated(j),c.ok(I)}}};function i(c,u){const{gen:f}=c;return u.validate?f.scopeValue("validate",{ref:u.validate}):(0,r._)`${f.scopeValue("wrapper",{ref:u})}.validate`}kn.getValidate=i;function l(c,u,f,p){const{gen:h,it:m}=c,{allErrors:_,schemaEnv:y,opts:w}=m,v=w.passContext?n.default.this:r.nil;p?g():S();function g(){if(!y.$async)throw new Error("async schema referenced by sync schema");const C=h.let("valid");h.try(()=>{h.code((0,r._)`await ${(0,t.callValidateCode)(c,u,v)}`),k(u),_||h.assign(C,!0)},R=>{h.if((0,r._)`!(${R} instanceof ${m.ValidationError})`,()=>h.throw(R)),b(R),_||h.assign(C,!1)}),c.ok(C)}function S(){c.result((0,t.callValidateCode)(c,u,v),()=>k(u),()=>b(u))}function b(C){const R=(0,r._)`${C}.errors`;h.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${R} : ${n.default.vErrors}.concat(${R})`),h.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function k(C){var R;if(!m.opts.unevaluated)return;const I=(R=f?.validate)===null||R===void 0?void 0:R.evaluated;if(m.props!==!0)if(I&&!I.dynamicProps)I.props!==void 0&&(m.props=s.mergeEvaluated.props(h,I.props,m.props));else{const j=h.var("props",(0,r._)`${C}.evaluated.props`);m.props=s.mergeEvaluated.props(h,j,m.props,r.Name)}if(m.items!==!0)if(I&&!I.dynamicItems)I.items!==void 0&&(m.items=s.mergeEvaluated.items(h,I.items,m.items));else{const j=h.var("items",(0,r._)`${C}.evaluated.items`);m.items=s.mergeEvaluated.items(h,j,m.items,r.Name)}}}return kn.callRef=l,kn.default=a,kn}var Lf;function ub(){if(Lf)return ei;Lf=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=lb(),t=cb(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return ei.default=r,ei}var ri={},ni={},jf;function db(){if(jf)return ni;jf=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=Ne(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:s,schemaCode:a})=>(0,e.str)`must be ${r[s].okStr} ${a}`,params:({keyword:s,schemaCode:a})=>(0,e._)`{comparison: ${r[s].okStr}, limit: ${a}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(s){const{keyword:a,data:i,schemaCode:l}=s;s.fail$data((0,e._)`${i} ${r[a].fail} ${l} || isNaN(${i})`)}};return ni.default=o,ni}var oi={},Df;function pb(){if(Df)return oi;Df=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=Ne(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,e._)`{multipleOf: ${n}}`},code(n){const{gen:o,data:s,schemaCode:a,it:i}=n,l=i.opts.multipleOfPrecision,c=o.let("res"),u=l?(0,e._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,e._)`${c} !== parseInt(${c})`;n.fail$data((0,e._)`(${a} === 0 || (${c} = ${s}/${a}, ${u}))`)}};return oi.default=r,oi}var si={},ai={},Uf;function fb(){if(Uf)return ai;Uf=1,Object.defineProperty(ai,"__esModule",{value:!0});function e(t){const r=t.length;let n=0,o=0,s;for(;o<r;)n++,s=t.charCodeAt(o++),s>=55296&&s<=56319&&o<r&&(s=t.charCodeAt(o),(s&64512)===56320&&o++);return n}return ai.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',ai}var zf;function hb(){if(zf)return si;zf=1,Object.defineProperty(si,"__esModule",{value:!0});const e=Ne(),t=Ze(),r=fb(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:a}){const i=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:a,data:i,schemaCode:l,it:c}=s,u=a==="maxLength"?e.operators.GT:e.operators.LT,f=c.opts.unicode===!1?(0,e._)`${i}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${i})`;s.fail$data((0,e._)`${f} ${u} ${l}`)}};return si.default=o,si}var ii={},Zf;function mb(){if(Zf)return ii;Zf=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=Pr(),t=Ze(),r=Ne(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,r.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,r._)`{pattern: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:f}=s,p=f.opts.unicodeRegExp?"u":"";if(l){const{regExp:h}=f.opts.code,m=h.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(a,h),_=a.let("valid");a.try(()=>a.assign(_,(0,r._)`${m}(${u}, ${p}).test(${i})`),()=>a.assign(_,!1)),s.fail$data((0,r._)`!${_}`)}else{const h=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${h}.test(${i})`)}}};return ii.default=o,ii}var li={},Ff;function gb(){if(Ff)return li;Ff=1,Object.defineProperty(li,"__esModule",{value:!0});const e=Ne(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${i} ${a}`)}};return li.default=r,li}var ci={},Vf;function yb(){if(Vf)return ci;Vf=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=Pr(),t=Ne(),r=Ze(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:a,schema:i,schemaCode:l,data:c,$data:u,it:f}=s,{opts:p}=f;if(!u&&i.length===0)return;const h=i.length>=p.loopRequired;if(f.allErrors?m():_(),p.strictRequired){const v=s.parentSchema.properties,{definedProperties:g}=s.it;for(const S of i)if(v?.[S]===void 0&&!g.has(S)){const b=f.schemaEnv.baseId+f.errSchemaPath,k=`required property "${S}" is not defined at "${b}" (strictRequired)`;(0,r.checkStrictMode)(f,k,f.opts.strictRequired)}}function m(){if(h||u)s.block$data(t.nil,y);else for(const v of i)(0,e.checkReportMissingProp)(s,v)}function _(){const v=a.let("missing");if(h||u){const g=a.let("valid",!0);s.block$data(g,()=>w(v,g)),s.ok(g)}else a.if((0,e.checkMissingProp)(s,i,v)),(0,e.reportMissingProp)(s,v),a.else()}function y(){a.forOf("prop",l,v=>{s.setParams({missingProperty:v}),a.if((0,e.noPropertyInData)(a,c,v,p.ownProperties),()=>s.error())})}function w(v,g){s.setParams({missingProperty:v}),a.forOf(v,l,()=>{a.assign(g,(0,e.propertyInData)(a,c,v,p.ownProperties)),a.if((0,t.not)(g),()=>{s.error(),a.break()})},t.nil)}}};return ci.default=o,ci}var ui={},Hf;function vb(){if(Hf)return ui;Hf=1,Object.defineProperty(ui,"__esModule",{value:!0});const e=Ne(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${i} ${a}`)}};return ui.default=r,ui}var di={},pi={},Bf;function Tc(){if(Bf)return pi;Bf=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=Tf();return e.code='require("ajv/dist/runtime/equal").default',pi.default=e,pi}var Wf;function _b(){if(Wf)return di;Wf=1,Object.defineProperty(di,"__esModule",{value:!0});const e=Ba(),t=Ne(),r=Ze(),n=Tc(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,t.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,t._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:l,$data:c,schema:u,parentSchema:f,schemaCode:p,it:h}=a;if(!c&&!u)return;const m=i.let("valid"),_=f.items?(0,e.getSchemaTypes)(f.items):[];a.block$data(m,y,(0,t._)`${p} === false`),a.ok(m);function y(){const S=i.let("i",(0,t._)`${l}.length`),b=i.let("j");a.setParams({i:S,j:b}),i.assign(m,!0),i.if((0,t._)`${S} > 1`,()=>(w()?v:g)(S,b))}function w(){return _.length>0&&!_.some(S=>S==="object"||S==="array")}function v(S,b){const k=i.name("item"),C=(0,e.checkDataTypes)(_,k,h.opts.strictNumbers,e.DataType.Wrong),R=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${S}--;`,()=>{i.let(k,(0,t._)`${l}[${S}]`),i.if(C,(0,t._)`continue`),_.length>1&&i.if((0,t._)`typeof ${k} == "string"`,(0,t._)`${k} += "_"`),i.if((0,t._)`typeof ${R}[${k}] == "number"`,()=>{i.assign(b,(0,t._)`${R}[${k}]`),a.error(),i.assign(m,!1).break()}).code((0,t._)`${R}[${k}] = ${S}`)})}function g(S,b){const k=(0,r.useFunc)(i,n.default),C=i.name("outer");i.label(C).for((0,t._)`;${S}--;`,()=>i.for((0,t._)`${b} = ${S}; ${b}--;`,()=>i.if((0,t._)`${k}(${l}[${S}], ${l}[${b}])`,()=>{a.error(),i.assign(m,!1).break(C)})))}}};return di.default=s,di}var fi={},Gf;function wb(){if(Gf)return fi;Gf=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=Ne(),t=Ze(),r=Tc(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:s})=>(0,e._)`{allowedValue: ${s}}`},code(s){const{gen:a,data:i,$data:l,schemaCode:c,schema:u}=s;l||u&&typeof u=="object"?s.fail$data((0,e._)`!${(0,t.useFunc)(a,r.default)}(${i}, ${c})`):s.fail((0,e._)`${u} !== ${i}`)}};return fi.default=o,fi}var hi={},Jf;function bb(){if(Jf)return hi;Jf=1,Object.defineProperty(hi,"__esModule",{value:!0});const e=Ne(),t=Ze(),r=Tc(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:f}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=f.opts.loopEnum;let h;const m=()=>h??(h=(0,t.useFunc)(a,r.default));let _;if(p||l)_=a.let("valid"),s.block$data(_,y);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const v=a.const("vSchema",u);_=(0,e.or)(...c.map((g,S)=>w(v,S)))}s.pass(_);function y(){a.assign(_,!1),a.forOf("v",u,v=>a.if((0,e._)`${m()}(${i}, ${v})`,()=>a.assign(_,!0).break()))}function w(v,g){const S=c[g];return typeof S=="object"&&S!==null?(0,e._)`${m()}(${i}, ${v}[${g}])`:(0,e._)`${i} === ${S}`}}};return hi.default=o,hi}var Kf;function Tb(){if(Kf)return ri;Kf=1,Object.defineProperty(ri,"__esModule",{value:!0});const e=db(),t=pb(),r=hb(),n=mb(),o=gb(),s=yb(),a=vb(),i=_b(),l=wb(),c=bb(),u=[e.default,t.default,r.default,n.default,o.default,s.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return ri.default=u,ri}var mi={},bo={},Yf;function Qf(){if(Yf)return bo;Yf=1,Object.defineProperty(bo,"__esModule",{value:!0}),bo.validateAdditionalItems=void 0;const e=Ne(),t=Ze(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:a,it:i}=s,{items:l}=a;if(!Array.isArray(l)){(0,t.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,a){const{gen:i,schema:l,data:c,keyword:u,it:f}=s;f.items=!0;const p=i.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:a.length}),s.pass((0,e._)`${p} <= ${a.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(f,l)){const m=i.var("valid",(0,e._)`${p} <= ${a.length}`);i.if((0,e.not)(m),()=>h(m)),s.ok(m)}function h(m){i.forRange("i",a.length,p,_=>{s.subschema({keyword:u,dataProp:_,dataPropType:t.Type.Num},m),f.allErrors||i.if((0,e.not)(m),()=>i.break())})}}return bo.validateAdditionalItems=o,bo.default=n,bo}var gi={},To={},Xf;function eh(){if(Xf)return To;Xf=1,Object.defineProperty(To,"__esModule",{value:!0}),To.validateTuple=void 0;const e=Ne(),t=Ze(),r=Pr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:a,it:i}=s;if(Array.isArray(a))return o(s,"additionalItems",a);i.items=!0,!(0,t.alwaysValidSchema)(i,a)&&s.ok((0,r.validateArray)(s))}};function o(s,a,i=s.schema){const{gen:l,parentSchema:c,data:u,keyword:f,it:p}=s;_(c),p.opts.unevaluated&&i.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,i.length,p.items));const h=l.name("valid"),m=l.const("len",(0,e._)`${u}.length`);i.forEach((y,w)=>{(0,t.alwaysValidSchema)(p,y)||(l.if((0,e._)`${m} > ${w}`,()=>s.subschema({keyword:f,schemaProp:w,dataProp:w},h)),s.ok(h))});function _(y){const{opts:w,errSchemaPath:v}=p,g=i.length,S=g===y.minItems&&(g===y.maxItems||y[a]===!1);if(w.strictTuples&&!S){const b=`"${f}" is ${g}-tuple, but minItems or maxItems/${a} are not specified or different at path "${v}"`;(0,t.checkStrictMode)(p,b,w.strictTuples)}}}return To.validateTuple=o,To.default=n,To}var th;function kb(){if(th)return gi;th=1,Object.defineProperty(gi,"__esModule",{value:!0});const e=eh(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return gi.default=t,gi}var yi={},rh;function Sb(){if(rh)return yi;rh=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=Ne(),t=Ze(),r=Pr(),n=Qf(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,e.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,e._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:l,it:c}=a,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return yi.default=s,yi}var vi={},nh;function Cb(){if(nh)return vi;nh=1,Object.defineProperty(vi,"__esModule",{value:!0});const e=Ne(),t=Ze(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:a,parentSchema:i,data:l,it:c}=o;let u,f;const{minContains:p,maxContains:h}=i;c.opts.next?(u=p===void 0?1:p,f=h):u=1;const m=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:f}),f===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(f!==void 0&&u>f){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,a)){let g=(0,e._)`${m} >= ${u}`;f!==void 0&&(g=(0,e._)`${g} && ${m} <= ${f}`),o.pass(g);return}c.items=!0;const _=s.name("valid");f===void 0&&u===1?w(_,()=>s.if(_,()=>s.break())):u===0?(s.let(_,!0),f!==void 0&&s.if((0,e._)`${l}.length > 0`,y)):(s.let(_,!1),y()),o.result(_,()=>o.reset());function y(){const g=s.name("_valid"),S=s.let("count",0);w(g,()=>s.if(g,()=>v(S)))}function w(g,S){s.forRange("i",0,m,b=>{o.subschema({keyword:"contains",dataProp:b,dataPropType:t.Type.Num,compositeRule:!0},g),S()})}function v(g){s.code((0,e._)`${g}++`),f===void 0?s.if((0,e._)`${g} >= ${u}`,()=>s.assign(_,!0).break()):(s.if((0,e._)`${g} > ${f}`,()=>s.assign(_,!1).break()),u===1?s.assign(_,!0):s.if((0,e._)`${g} >= ${u}`,()=>s.assign(_,!0)))}}};return vi.default=n,vi}var kc={},oh;function Ib(){return oh||(oh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Ne(),r=Ze(),n=Pr();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const f=c===1?"property":"properties";return(0,t.str)`must have ${f} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:f}})=>(0,t._)`{property: ${l},
1
+ (function(Ee,Wn){typeof exports=="object"&&typeof module<"u"?Wn(exports):typeof define=="function"&&define.amd?define(["exports"],Wn):(Ee=typeof globalThis<"u"?globalThis:Ee||self,Wn(Ee.WebMCP={}))})(this,(function(Ee){"use strict";function Wn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ja={exports:{}},mc={},an={},Gn={},gc={},yc={},vc={},af;function Wa(){return af||(af=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends t{constructor(v){if(super(),!e.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}e.Name=r;class n extends t{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((y,S)=>`${y}${S}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((y,S)=>(S instanceof r&&(y[S.str]=(y[S.str]||0)+1),y),{})}}e._Code=n,e.nil=new n("");function o(w,...v){const y=[w[0]];let S=0;for(;S<v.length;)i(y,v[S]),y.push(w[++S]);return new n(y)}e._=o;const s=new n("+");function a(w,...v){const y=[h(w[0])];let S=0;for(;S<v.length;)y.push(s),i(y,v[S]),y.push(s,h(w[++S]));return l(y),new n(y)}e.str=a;function i(w,v){v instanceof n?w.push(...v._items):v instanceof r?w.push(v):w.push(f(v))}e.addCodeArg=i;function l(w){let v=1;for(;v<w.length-1;){if(w[v]===s){const y=c(w[v-1],w[v+1]);if(y!==void 0){w.splice(v-1,3,y);continue}w[v++]="+"}v++}}function c(w,v){if(v==='""')return w;if(w==='""')return v;if(typeof w=="string")return v instanceof r||w[w.length-1]!=='"'?void 0:typeof v!="string"?`${w.slice(0,-1)}${v}"`:v[0]==='"'?w.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(w instanceof r))return`"${w}${v.slice(1)}`}function u(w,v){return v.emptyStr()?w:w.emptyStr()?v:a`${w}${v}`}e.strConcat=u;function f(w){return typeof w=="number"||typeof w=="boolean"||w===null?w:h(Array.isArray(w)?w.join(","):w)}function p(w){return new n(h(w))}e.stringify=p;function h(w){return JSON.stringify(w).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function m(w){return typeof w=="string"&&e.IDENTIFIER.test(w)?new n(`.${w}`):o`[${w}]`}e.getProperty=m;function _(w){if(typeof w=="string"&&e.IDENTIFIER.test(w))return new n(`${w}`);throw new Error(`CodeGen: invalid export name: ${w}, use explicit $id name mapping`)}e.getEsmExportName=_;function g(w){return new n(w.toString())}e.regexpCode=g})(vc)),vc}var _c={},lf;function cf(){return lf||(lf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=Wa();class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var n;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(n||(e.UsedValueState=n={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof t.Name?c:this.name(c)}name(c){return new t.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,f;if(!((f=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||f===void 0)&&f.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}e.Scope=o;class s extends t.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:f}){this.value=c,this.scopePath=(0,t._)`.${new t.Name(u)}[${f}]`}}e.ValueScopeName=s;const a=(0,t._)`\n`;class i extends o{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?a:t.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var f;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(c),{prefix:h}=p,m=(f=u.key)!==null&&f!==void 0?f:u.ref;let _=this._values[h];if(_){const v=_.get(m);if(v)return v}else _=this._values[h]=new Map;_.set(m,p);const g=this._scope[h]||(this._scope[h]=[]),w=g.length;return g[w]=u.ref,p.setValue(u,{property:h,itemIndex:w}),p}getValue(c,u){const f=this._values[c];if(f)return f.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,t._)`${c}${f.scopePath}`})}scopeCode(c=this._values,u,f){return this._reduceValues(c,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},u,f)}_reduceValues(c,u,f={},p){let h=t.nil;for(const m in c){const _=c[m];if(!_)continue;const g=f[m]=f[m]||new Map;_.forEach(w=>{if(g.has(w))return;g.set(w,n.Started);let v=u(w);if(v){const y=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${y} ${w} = ${v};${this.opts._n}`}else if(v=p?.(w))h=(0,t._)`${h}${v}${this.opts._n}`;else throw new r(w);g.set(w,n.Completed)})}return h}}e.ValueScope=i})(_c)),_c}var uf;function Ue(){return uf||(uf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=Wa(),r=cf();var n=Wa();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}});var o=cf();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(I,M){return this}}class a extends s{constructor(I,M,B){super(),this.varKind=I,this.name=M,this.rhs=B}render({es5:I,_n:M}){const B=I?r.varKinds.var:this.varKind,oe=this.rhs===void 0?"":` = ${this.rhs}`;return`${B} ${this.name}${oe};`+M}optimizeNames(I,M){if(I[this.name.str])return this.rhs&&(this.rhs=H(this.rhs,I,M)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(I,M,B){super(),this.lhs=I,this.rhs=M,this.sideEffects=B}render({_n:I}){return`${this.lhs} = ${this.rhs};`+I}optimizeNames(I,M){if(!(this.lhs instanceof t.Name&&!I[this.lhs.str]&&!this.sideEffects))return this.rhs=H(this.rhs,I,M),this}get names(){const I=this.lhs instanceof t.Name?{}:{...this.lhs.names};return z(I,this.rhs)}}class l extends i{constructor(I,M,B,oe){super(I,B,oe),this.op=M}render({_n:I}){return`${this.lhs} ${this.op}= ${this.rhs};`+I}}class c extends s{constructor(I){super(),this.label=I,this.names={}}render({_n:I}){return`${this.label}:`+I}}class u extends s{constructor(I){super(),this.label=I,this.names={}}render({_n:I}){return`break${this.label?` ${this.label}`:""};`+I}}class f extends s{constructor(I){super(),this.error=I}render({_n:I}){return`throw ${this.error};`+I}get names(){return this.error.names}}class p extends s{constructor(I){super(),this.code=I}render({_n:I}){return`${this.code};`+I}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(I,M){return this.code=H(this.code,I,M),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(I=[]){super(),this.nodes=I}render(I){return this.nodes.reduce((M,B)=>M+B.render(I),"")}optimizeNodes(){const{nodes:I}=this;let M=I.length;for(;M--;){const B=I[M].optimizeNodes();Array.isArray(B)?I.splice(M,1,...B):B?I[M]=B:I.splice(M,1)}return I.length>0?this:void 0}optimizeNames(I,M){const{nodes:B}=this;let oe=B.length;for(;oe--;){const ne=B[oe];ne.optimizeNames(I,M)||(ee(I,ne.names),B.splice(oe,1))}return B.length>0?this:void 0}get names(){return this.nodes.reduce((I,M)=>q(I,M.names),{})}}class m extends h{render(I){return"{"+I._n+super.render(I)+"}"+I._n}}class _ extends h{}class g extends m{}g.kind="else";class w extends m{constructor(I,M){super(M),this.condition=I}render(I){let M=`if(${this.condition})`+super.render(I);return this.else&&(M+="else "+this.else.render(I)),M}optimizeNodes(){super.optimizeNodes();const I=this.condition;if(I===!0)return this.nodes;let M=this.else;if(M){const B=M.optimizeNodes();M=this.else=Array.isArray(B)?new g(B):B}if(M)return I===!1?M instanceof w?M:M.nodes:this.nodes.length?this:new w(re(I),M instanceof w?[M]:M.nodes);if(!(I===!1||!this.nodes.length))return this}optimizeNames(I,M){var B;if(this.else=(B=this.else)===null||B===void 0?void 0:B.optimizeNames(I,M),!!(super.optimizeNames(I,M)||this.else))return this.condition=H(this.condition,I,M),this}get names(){const I=super.names;return z(I,this.condition),this.else&&q(I,this.else.names),I}}w.kind="if";class v extends m{}v.kind="for";class y extends v{constructor(I){super(),this.iteration=I}render(I){return`for(${this.iteration})`+super.render(I)}optimizeNames(I,M){if(super.optimizeNames(I,M))return this.iteration=H(this.iteration,I,M),this}get names(){return q(super.names,this.iteration.names)}}class S extends v{constructor(I,M,B,oe){super(),this.varKind=I,this.name=M,this.from=B,this.to=oe}render(I){const M=I.es5?r.varKinds.var:this.varKind,{name:B,from:oe,to:ne}=this;return`for(${M} ${B}=${oe}; ${B}<${ne}; ${B}++)`+super.render(I)}get names(){const I=z(super.names,this.from);return z(I,this.to)}}class b extends v{constructor(I,M,B,oe){super(),this.loop=I,this.varKind=M,this.name=B,this.iterable=oe}render(I){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(I)}optimizeNames(I,M){if(super.optimizeNames(I,M))return this.iterable=H(this.iterable,I,M),this}get names(){return q(super.names,this.iterable.names)}}class T extends m{constructor(I,M,B){super(),this.name=I,this.args=M,this.async=B}render(I){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(I)}}T.kind="func";class x extends h{render(I){return"return "+super.render(I)}}x.kind="return";class R extends m{render(I){let M="try"+super.render(I);return this.catch&&(M+=this.catch.render(I)),this.finally&&(M+=this.finally.render(I)),M}optimizeNodes(){var I,M;return super.optimizeNodes(),(I=this.catch)===null||I===void 0||I.optimizeNodes(),(M=this.finally)===null||M===void 0||M.optimizeNodes(),this}optimizeNames(I,M){var B,oe;return super.optimizeNames(I,M),(B=this.catch)===null||B===void 0||B.optimizeNames(I,M),(oe=this.finally)===null||oe===void 0||oe.optimizeNames(I,M),this}get names(){const I=super.names;return this.catch&&q(I,this.catch.names),this.finally&&q(I,this.finally.names),I}}class C extends m{constructor(I){super(),this.error=I}render(I){return`catch(${this.error})`+super.render(I)}}C.kind="catch";class L extends m{render(I){return"finally"+super.render(I)}}L.kind="finally";class O{constructor(I,M={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...M,_n:M.lines?`
2
+ `:""},this._extScope=I,this._scope=new r.Scope({parent:I}),this._nodes=[new _]}toString(){return this._root.render(this.opts)}name(I){return this._scope.name(I)}scopeName(I){return this._extScope.name(I)}scopeValue(I,M){const B=this._extScope.value(I,M);return(this._values[B.prefix]||(this._values[B.prefix]=new Set)).add(B),B}getScopeValue(I,M){return this._extScope.getValue(I,M)}scopeRefs(I){return this._extScope.scopeRefs(I,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(I,M,B,oe){const ne=this._scope.toName(M);return B!==void 0&&oe&&(this._constants[ne.str]=B),this._leafNode(new a(I,ne,B)),ne}const(I,M,B){return this._def(r.varKinds.const,I,M,B)}let(I,M,B){return this._def(r.varKinds.let,I,M,B)}var(I,M,B){return this._def(r.varKinds.var,I,M,B)}assign(I,M,B){return this._leafNode(new i(I,M,B))}add(I,M){return this._leafNode(new l(I,e.operators.ADD,M))}code(I){return typeof I=="function"?I():I!==t.nil&&this._leafNode(new p(I)),this}object(...I){const M=["{"];for(const[B,oe]of I)M.length>1&&M.push(","),M.push(B),(B!==oe||this.opts.es5)&&(M.push(":"),(0,t.addCodeArg)(M,oe));return M.push("}"),new t._Code(M)}if(I,M,B){if(this._blockNode(new w(I)),M&&B)this.code(M).else().code(B).endIf();else if(M)this.code(M).endIf();else if(B)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(I){return this._elseNode(new w(I))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(w,g)}_for(I,M){return this._blockNode(I),M&&this.code(M).endFor(),this}for(I,M){return this._for(new y(I),M)}forRange(I,M,B,oe,ne=this.opts.es5?r.varKinds.var:r.varKinds.let){const be=this._scope.toName(I);return this._for(new S(ne,be,M,B),()=>oe(be))}forOf(I,M,B,oe=r.varKinds.const){const ne=this._scope.toName(I);if(this.opts.es5){const be=M instanceof t.Name?M:this.var("_arr",M);return this.forRange("_i",0,(0,t._)`${be}.length`,W=>{this.var(ne,(0,t._)`${be}[${W}]`),B(ne)})}return this._for(new b("of",oe,ne,M),()=>B(ne))}forIn(I,M,B,oe=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(I,(0,t._)`Object.keys(${M})`,B);const ne=this._scope.toName(I);return this._for(new b("in",oe,ne,M),()=>B(ne))}endFor(){return this._endBlockNode(v)}label(I){return this._leafNode(new c(I))}break(I){return this._leafNode(new u(I))}return(I){const M=new x;if(this._blockNode(M),this.code(I),M.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(x)}try(I,M,B){if(!M&&!B)throw new Error('CodeGen: "try" without "catch" and "finally"');const oe=new R;if(this._blockNode(oe),this.code(I),M){const ne=this.name("e");this._currNode=oe.catch=new C(ne),M(ne)}return B&&(this._currNode=oe.finally=new L,this.code(B)),this._endBlockNode(C,L)}throw(I){return this._leafNode(new f(I))}block(I,M){return this._blockStarts.push(this._nodes.length),I&&this.code(I).endBlock(M),this}endBlock(I){const M=this._blockStarts.pop();if(M===void 0)throw new Error("CodeGen: not in self-balancing block");const B=this._nodes.length-M;if(B<0||I!==void 0&&B!==I)throw new Error(`CodeGen: wrong number of nodes: ${B} vs ${I} expected`);return this._nodes.length=M,this}func(I,M=t.nil,B,oe){return this._blockNode(new T(I,M,B)),oe&&this.code(oe).endFunc(),this}endFunc(){return this._endBlockNode(T)}optimize(I=1){for(;I-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(I){return this._currNode.nodes.push(I),this}_blockNode(I){this._currNode.nodes.push(I),this._nodes.push(I)}_endBlockNode(I,M){const B=this._currNode;if(B instanceof I||M&&B instanceof M)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${M?`${I.kind}/${M.kind}`:I.kind}"`)}_elseNode(I){const M=this._currNode;if(!(M instanceof w))throw new Error('CodeGen: "else" without "if"');return this._currNode=M.else=I,this}get _root(){return this._nodes[0]}get _currNode(){const I=this._nodes;return I[I.length-1]}set _currNode(I){const M=this._nodes;M[M.length-1]=I}}e.CodeGen=O;function q(Z,I){for(const M in I)Z[M]=(Z[M]||0)+(I[M]||0);return Z}function z(Z,I){return I instanceof t._CodeOrName?q(Z,I.names):Z}function H(Z,I,M){if(Z instanceof t.Name)return B(Z);if(!oe(Z))return Z;return new t._Code(Z._items.reduce((ne,be)=>(be instanceof t.Name&&(be=B(be)),be instanceof t._Code?ne.push(...be._items):ne.push(be),ne),[]));function B(ne){const be=M[ne.str];return be===void 0||I[ne.str]!==1?ne:(delete I[ne.str],be)}function oe(ne){return ne instanceof t._Code&&ne._items.some(be=>be instanceof t.Name&&I[be.str]===1&&M[be.str]!==void 0)}}function ee(Z,I){for(const M in I)Z[M]=(Z[M]||0)-(I[M]||0)}function re(Z){return typeof Z=="boolean"||typeof Z=="number"||Z===null?!Z:(0,t._)`!${U(Z)}`}e.not=re;const X=E(e.operators.AND);function V(...Z){return Z.reduce(X)}e.and=V;const ie=E(e.operators.OR);function D(...Z){return Z.reduce(ie)}e.or=D;function E(Z){return(I,M)=>I===t.nil?M:M===t.nil?I:(0,t._)`${U(I)} ${Z} ${U(M)}`}function U(Z){return Z instanceof t.Name?Z:(0,t._)`(${Z})`}})(yc)),yc}var ze={},df;function Ge(){if(df)return ze;df=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.checkStrictMode=ze.getErrorPath=ze.Type=ze.useFunc=ze.setEvaluated=ze.evaluatedPropsToName=ze.mergeEvaluated=ze.eachItem=ze.unescapeJsonPointer=ze.escapeJsonPointer=ze.escapeFragment=ze.unescapeFragment=ze.schemaRefOrVal=ze.schemaHasRulesButRef=ze.schemaHasRules=ze.checkUnknownRules=ze.alwaysValidSchema=ze.toHash=void 0;const e=Ue(),t=Wa();function r(b){const T={};for(const x of b)T[x]=!0;return T}ze.toHash=r;function n(b,T){return typeof T=="boolean"?T:Object.keys(T).length===0?!0:(o(b,T),!s(T,b.self.RULES.all))}ze.alwaysValidSchema=n;function o(b,T=b.schema){const{opts:x,self:R}=b;if(!x.strictSchema||typeof T=="boolean")return;const C=R.RULES.keywords;for(const L in T)C[L]||S(b,`unknown keyword: "${L}"`)}ze.checkUnknownRules=o;function s(b,T){if(typeof b=="boolean")return!b;for(const x in b)if(T[x])return!0;return!1}ze.schemaHasRules=s;function a(b,T){if(typeof b=="boolean")return!b;for(const x in b)if(x!=="$ref"&&T.all[x])return!0;return!1}ze.schemaHasRulesButRef=a;function i({topSchemaRef:b,schemaPath:T},x,R,C){if(!C){if(typeof x=="number"||typeof x=="boolean")return x;if(typeof x=="string")return(0,e._)`${x}`}return(0,e._)`${b}${T}${(0,e.getProperty)(R)}`}ze.schemaRefOrVal=i;function l(b){return f(decodeURIComponent(b))}ze.unescapeFragment=l;function c(b){return encodeURIComponent(u(b))}ze.escapeFragment=c;function u(b){return typeof b=="number"?`${b}`:b.replace(/~/g,"~0").replace(/\//g,"~1")}ze.escapeJsonPointer=u;function f(b){return b.replace(/~1/g,"/").replace(/~0/g,"~")}ze.unescapeJsonPointer=f;function p(b,T){if(Array.isArray(b))for(const x of b)T(x);else T(b)}ze.eachItem=p;function h({mergeNames:b,mergeToName:T,mergeValues:x,resultToName:R}){return(C,L,O,q)=>{const z=O===void 0?L:O instanceof e.Name?(L instanceof e.Name?b(C,L,O):T(C,L,O),O):L instanceof e.Name?(T(C,O,L),L):x(L,O);return q===e.Name&&!(z instanceof e.Name)?R(C,z):z}}ze.mergeEvaluated={props:h({mergeNames:(b,T,x)=>b.if((0,e._)`${x} !== true && ${T} !== undefined`,()=>{b.if((0,e._)`${T} === true`,()=>b.assign(x,!0),()=>b.assign(x,(0,e._)`${x} || {}`).code((0,e._)`Object.assign(${x}, ${T})`))}),mergeToName:(b,T,x)=>b.if((0,e._)`${x} !== true`,()=>{T===!0?b.assign(x,!0):(b.assign(x,(0,e._)`${x} || {}`),_(b,x,T))}),mergeValues:(b,T)=>b===!0?!0:{...b,...T},resultToName:m}),items:h({mergeNames:(b,T,x)=>b.if((0,e._)`${x} !== true && ${T} !== undefined`,()=>b.assign(x,(0,e._)`${T} === true ? true : ${x} > ${T} ? ${x} : ${T}`)),mergeToName:(b,T,x)=>b.if((0,e._)`${x} !== true`,()=>b.assign(x,T===!0?!0:(0,e._)`${x} > ${T} ? ${x} : ${T}`)),mergeValues:(b,T)=>b===!0?!0:Math.max(b,T),resultToName:(b,T)=>b.var("items",T)})};function m(b,T){if(T===!0)return b.var("props",!0);const x=b.var("props",(0,e._)`{}`);return T!==void 0&&_(b,x,T),x}ze.evaluatedPropsToName=m;function _(b,T,x){Object.keys(x).forEach(R=>b.assign((0,e._)`${T}${(0,e.getProperty)(R)}`,!0))}ze.setEvaluated=_;const g={};function w(b,T){return b.scopeValue("func",{ref:T,code:g[T.code]||(g[T.code]=new t._Code(T.code))})}ze.useFunc=w;var v;(function(b){b[b.Num=0]="Num",b[b.Str=1]="Str"})(v||(ze.Type=v={}));function y(b,T,x){if(b instanceof e.Name){const R=T===v.Num;return x?R?(0,e._)`"[" + ${b} + "]"`:(0,e._)`"['" + ${b} + "']"`:R?(0,e._)`"/" + ${b}`:(0,e._)`"/" + ${b}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return x?(0,e.getProperty)(b).toString():"/"+u(b)}ze.getErrorPath=y;function S(b,T,x=b.opts.strictSchema){if(x){if(T=`strict mode: ${T}`,x===!0)throw new Error(T);b.self.logger.warn(T)}}return ze.checkStrictMode=S,ze}var Ga={},pf;function Cn(){if(pf)return Ga;pf=1,Object.defineProperty(Ga,"__esModule",{value:!0});const e=Ue(),t={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};return Ga.default=t,Ga}var ff;function Ka(){return ff||(ff=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=Ue(),r=Ge(),n=Cn();e.keywordError={message:({keyword:g})=>(0,t.str)`must pass "${g}" keyword validation`},e.keyword$DataError={message:({keyword:g,schemaType:w})=>w?(0,t.str)`"${g}" keyword must be ${w} ($data)`:(0,t.str)`"${g}" keyword is invalid ($data)`};function o(g,w=e.keywordError,v,y){const{it:S}=g,{gen:b,compositeRule:T,allErrors:x}=S,R=f(g,w,v);y??(T||x)?l(b,R):c(S,(0,t._)`[${R}]`)}e.reportError=o;function s(g,w=e.keywordError,v){const{it:y}=g,{gen:S,compositeRule:b,allErrors:T}=y,x=f(g,w,v);l(S,x),b||T||c(y,n.default.vErrors)}e.reportExtraError=s;function a(g,w){g.assign(n.default.errors,w),g.if((0,t._)`${n.default.vErrors} !== null`,()=>g.if(w,()=>g.assign((0,t._)`${n.default.vErrors}.length`,w),()=>g.assign(n.default.vErrors,null)))}e.resetErrorsCount=a;function i({gen:g,keyword:w,schemaValue:v,data:y,errsCount:S,it:b}){if(S===void 0)throw new Error("ajv implementation error");const T=g.name("err");g.forRange("i",S,n.default.errors,x=>{g.const(T,(0,t._)`${n.default.vErrors}[${x}]`),g.if((0,t._)`${T}.instancePath === undefined`,()=>g.assign((0,t._)`${T}.instancePath`,(0,t.strConcat)(n.default.instancePath,b.errorPath))),g.assign((0,t._)`${T}.schemaPath`,(0,t.str)`${b.errSchemaPath}/${w}`),b.opts.verbose&&(g.assign((0,t._)`${T}.schema`,v),g.assign((0,t._)`${T}.data`,y))})}e.extendErrors=i;function l(g,w){const v=g.const("err",w);g.if((0,t._)`${n.default.vErrors} === null`,()=>g.assign(n.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${n.default.vErrors}.push(${v})`),g.code((0,t._)`${n.default.errors}++`)}function c(g,w){const{gen:v,validateName:y,schemaEnv:S}=g;S.$async?v.throw((0,t._)`new ${g.ValidationError}(${w})`):(v.assign((0,t._)`${y}.errors`,w),v.return(!1))}const u={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function f(g,w,v){const{createErrors:y}=g.it;return y===!1?(0,t._)`{}`:p(g,w,v)}function p(g,w,v={}){const{gen:y,it:S}=g,b=[h(S,v),m(g,v)];return _(g,w,b),y.object(...b)}function h({errorPath:g},{instancePath:w}){const v=w?(0,t.str)`${g}${(0,r.getErrorPath)(w,r.Type.Str)}`:g;return[n.default.instancePath,(0,t.strConcat)(n.default.instancePath,v)]}function m({keyword:g,it:{errSchemaPath:w}},{schemaPath:v,parentSchema:y}){let S=y?w:(0,t.str)`${w}/${g}`;return v&&(S=(0,t.str)`${S}${(0,r.getErrorPath)(v,r.Type.Str)}`),[u.schemaPath,S]}function _(g,{params:w,message:v},y){const{keyword:S,data:b,schemaValue:T,it:x}=g,{opts:R,propertyName:C,topSchemaRef:L,schemaPath:O}=x;y.push([u.keyword,S],[u.params,typeof w=="function"?w(g):w||(0,t._)`{}`]),R.messages&&y.push([u.message,typeof v=="function"?v(g):v]),R.verbose&&y.push([u.schema,T],[u.parentSchema,(0,t._)`${L}${O}`],[n.default.data,b]),C&&y.push([u.propertyName,C])}})(gc)),gc}var hf;function ib(){if(hf)return Gn;hf=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.boolOrEmptySchema=Gn.topBoolOrEmptySchema=void 0;const e=Ka(),t=Ue(),r=Cn(),n={message:"boolean schema is false"};function o(i){const{gen:l,schema:c,validateName:u}=i;c===!1?a(i,!1):typeof c=="object"&&c.$async===!0?l.return(r.default.data):(l.assign((0,t._)`${u}.errors`,null),l.return(!0))}Gn.topBoolOrEmptySchema=o;function s(i,l){const{gen:c,schema:u}=i;u===!1?(c.var(l,!1),a(i)):c.var(l,!0)}Gn.boolOrEmptySchema=s;function a(i,l){const{gen:c,data:u}=i,f={gen:c,keyword:"false schema",data:u,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:i};(0,e.reportError)(f,n,void 0,l)}return Gn}var qt={},Kn={},mf;function gf(){if(mf)return Kn;mf=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.getRules=Kn.isJSONType=void 0;const e=["string","number","integer","boolean","null","object","array"],t=new Set(e);function r(o){return typeof o=="string"&&t.has(o)}Kn.isJSONType=r;function n(){const o={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...o,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},o.number,o.string,o.array,o.object],post:{rules:[]},all:{},keywords:{}}}return Kn.getRules=n,Kn}var ln={},yf;function vf(){if(yf)return ln;yf=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.shouldUseRule=ln.shouldUseGroup=ln.schemaHasRulesForType=void 0;function e({schema:n,self:o},s){const a=o.RULES.types[s];return a&&a!==!0&&t(n,a)}ln.schemaHasRulesForType=e;function t(n,o){return o.rules.some(s=>r(n,s))}ln.shouldUseGroup=t;function r(n,o){var s;return n[o.keyword]!==void 0||((s=o.definition.implements)===null||s===void 0?void 0:s.some(a=>n[a]!==void 0))}return ln.shouldUseRule=r,ln}var _f;function Ya(){if(_f)return qt;_f=1,Object.defineProperty(qt,"__esModule",{value:!0}),qt.reportTypeError=qt.checkDataTypes=qt.checkDataType=qt.coerceAndCheckDataType=qt.getJSONTypes=qt.getSchemaTypes=qt.DataType=void 0;const e=gf(),t=vf(),r=Ka(),n=Ue(),o=Ge();var s;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(s||(qt.DataType=s={}));function a(v){const y=i(v.type);if(y.includes("null")){if(v.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!y.length&&v.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');v.nullable===!0&&y.push("null")}return y}qt.getSchemaTypes=a;function i(v){const y=Array.isArray(v)?v:v?[v]:[];if(y.every(e.isJSONType))return y;throw new Error("type must be JSONType or JSONType[]: "+y.join(","))}qt.getJSONTypes=i;function l(v,y){const{gen:S,data:b,opts:T}=v,x=u(y,T.coerceTypes),R=y.length>0&&!(x.length===0&&y.length===1&&(0,t.schemaHasRulesForType)(v,y[0]));if(R){const C=m(y,b,T.strictNumbers,s.Wrong);S.if(C,()=>{x.length?f(v,y,x):g(v)})}return R}qt.coerceAndCheckDataType=l;const c=new Set(["string","number","integer","boolean","null"]);function u(v,y){return y?v.filter(S=>c.has(S)||y==="array"&&S==="array"):[]}function f(v,y,S){const{gen:b,data:T,opts:x}=v,R=b.let("dataType",(0,n._)`typeof ${T}`),C=b.let("coerced",(0,n._)`undefined`);x.coerceTypes==="array"&&b.if((0,n._)`${R} == 'object' && Array.isArray(${T}) && ${T}.length == 1`,()=>b.assign(T,(0,n._)`${T}[0]`).assign(R,(0,n._)`typeof ${T}`).if(m(y,T,x.strictNumbers),()=>b.assign(C,T))),b.if((0,n._)`${C} !== undefined`);for(const O of S)(c.has(O)||O==="array"&&x.coerceTypes==="array")&&L(O);b.else(),g(v),b.endIf(),b.if((0,n._)`${C} !== undefined`,()=>{b.assign(T,C),p(v,C)});function L(O){switch(O){case"string":b.elseIf((0,n._)`${R} == "number" || ${R} == "boolean"`).assign(C,(0,n._)`"" + ${T}`).elseIf((0,n._)`${T} === null`).assign(C,(0,n._)`""`);return;case"number":b.elseIf((0,n._)`${R} == "boolean" || ${T} === null
3
+ || (${R} == "string" && ${T} && ${T} == +${T})`).assign(C,(0,n._)`+${T}`);return;case"integer":b.elseIf((0,n._)`${R} === "boolean" || ${T} === null
4
+ || (${R} === "string" && ${T} && ${T} == +${T} && !(${T} % 1))`).assign(C,(0,n._)`+${T}`);return;case"boolean":b.elseIf((0,n._)`${T} === "false" || ${T} === 0 || ${T} === null`).assign(C,!1).elseIf((0,n._)`${T} === "true" || ${T} === 1`).assign(C,!0);return;case"null":b.elseIf((0,n._)`${T} === "" || ${T} === 0 || ${T} === false`),b.assign(C,null);return;case"array":b.elseIf((0,n._)`${R} === "string" || ${R} === "number"
5
+ || ${R} === "boolean" || ${T} === null`).assign(C,(0,n._)`[${T}]`)}}}function p({gen:v,parentData:y,parentDataProperty:S},b){v.if((0,n._)`${y} !== undefined`,()=>v.assign((0,n._)`${y}[${S}]`,b))}function h(v,y,S,b=s.Correct){const T=b===s.Correct?n.operators.EQ:n.operators.NEQ;let x;switch(v){case"null":return(0,n._)`${y} ${T} null`;case"array":x=(0,n._)`Array.isArray(${y})`;break;case"object":x=(0,n._)`${y} && typeof ${y} == "object" && !Array.isArray(${y})`;break;case"integer":x=R((0,n._)`!(${y} % 1) && !isNaN(${y})`);break;case"number":x=R();break;default:return(0,n._)`typeof ${y} ${T} ${v}`}return b===s.Correct?x:(0,n.not)(x);function R(C=n.nil){return(0,n.and)((0,n._)`typeof ${y} == "number"`,C,S?(0,n._)`isFinite(${y})`:n.nil)}}qt.checkDataType=h;function m(v,y,S,b){if(v.length===1)return h(v[0],y,S,b);let T;const x=(0,o.toHash)(v);if(x.array&&x.object){const R=(0,n._)`typeof ${y} != "object"`;T=x.null?R:(0,n._)`!${y} || ${R}`,delete x.null,delete x.array,delete x.object}else T=n.nil;x.number&&delete x.integer;for(const R in x)T=(0,n.and)(T,h(R,y,S,b));return T}qt.checkDataTypes=m;const _={message:({schema:v})=>`must be ${v}`,params:({schema:v,schemaValue:y})=>typeof v=="string"?(0,n._)`{type: ${v}}`:(0,n._)`{type: ${y}}`};function g(v){const y=w(v);(0,r.reportError)(y,_)}qt.reportTypeError=g;function w(v){const{gen:y,data:S,schema:b}=v,T=(0,o.schemaRefOrVal)(v,b,"type");return{gen:y,keyword:"type",data:S,schema:b.type,schemaCode:T,schemaValue:T,parentSchema:b,params:{},it:v}}return qt}var ms={},wf;function lb(){if(wf)return ms;wf=1,Object.defineProperty(ms,"__esModule",{value:!0}),ms.assignDefaults=void 0;const e=Ue(),t=Ge();function r(o,s){const{properties:a,items:i}=o.schema;if(s==="object"&&a)for(const l in a)n(o,l,a[l].default);else s==="array"&&Array.isArray(i)&&i.forEach((l,c)=>n(o,c,l.default))}ms.assignDefaults=r;function n(o,s,a){const{gen:i,compositeRule:l,data:c,opts:u}=o;if(a===void 0)return;const f=(0,e._)`${c}${(0,e.getProperty)(s)}`;if(l){(0,t.checkStrictMode)(o,`default is ignored for: ${f}`);return}let p=(0,e._)`${f} === undefined`;u.useDefaults==="empty"&&(p=(0,e._)`${p} || ${f} === null || ${f} === ""`),i.if(p,(0,e._)`${f} = ${(0,e.stringify)(a)}`)}return ms}var Rr={},ot={},bf;function Pr(){if(bf)return ot;bf=1,Object.defineProperty(ot,"__esModule",{value:!0}),ot.validateUnion=ot.validateArray=ot.usePattern=ot.callValidateCode=ot.schemaProperties=ot.allSchemaProperties=ot.noPropertyInData=ot.propertyInData=ot.isOwnProperty=ot.hasPropFunc=ot.reportMissingProp=ot.checkMissingProp=ot.checkReportMissingProp=void 0;const e=Ue(),t=Ge(),r=Cn(),n=Ge();function o(v,y){const{gen:S,data:b,it:T}=v;S.if(u(S,b,y,T.opts.ownProperties),()=>{v.setParams({missingProperty:(0,e._)`${y}`},!0),v.error()})}ot.checkReportMissingProp=o;function s({gen:v,data:y,it:{opts:S}},b,T){return(0,e.or)(...b.map(x=>(0,e.and)(u(v,y,x,S.ownProperties),(0,e._)`${T} = ${x}`)))}ot.checkMissingProp=s;function a(v,y){v.setParams({missingProperty:y},!0),v.error()}ot.reportMissingProp=a;function i(v){return v.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,e._)`Object.prototype.hasOwnProperty`})}ot.hasPropFunc=i;function l(v,y,S){return(0,e._)`${i(v)}.call(${y}, ${S})`}ot.isOwnProperty=l;function c(v,y,S,b){const T=(0,e._)`${y}${(0,e.getProperty)(S)} !== undefined`;return b?(0,e._)`${T} && ${l(v,y,S)}`:T}ot.propertyInData=c;function u(v,y,S,b){const T=(0,e._)`${y}${(0,e.getProperty)(S)} === undefined`;return b?(0,e.or)(T,(0,e.not)(l(v,y,S))):T}ot.noPropertyInData=u;function f(v){return v?Object.keys(v).filter(y=>y!=="__proto__"):[]}ot.allSchemaProperties=f;function p(v,y){return f(y).filter(S=>!(0,t.alwaysValidSchema)(v,y[S]))}ot.schemaProperties=p;function h({schemaCode:v,data:y,it:{gen:S,topSchemaRef:b,schemaPath:T,errorPath:x},it:R},C,L,O){const q=O?(0,e._)`${v}, ${y}, ${b}${T}`:y,z=[[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,x)],[r.default.parentData,R.parentData],[r.default.parentDataProperty,R.parentDataProperty],[r.default.rootData,r.default.rootData]];R.opts.dynamicRef&&z.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);const H=(0,e._)`${q}, ${S.object(...z)}`;return L!==e.nil?(0,e._)`${C}.call(${L}, ${H})`:(0,e._)`${C}(${H})`}ot.callValidateCode=h;const m=(0,e._)`new RegExp`;function _({gen:v,it:{opts:y}},S){const b=y.unicodeRegExp?"u":"",{regExp:T}=y.code,x=T(S,b);return v.scopeValue("pattern",{key:x.toString(),ref:x,code:(0,e._)`${T.code==="new RegExp"?m:(0,n.useFunc)(v,T)}(${S}, ${b})`})}ot.usePattern=_;function g(v){const{gen:y,data:S,keyword:b,it:T}=v,x=y.name("valid");if(T.allErrors){const C=y.let("valid",!0);return R(()=>y.assign(C,!1)),C}return y.var(x,!0),R(()=>y.break()),x;function R(C){const L=y.const("len",(0,e._)`${S}.length`);y.forRange("i",0,L,O=>{v.subschema({keyword:b,dataProp:O,dataPropType:t.Type.Num},x),y.if((0,e.not)(x),C)})}}ot.validateArray=g;function w(v){const{gen:y,schema:S,keyword:b,it:T}=v;if(!Array.isArray(S))throw new Error("ajv implementation error");if(S.some(L=>(0,t.alwaysValidSchema)(T,L))&&!T.opts.unevaluated)return;const R=y.let("valid",!1),C=y.name("_valid");y.block(()=>S.forEach((L,O)=>{const q=v.subschema({keyword:b,schemaProp:O,compositeRule:!0},C);y.assign(R,(0,e._)`${R} || ${C}`),v.mergeValidEvaluated(q,C)||y.if((0,e.not)(R))})),v.result(R,()=>v.reset(),()=>v.error(!0))}return ot.validateUnion=w,ot}var kf;function cb(){if(kf)return Rr;kf=1,Object.defineProperty(Rr,"__esModule",{value:!0}),Rr.validateKeywordUsage=Rr.validSchemaType=Rr.funcKeywordCode=Rr.macroKeywordCode=void 0;const e=Ue(),t=Cn(),r=Pr(),n=Ka();function o(p,h){const{gen:m,keyword:_,schema:g,parentSchema:w,it:v}=p,y=h.macro.call(v.self,g,w,v),S=c(m,_,y);v.opts.validateSchema!==!1&&v.self.validateSchema(y,!0);const b=m.name("valid");p.subschema({schema:y,schemaPath:e.nil,errSchemaPath:`${v.errSchemaPath}/${_}`,topSchemaRef:S,compositeRule:!0},b),p.pass(b,()=>p.error(!0))}Rr.macroKeywordCode=o;function s(p,h){var m;const{gen:_,keyword:g,schema:w,parentSchema:v,$data:y,it:S}=p;l(S,h);const b=!y&&h.compile?h.compile.call(S.self,w,v,S):h.validate,T=c(_,g,b),x=_.let("valid");p.block$data(x,R),p.ok((m=h.valid)!==null&&m!==void 0?m:x);function R(){if(h.errors===!1)O(),h.modifying&&a(p),q(()=>p.error());else{const z=h.async?C():L();h.modifying&&a(p),q(()=>i(p,z))}}function C(){const z=_.let("ruleErrs",null);return _.try(()=>O((0,e._)`await `),H=>_.assign(x,!1).if((0,e._)`${H} instanceof ${S.ValidationError}`,()=>_.assign(z,(0,e._)`${H}.errors`),()=>_.throw(H))),z}function L(){const z=(0,e._)`${T}.errors`;return _.assign(z,null),O(e.nil),z}function O(z=h.async?(0,e._)`await `:e.nil){const H=S.opts.passContext?t.default.this:t.default.self,ee=!("compile"in h&&!y||h.schema===!1);_.assign(x,(0,e._)`${z}${(0,r.callValidateCode)(p,T,H,ee)}`,h.modifying)}function q(z){var H;_.if((0,e.not)((H=h.valid)!==null&&H!==void 0?H:x),z)}}Rr.funcKeywordCode=s;function a(p){const{gen:h,data:m,it:_}=p;h.if(_.parentData,()=>h.assign(m,(0,e._)`${_.parentData}[${_.parentDataProperty}]`))}function i(p,h){const{gen:m}=p;m.if((0,e._)`Array.isArray(${h})`,()=>{m.assign(t.default.vErrors,(0,e._)`${t.default.vErrors} === null ? ${h} : ${t.default.vErrors}.concat(${h})`).assign(t.default.errors,(0,e._)`${t.default.vErrors}.length`),(0,n.extendErrors)(p)},()=>p.error())}function l({schemaEnv:p},h){if(h.async&&!p.$async)throw new Error("async keyword in sync schema")}function c(p,h,m){if(m===void 0)throw new Error(`keyword "${h}" failed to compile`);return p.scopeValue("keyword",typeof m=="function"?{ref:m}:{ref:m,code:(0,e.stringify)(m)})}function u(p,h,m=!1){return!h.length||h.some(_=>_==="array"?Array.isArray(p):_==="object"?p&&typeof p=="object"&&!Array.isArray(p):typeof p==_||m&&typeof p>"u")}Rr.validSchemaType=u;function f({schema:p,opts:h,self:m,errSchemaPath:_},g,w){if(Array.isArray(g.keyword)?!g.keyword.includes(w):g.keyword!==w)throw new Error("ajv implementation error");const v=g.dependencies;if(v?.some(y=>!Object.prototype.hasOwnProperty.call(p,y)))throw new Error(`parent schema must have dependencies of ${w}: ${v.join(",")}`);if(g.validateSchema&&!g.validateSchema(p[w])){const S=`keyword "${w}" value is invalid at path "${_}": `+m.errorsText(g.validateSchema.errors);if(h.validateSchema==="log")m.logger.error(S);else throw new Error(S)}}return Rr.validateKeywordUsage=f,Rr}var cn={},Tf;function ub(){if(Tf)return cn;Tf=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.extendSubschemaMode=cn.extendSubschemaData=cn.getSubschema=void 0;const e=Ue(),t=Ge();function r(s,{keyword:a,schemaProp:i,schema:l,schemaPath:c,errSchemaPath:u,topSchemaRef:f}){if(a!==void 0&&l!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(a!==void 0){const p=s.schema[a];return i===void 0?{schema:p,schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}`,errSchemaPath:`${s.errSchemaPath}/${a}`}:{schema:p[i],schemaPath:(0,e._)`${s.schemaPath}${(0,e.getProperty)(a)}${(0,e.getProperty)(i)}`,errSchemaPath:`${s.errSchemaPath}/${a}/${(0,t.escapeFragment)(i)}`}}if(l!==void 0){if(c===void 0||u===void 0||f===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:l,schemaPath:c,topSchemaRef:f,errSchemaPath:u}}throw new Error('either "keyword" or "schema" must be passed')}cn.getSubschema=r;function n(s,a,{dataProp:i,dataPropType:l,data:c,dataTypes:u,propertyName:f}){if(c!==void 0&&i!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:p}=a;if(i!==void 0){const{errorPath:m,dataPathArr:_,opts:g}=a,w=p.let("data",(0,e._)`${a.data}${(0,e.getProperty)(i)}`,!0);h(w),s.errorPath=(0,e.str)`${m}${(0,t.getErrorPath)(i,l,g.jsPropertySyntax)}`,s.parentDataProperty=(0,e._)`${i}`,s.dataPathArr=[..._,s.parentDataProperty]}if(c!==void 0){const m=c instanceof e.Name?c:p.let("data",c,!0);h(m),f!==void 0&&(s.propertyName=f)}u&&(s.dataTypes=u);function h(m){s.data=m,s.dataLevel=a.dataLevel+1,s.dataTypes=[],a.definedProperties=new Set,s.parentData=a.data,s.dataNames=[...a.dataNames,m]}}cn.extendSubschemaData=n;function o(s,{jtdDiscriminator:a,jtdMetadata:i,compositeRule:l,createErrors:c,allErrors:u}){l!==void 0&&(s.compositeRule=l),c!==void 0&&(s.createErrors=c),u!==void 0&&(s.allErrors=u),s.jtdDiscriminator=a,s.jtdMetadata=i}return cn.extendSubschemaMode=o,cn}var Wt={},wc,Sf;function Cf(){return Sf||(Sf=1,wc=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var a=s[o];if(!e(t[a],r[a]))return!1}return!0}return t!==t&&r!==r}),wc}var bc={exports:{}},xf;function db(){if(xf)return bc.exports;xf=1;var e=bc.exports=function(n,o,s){typeof o=="function"&&(s=o,o={}),s=o.cb||s;var a=typeof s=="function"?s:s.pre||function(){},i=s.post||function(){};t(o,a,i,n,"",n)};e.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},e.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},e.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},e.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function t(n,o,s,a,i,l,c,u,f,p){if(a&&typeof a=="object"&&!Array.isArray(a)){o(a,i,l,c,u,f,p);for(var h in a){var m=a[h];if(Array.isArray(m)){if(h in e.arrayKeywords)for(var _=0;_<m.length;_++)t(n,o,s,m[_],i+"/"+h+"/"+_,l,i,h,a,_)}else if(h in e.propsKeywords){if(m&&typeof m=="object")for(var g in m)t(n,o,s,m[g],i+"/"+h+"/"+r(g),l,i,h,a,g)}else(h in e.keywords||n.allKeys&&!(h in e.skipKeywords))&&t(n,o,s,m,i+"/"+h,l,i,h,a)}s(a,i,l,c,u,f,p)}}function r(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}return bc.exports}var If;function Qa(){if(If)return Wt;If=1,Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.getSchemaRefs=Wt.resolveUrl=Wt.normalizeId=Wt._getFullPath=Wt.getFullPath=Wt.inlineRef=void 0;const e=Ge(),t=Cf(),r=db(),n=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function o(_,g=!0){return typeof _=="boolean"?!0:g===!0?!a(_):g?i(_)<=g:!1}Wt.inlineRef=o;const s=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function a(_){for(const g in _){if(s.has(g))return!0;const w=_[g];if(Array.isArray(w)&&w.some(a)||typeof w=="object"&&a(w))return!0}return!1}function i(_){let g=0;for(const w in _){if(w==="$ref")return 1/0;if(g++,!n.has(w)&&(typeof _[w]=="object"&&(0,e.eachItem)(_[w],v=>g+=i(v)),g===1/0))return 1/0}return g}function l(_,g="",w){w!==!1&&(g=f(g));const v=_.parse(g);return c(_,v)}Wt.getFullPath=l;function c(_,g){return _.serialize(g).split("#")[0]+"#"}Wt._getFullPath=c;const u=/#\/?$/;function f(_){return _?_.replace(u,""):""}Wt.normalizeId=f;function p(_,g,w){return w=f(w),_.resolve(g,w)}Wt.resolveUrl=p;const h=/^[a-z_][-a-z0-9._]*$/i;function m(_,g){if(typeof _=="boolean")return{};const{schemaId:w,uriResolver:v}=this.opts,y=f(_[w]||g),S={"":y},b=l(v,y,!1),T={},x=new Set;return r(_,{allKeys:!0},(L,O,q,z)=>{if(z===void 0)return;const H=b+O;let ee=S[z];typeof L[w]=="string"&&(ee=re.call(this,L[w])),X.call(this,L.$anchor),X.call(this,L.$dynamicAnchor),S[O]=ee;function re(V){const ie=this.opts.uriResolver.resolve;if(V=f(ee?ie(ee,V):V),x.has(V))throw C(V);x.add(V);let D=this.refs[V];return typeof D=="string"&&(D=this.refs[D]),typeof D=="object"?R(L,D.schema,V):V!==f(H)&&(V[0]==="#"?(R(L,T[V],V),T[V]=L):this.refs[V]=H),V}function X(V){if(typeof V=="string"){if(!h.test(V))throw new Error(`invalid anchor "${V}"`);re.call(this,`#${V}`)}}}),T;function R(L,O,q){if(O!==void 0&&!t(L,O))throw C(q)}function C(L){return new Error(`reference "${L}" resolves to more than one schema`)}}return Wt.getSchemaRefs=m,Wt}var $f;function Xa(){if($f)return an;$f=1,Object.defineProperty(an,"__esModule",{value:!0}),an.getData=an.KeywordCxt=an.validateFunctionCode=void 0;const e=ib(),t=Ya(),r=vf(),n=Ya(),o=lb(),s=cb(),a=ub(),i=Ue(),l=Cn(),c=Qa(),u=Ge(),f=Ka();function p(A){if(b(A)&&(x(A),S(A))){g(A);return}h(A,()=>(0,e.topBoolOrEmptySchema)(A))}an.validateFunctionCode=p;function h({gen:A,validateName:F,schema:J,schemaEnv:Q,opts:he},Pe){he.code.es5?A.func(F,(0,i._)`${l.default.data}, ${l.default.valCxt}`,Q.$async,()=>{A.code((0,i._)`"use strict"; ${v(J,he)}`),_(A,he),A.code(Pe)}):A.func(F,(0,i._)`${l.default.data}, ${m(he)}`,Q.$async,()=>A.code(v(J,he)).code(Pe))}function m(A){return(0,i._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${A.dynamicRef?(0,i._)`, ${l.default.dynamicAnchors}={}`:i.nil}}={}`}function _(A,F){A.if(l.default.valCxt,()=>{A.var(l.default.instancePath,(0,i._)`${l.default.valCxt}.${l.default.instancePath}`),A.var(l.default.parentData,(0,i._)`${l.default.valCxt}.${l.default.parentData}`),A.var(l.default.parentDataProperty,(0,i._)`${l.default.valCxt}.${l.default.parentDataProperty}`),A.var(l.default.rootData,(0,i._)`${l.default.valCxt}.${l.default.rootData}`),F.dynamicRef&&A.var(l.default.dynamicAnchors,(0,i._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{A.var(l.default.instancePath,(0,i._)`""`),A.var(l.default.parentData,(0,i._)`undefined`),A.var(l.default.parentDataProperty,(0,i._)`undefined`),A.var(l.default.rootData,l.default.data),F.dynamicRef&&A.var(l.default.dynamicAnchors,(0,i._)`{}`)})}function g(A){const{schema:F,opts:J,gen:Q}=A;h(A,()=>{J.$comment&&F.$comment&&z(A),L(A),Q.let(l.default.vErrors,null),Q.let(l.default.errors,0),J.unevaluated&&w(A),R(A),H(A)})}function w(A){const{gen:F,validateName:J}=A;A.evaluated=F.const("evaluated",(0,i._)`${J}.evaluated`),F.if((0,i._)`${A.evaluated}.dynamicProps`,()=>F.assign((0,i._)`${A.evaluated}.props`,(0,i._)`undefined`)),F.if((0,i._)`${A.evaluated}.dynamicItems`,()=>F.assign((0,i._)`${A.evaluated}.items`,(0,i._)`undefined`))}function v(A,F){const J=typeof A=="object"&&A[F.schemaId];return J&&(F.code.source||F.code.process)?(0,i._)`/*# sourceURL=${J} */`:i.nil}function y(A,F){if(b(A)&&(x(A),S(A))){T(A,F);return}(0,e.boolOrEmptySchema)(A,F)}function S({schema:A,self:F}){if(typeof A=="boolean")return!A;for(const J in A)if(F.RULES.all[J])return!0;return!1}function b(A){return typeof A.schema!="boolean"}function T(A,F){const{schema:J,gen:Q,opts:he}=A;he.$comment&&J.$comment&&z(A),O(A),q(A);const Pe=Q.const("_errs",l.default.errors);R(A,Pe),Q.var(F,(0,i._)`${Pe} === ${l.default.errors}`)}function x(A){(0,u.checkUnknownRules)(A),C(A)}function R(A,F){if(A.opts.jtd)return re(A,[],!1,F);const J=(0,t.getSchemaTypes)(A.schema),Q=(0,t.coerceAndCheckDataType)(A,J);re(A,J,!Q,F)}function C(A){const{schema:F,errSchemaPath:J,opts:Q,self:he}=A;F.$ref&&Q.ignoreKeywordsWithRef&&(0,u.schemaHasRulesButRef)(F,he.RULES)&&he.logger.warn(`$ref: keywords ignored in schema at path "${J}"`)}function L(A){const{schema:F,opts:J}=A;F.default!==void 0&&J.useDefaults&&J.strictSchema&&(0,u.checkStrictMode)(A,"default is ignored in the schema root")}function O(A){const F=A.schema[A.opts.schemaId];F&&(A.baseId=(0,c.resolveUrl)(A.opts.uriResolver,A.baseId,F))}function q(A){if(A.schema.$async&&!A.schemaEnv.$async)throw new Error("async schema in sync schema")}function z({gen:A,schemaEnv:F,schema:J,errSchemaPath:Q,opts:he}){const Pe=J.$comment;if(he.$comment===!0)A.code((0,i._)`${l.default.self}.logger.log(${Pe})`);else if(typeof he.$comment=="function"){const Ke=(0,i.str)`${Q}/$comment`,it=A.scopeValue("root",{ref:F.root});A.code((0,i._)`${l.default.self}.opts.$comment(${Pe}, ${Ke}, ${it}.schema)`)}}function H(A){const{gen:F,schemaEnv:J,validateName:Q,ValidationError:he,opts:Pe}=A;J.$async?F.if((0,i._)`${l.default.errors} === 0`,()=>F.return(l.default.data),()=>F.throw((0,i._)`new ${he}(${l.default.vErrors})`)):(F.assign((0,i._)`${Q}.errors`,l.default.vErrors),Pe.unevaluated&&ee(A),F.return((0,i._)`${l.default.errors} === 0`))}function ee({gen:A,evaluated:F,props:J,items:Q}){J instanceof i.Name&&A.assign((0,i._)`${F}.props`,J),Q instanceof i.Name&&A.assign((0,i._)`${F}.items`,Q)}function re(A,F,J,Q){const{gen:he,schema:Pe,data:Ke,allErrors:it,opts:gt,self:ae}=A,{RULES:rt}=ae;if(Pe.$ref&&(gt.ignoreKeywordsWithRef||!(0,u.schemaHasRulesButRef)(Pe,rt))){he.block(()=>oe(A,"$ref",rt.all.$ref.definition));return}gt.jtd||V(A,F),he.block(()=>{for(const ue of rt.rules)_e(ue);_e(rt.post)});function _e(ue){(0,r.shouldUseGroup)(Pe,ue)&&(ue.type?(he.if((0,n.checkDataType)(ue.type,Ke,gt.strictNumbers)),X(A,ue),F.length===1&&F[0]===ue.type&&J&&(he.else(),(0,n.reportTypeError)(A)),he.endIf()):X(A,ue),it||he.if((0,i._)`${l.default.errors} === ${Q||0}`))}}function X(A,F){const{gen:J,schema:Q,opts:{useDefaults:he}}=A;he&&(0,o.assignDefaults)(A,F.type),J.block(()=>{for(const Pe of F.rules)(0,r.shouldUseRule)(Q,Pe)&&oe(A,Pe.keyword,Pe.definition,F.type)})}function V(A,F){A.schemaEnv.meta||!A.opts.strictTypes||(ie(A,F),A.opts.allowUnionTypes||D(A,F),E(A,A.dataTypes))}function ie(A,F){if(F.length){if(!A.dataTypes.length){A.dataTypes=F;return}F.forEach(J=>{Z(A.dataTypes,J)||M(A,`type "${J}" not allowed by context "${A.dataTypes.join(",")}"`)}),I(A,F)}}function D(A,F){F.length>1&&!(F.length===2&&F.includes("null"))&&M(A,"use allowUnionTypes to allow union type keyword")}function E(A,F){const J=A.self.RULES.all;for(const Q in J){const he=J[Q];if(typeof he=="object"&&(0,r.shouldUseRule)(A.schema,he)){const{type:Pe}=he.definition;Pe.length&&!Pe.some(Ke=>U(F,Ke))&&M(A,`missing type "${Pe.join(",")}" for keyword "${Q}"`)}}}function U(A,F){return A.includes(F)||F==="number"&&A.includes("integer")}function Z(A,F){return A.includes(F)||F==="integer"&&A.includes("number")}function I(A,F){const J=[];for(const Q of A.dataTypes)Z(F,Q)?J.push(Q):F.includes("integer")&&Q==="number"&&J.push("integer");A.dataTypes=J}function M(A,F){const J=A.schemaEnv.baseId+A.errSchemaPath;F+=` at "${J}" (strictTypes)`,(0,u.checkStrictMode)(A,F,A.opts.strictTypes)}class B{constructor(F,J,Q){if((0,s.validateKeywordUsage)(F,J,Q),this.gen=F.gen,this.allErrors=F.allErrors,this.keyword=Q,this.data=F.data,this.schema=F.schema[Q],this.$data=J.$data&&F.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,u.schemaRefOrVal)(F,this.schema,Q,this.$data),this.schemaType=J.schemaType,this.parentSchema=F.schema,this.params={},this.it=F,this.def=J,this.$data)this.schemaCode=F.gen.const("vSchema",W(this.$data,F));else if(this.schemaCode=this.schemaValue,!(0,s.validSchemaType)(this.schema,J.schemaType,J.allowUndefined))throw new Error(`${Q} value must be ${JSON.stringify(J.schemaType)}`);("code"in J?J.trackErrors:J.errors!==!1)&&(this.errsCount=F.gen.const("_errs",l.default.errors))}result(F,J,Q){this.failResult((0,i.not)(F),J,Q)}failResult(F,J,Q){this.gen.if(F),Q?Q():this.error(),J?(this.gen.else(),J(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(F,J){this.failResult((0,i.not)(F),void 0,J)}fail(F){if(F===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(F),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(F){if(!this.$data)return this.fail(F);const{schemaCode:J}=this;this.fail((0,i._)`${J} !== undefined && (${(0,i.or)(this.invalid$data(),F)})`)}error(F,J,Q){if(J){this.setParams(J),this._error(F,Q),this.setParams({});return}this._error(F,Q)}_error(F,J){(F?f.reportExtraError:f.reportError)(this,this.def.error,J)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(F){this.allErrors||this.gen.if(F)}setParams(F,J){J?Object.assign(this.params,F):this.params=F}block$data(F,J,Q=i.nil){this.gen.block(()=>{this.check$data(F,Q),J()})}check$data(F=i.nil,J=i.nil){if(!this.$data)return;const{gen:Q,schemaCode:he,schemaType:Pe,def:Ke}=this;Q.if((0,i.or)((0,i._)`${he} === undefined`,J)),F!==i.nil&&Q.assign(F,!0),(Pe.length||Ke.validateSchema)&&(Q.elseIf(this.invalid$data()),this.$dataError(),F!==i.nil&&Q.assign(F,!1)),Q.else()}invalid$data(){const{gen:F,schemaCode:J,schemaType:Q,def:he,it:Pe}=this;return(0,i.or)(Ke(),it());function Ke(){if(Q.length){if(!(J instanceof i.Name))throw new Error("ajv implementation error");const gt=Array.isArray(Q)?Q:[Q];return(0,i._)`${(0,n.checkDataTypes)(gt,J,Pe.opts.strictNumbers,n.DataType.Wrong)}`}return i.nil}function it(){if(he.validateSchema){const gt=F.scopeValue("validate$data",{ref:he.validateSchema});return(0,i._)`!${gt}(${J})`}return i.nil}}subschema(F,J){const Q=(0,a.getSubschema)(this.it,F);(0,a.extendSubschemaData)(Q,this.it,F),(0,a.extendSubschemaMode)(Q,F);const he={...this.it,...Q,items:void 0,props:void 0};return y(he,J),he}mergeEvaluated(F,J){const{it:Q,gen:he}=this;Q.opts.unevaluated&&(Q.props!==!0&&F.props!==void 0&&(Q.props=u.mergeEvaluated.props(he,F.props,Q.props,J)),Q.items!==!0&&F.items!==void 0&&(Q.items=u.mergeEvaluated.items(he,F.items,Q.items,J)))}mergeValidEvaluated(F,J){const{it:Q,gen:he}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return he.if(J,()=>this.mergeEvaluated(F,i.Name)),!0}}an.KeywordCxt=B;function oe(A,F,J,Q){const he=new B(A,J,F);"code"in J?J.code(he,Q):he.$data&&J.validate?(0,s.funcKeywordCode)(he,J):"macro"in J?(0,s.macroKeywordCode)(he,J):(J.compile||J.validate)&&(0,s.funcKeywordCode)(he,J)}const ne=/^\/(?:[^~]|~0|~1)*$/,be=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function W(A,{dataLevel:F,dataNames:J,dataPathArr:Q}){let he,Pe;if(A==="")return l.default.rootData;if(A[0]==="/"){if(!ne.test(A))throw new Error(`Invalid JSON-pointer: ${A}`);he=A,Pe=l.default.rootData}else{const ae=be.exec(A);if(!ae)throw new Error(`Invalid JSON-pointer: ${A}`);const rt=+ae[1];if(he=ae[2],he==="#"){if(rt>=F)throw new Error(gt("property/index",rt));return Q[F-rt]}if(rt>F)throw new Error(gt("data",rt));if(Pe=J[F-rt],!he)return Pe}let Ke=Pe;const it=he.split("/");for(const ae of it)ae&&(Pe=(0,i._)`${Pe}${(0,i.getProperty)((0,u.unescapeJsonPointer)(ae))}`,Ke=(0,i._)`${Ke} && ${Pe}`);return Ke;function gt(ae,rt){return`Cannot access ${ae} ${rt} levels up, current level is ${F}`}}return an.getData=W,an}var ei={},Ef;function kc(){if(Ef)return ei;Ef=1,Object.defineProperty(ei,"__esModule",{value:!0});class e extends Error{constructor(r){super("validation failed"),this.errors=r,this.ajv=this.validation=!0}}return ei.default=e,ei}var ti={},Rf;function ri(){if(Rf)return ti;Rf=1,Object.defineProperty(ti,"__esModule",{value:!0});const e=Qa();class t extends Error{constructor(n,o,s,a){super(a||`can't resolve reference ${s} from id ${o}`),this.missingRef=(0,e.resolveUrl)(n,o,s),this.missingSchema=(0,e.normalizeId)((0,e.getFullPath)(n,this.missingRef))}}return ti.default=t,ti}var ur={},Pf;function Tc(){if(Pf)return ur;Pf=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.resolveSchema=ur.getCompilingSchema=ur.resolveRef=ur.compileSchema=ur.SchemaEnv=void 0;const e=Ue(),t=kc(),r=Cn(),n=Qa(),o=Ge(),s=Xa();class a{constructor(w){var v;this.refs={},this.dynamicAnchors={};let y;typeof w.schema=="object"&&(y=w.schema),this.schema=w.schema,this.schemaId=w.schemaId,this.root=w.root||this,this.baseId=(v=w.baseId)!==null&&v!==void 0?v:(0,n.normalizeId)(y?.[w.schemaId||"$id"]),this.schemaPath=w.schemaPath,this.localRefs=w.localRefs,this.meta=w.meta,this.$async=y?.$async,this.refs={}}}ur.SchemaEnv=a;function i(g){const w=u.call(this,g);if(w)return w;const v=(0,n.getFullPath)(this.opts.uriResolver,g.root.baseId),{es5:y,lines:S}=this.opts.code,{ownProperties:b}=this.opts,T=new e.CodeGen(this.scope,{es5:y,lines:S,ownProperties:b});let x;g.$async&&(x=T.scopeValue("Error",{ref:t.default,code:(0,e._)`require("ajv/dist/runtime/validation_error").default`}));const R=T.scopeName("validate");g.validateName=R;const C={gen:T,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[e.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:T.scopeValue("schema",this.opts.code.source===!0?{ref:g.schema,code:(0,e.stringify)(g.schema)}:{ref:g.schema}),validateName:R,ValidationError:x,schema:g.schema,schemaEnv:g,rootId:v,baseId:g.baseId||v,schemaPath:e.nil,errSchemaPath:g.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,e._)`""`,opts:this.opts,self:this};let L;try{this._compilations.add(g),(0,s.validateFunctionCode)(C),T.optimize(this.opts.code.optimize);const O=T.toString();L=`${T.scopeRefs(r.default.scope)}return ${O}`,this.opts.code.process&&(L=this.opts.code.process(L,g));const z=new Function(`${r.default.self}`,`${r.default.scope}`,L)(this,this.scope.get());if(this.scope.value(R,{ref:z}),z.errors=null,z.schema=g.schema,z.schemaEnv=g,g.$async&&(z.$async=!0),this.opts.code.source===!0&&(z.source={validateName:R,validateCode:O,scopeValues:T._values}),this.opts.unevaluated){const{props:H,items:ee}=C;z.evaluated={props:H instanceof e.Name?void 0:H,items:ee instanceof e.Name?void 0:ee,dynamicProps:H instanceof e.Name,dynamicItems:ee instanceof e.Name},z.source&&(z.source.evaluated=(0,e.stringify)(z.evaluated))}return g.validate=z,g}catch(O){throw delete g.validate,delete g.validateName,L&&this.logger.error("Error compiling schema, function code:",L),O}finally{this._compilations.delete(g)}}ur.compileSchema=i;function l(g,w,v){var y;v=(0,n.resolveUrl)(this.opts.uriResolver,w,v);const S=g.refs[v];if(S)return S;let b=p.call(this,g,v);if(b===void 0){const T=(y=g.localRefs)===null||y===void 0?void 0:y[v],{schemaId:x}=this.opts;T&&(b=new a({schema:T,schemaId:x,root:g,baseId:w}))}if(b!==void 0)return g.refs[v]=c.call(this,b)}ur.resolveRef=l;function c(g){return(0,n.inlineRef)(g.schema,this.opts.inlineRefs)?g.schema:g.validate?g:i.call(this,g)}function u(g){for(const w of this._compilations)if(f(w,g))return w}ur.getCompilingSchema=u;function f(g,w){return g.schema===w.schema&&g.root===w.root&&g.baseId===w.baseId}function p(g,w){let v;for(;typeof(v=this.refs[w])=="string";)w=v;return v||this.schemas[w]||h.call(this,g,w)}function h(g,w){const v=this.opts.uriResolver.parse(w),y=(0,n._getFullPath)(this.opts.uriResolver,v);let S=(0,n.getFullPath)(this.opts.uriResolver,g.baseId,void 0);if(Object.keys(g.schema).length>0&&y===S)return _.call(this,v,g);const b=(0,n.normalizeId)(y),T=this.refs[b]||this.schemas[b];if(typeof T=="string"){const x=h.call(this,g,T);return typeof x?.schema!="object"?void 0:_.call(this,v,x)}if(typeof T?.schema=="object"){if(T.validate||i.call(this,T),b===(0,n.normalizeId)(w)){const{schema:x}=T,{schemaId:R}=this.opts,C=x[R];return C&&(S=(0,n.resolveUrl)(this.opts.uriResolver,S,C)),new a({schema:x,schemaId:R,root:g,baseId:S})}return _.call(this,v,T)}}ur.resolveSchema=h;const m=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _(g,{baseId:w,schema:v,root:y}){var S;if(((S=g.fragment)===null||S===void 0?void 0:S[0])!=="/")return;for(const x of g.fragment.slice(1).split("/")){if(typeof v=="boolean")return;const R=v[(0,o.unescapeFragment)(x)];if(R===void 0)return;v=R;const C=typeof v=="object"&&v[this.opts.schemaId];!m.has(x)&&C&&(w=(0,n.resolveUrl)(this.opts.uriResolver,w,C))}let b;if(typeof v!="boolean"&&v.$ref&&!(0,o.schemaHasRulesButRef)(v,this.RULES)){const x=(0,n.resolveUrl)(this.opts.uriResolver,w,v.$ref);b=h.call(this,y,x)}const{schemaId:T}=this.opts;if(b=b||new a({schema:v,schemaId:T,root:y,baseId:w}),b.schema!==b.root.schema)return b}return ur}const pb={$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 ni={},gs={exports:{}},Sc,Mf;function Of(){if(Mf)return Sc;Mf=1;const e=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),t=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function r(p){let h="",m=0,_=0;for(_=0;_<p.length;_++)if(m=p[_].charCodeAt(0),m!==48){if(!(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102))return"";h+=p[_];break}for(_+=1;_<p.length;_++){if(m=p[_].charCodeAt(0),!(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102))return"";h+=p[_]}return h}const n=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(p){return p.length=0,!0}function s(p,h,m){if(p.length){const _=r(p);if(_!=="")h.push(_);else return m.error=!0,!1;p.length=0}return!0}function a(p){let h=0;const m={error:!1,address:"",zone:""},_=[],g=[];let w=!1,v=!1,y=s;for(let S=0;S<p.length;S++){const b=p[S];if(!(b==="["||b==="]"))if(b===":"){if(w===!0&&(v=!0),!y(g,_,m))break;if(++h>7){m.error=!0;break}S>0&&p[S-1]===":"&&(w=!0),_.push(":");continue}else if(b==="%"){if(!y(g,_,m))break;y=o}else{g.push(b);continue}}return g.length&&(y===o?m.zone=g.join(""):v?_.push(g.join("")):_.push(r(g))),m.address=_.join(""),m}function i(p){if(l(p,":")<2)return{host:p,isIPV6:!1};const h=a(p);if(h.error)return{host:p,isIPV6:!1};{let m=h.address,_=h.address;return h.zone&&(m+="%"+h.zone,_+="%25"+h.zone),{host:m,isIPV6:!0,escapedHost:_}}}function l(p,h){let m=0;for(let _=0;_<p.length;_++)p[_]===h&&m++;return m}function c(p){let h=p;const m=[];let _=-1,g=0;for(;g=h.length;){if(g===1){if(h===".")break;if(h==="/"){m.push("/");break}else{m.push(h);break}}else if(g===2){if(h[0]==="."){if(h[1]===".")break;if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&(h[1]==="."||h[1]==="/")){m.push("/");break}}else if(g===3&&h==="/.."){m.length!==0&&m.pop(),m.push("/");break}if(h[0]==="."){if(h[1]==="."){if(h[2]==="/"){h=h.slice(3);continue}}else if(h[1]==="/"){h=h.slice(2);continue}}else if(h[0]==="/"&&h[1]==="."){if(h[2]==="/"){h=h.slice(2);continue}else if(h[2]==="."&&h[3]==="/"){h=h.slice(3),m.length!==0&&m.pop();continue}}if((_=h.indexOf("/",1))===-1){m.push(h);break}else m.push(h.slice(0,_)),h=h.slice(_)}return m.join("")}function u(p,h){const m=h!==!0?escape:unescape;return p.scheme!==void 0&&(p.scheme=m(p.scheme)),p.userinfo!==void 0&&(p.userinfo=m(p.userinfo)),p.host!==void 0&&(p.host=m(p.host)),p.path!==void 0&&(p.path=m(p.path)),p.query!==void 0&&(p.query=m(p.query)),p.fragment!==void 0&&(p.fragment=m(p.fragment)),p}function f(p){const h=[];if(p.userinfo!==void 0&&(h.push(p.userinfo),h.push("@")),p.host!==void 0){let m=unescape(p.host);if(!t(m)){const _=i(m);_.isIPV6===!0?m=`[${_.escapedHost}]`:m=p.host}h.push(m)}return(typeof p.port=="number"||typeof p.port=="string")&&(h.push(":"),h.push(String(p.port))),h.length?h.join(""):void 0}return Sc={nonSimpleDomain:n,recomposeAuthority:f,normalizeComponentEncoding:u,removeDotSegments:c,isIPv4:t,isUUID:e,normalizeIPv6:i,stringArrayToHexStripped:r},Sc}var Cc,Nf;function fb(){if(Nf)return Cc;Nf=1;const{isUUID:e}=Of(),t=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,r=["http","https","ws","wss","urn","urn:uuid"];function n(b){return r.indexOf(b)!==-1}function o(b){return b.secure===!0?!0:b.secure===!1?!1:b.scheme?b.scheme.length===3&&(b.scheme[0]==="w"||b.scheme[0]==="W")&&(b.scheme[1]==="s"||b.scheme[1]==="S")&&(b.scheme[2]==="s"||b.scheme[2]==="S"):!1}function s(b){return b.host||(b.error=b.error||"HTTP URIs must have a host."),b}function a(b){const T=String(b.scheme).toLowerCase()==="https";return(b.port===(T?443:80)||b.port==="")&&(b.port=void 0),b.path||(b.path="/"),b}function i(b){return b.secure=o(b),b.resourceName=(b.path||"/")+(b.query?"?"+b.query:""),b.path=void 0,b.query=void 0,b}function l(b){if((b.port===(o(b)?443:80)||b.port==="")&&(b.port=void 0),typeof b.secure=="boolean"&&(b.scheme=b.secure?"wss":"ws",b.secure=void 0),b.resourceName){const[T,x]=b.resourceName.split("?");b.path=T&&T!=="/"?T:void 0,b.query=x,b.resourceName=void 0}return b.fragment=void 0,b}function c(b,T){if(!b.path)return b.error="URN can not be parsed",b;const x=b.path.match(t);if(x){const R=T.scheme||b.scheme||"urn";b.nid=x[1].toLowerCase(),b.nss=x[2];const C=`${R}:${T.nid||b.nid}`,L=S(C);b.path=void 0,L&&(b=L.parse(b,T))}else b.error=b.error||"URN can not be parsed.";return b}function u(b,T){if(b.nid===void 0)throw new Error("URN without nid cannot be serialized");const x=T.scheme||b.scheme||"urn",R=b.nid.toLowerCase(),C=`${x}:${T.nid||R}`,L=S(C);L&&(b=L.serialize(b,T));const O=b,q=b.nss;return O.path=`${R||T.nid}:${q}`,T.skipEscape=!0,O}function f(b,T){const x=b;return x.uuid=x.nss,x.nss=void 0,!T.tolerant&&(!x.uuid||!e(x.uuid))&&(x.error=x.error||"UUID is not valid."),x}function p(b){const T=b;return T.nss=(b.uuid||"").toLowerCase(),T}const h={scheme:"http",domainHost:!0,parse:s,serialize:a},m={scheme:"https",domainHost:h.domainHost,parse:s,serialize:a},_={scheme:"ws",domainHost:!0,parse:i,serialize:l},g={scheme:"wss",domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},y={http:h,https:m,ws:_,wss:g,urn:{scheme:"urn",parse:c,serialize:u,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:f,serialize:p,skipNormalize:!0}};Object.setPrototypeOf(y,null);function S(b){return b&&(y[b]||y[b.toLowerCase()])||void 0}return Cc={wsIsSecure:o,SCHEMES:y,isValidSchemeName:n,getSchemeHandler:S},Cc}var Af;function hb(){if(Af)return gs.exports;Af=1;const{normalizeIPv6:e,removeDotSegments:t,recomposeAuthority:r,normalizeComponentEncoding:n,isIPv4:o,nonSimpleDomain:s}=Of(),{SCHEMES:a,getSchemeHandler:i}=fb();function l(g,w){return typeof g=="string"?g=p(m(g,w),w):typeof g=="object"&&(g=m(p(g,w),w)),g}function c(g,w,v){const y=v?Object.assign({scheme:"null"},v):{scheme:"null"},S=u(m(g,y),m(w,y),y,!0);return y.skipEscape=!0,p(S,y)}function u(g,w,v,y){const S={};return y||(g=m(p(g,v),v),w=m(p(w,v),v)),v=v||{},!v.tolerant&&w.scheme?(S.scheme=w.scheme,S.userinfo=w.userinfo,S.host=w.host,S.port=w.port,S.path=t(w.path||""),S.query=w.query):(w.userinfo!==void 0||w.host!==void 0||w.port!==void 0?(S.userinfo=w.userinfo,S.host=w.host,S.port=w.port,S.path=t(w.path||""),S.query=w.query):(w.path?(w.path[0]==="/"?S.path=t(w.path):((g.userinfo!==void 0||g.host!==void 0||g.port!==void 0)&&!g.path?S.path="/"+w.path:g.path?S.path=g.path.slice(0,g.path.lastIndexOf("/")+1)+w.path:S.path=w.path,S.path=t(S.path)),S.query=w.query):(S.path=g.path,w.query!==void 0?S.query=w.query:S.query=g.query),S.userinfo=g.userinfo,S.host=g.host,S.port=g.port),S.scheme=g.scheme),S.fragment=w.fragment,S}function f(g,w,v){return typeof g=="string"?(g=unescape(g),g=p(n(m(g,v),!0),{...v,skipEscape:!0})):typeof g=="object"&&(g=p(n(g,!0),{...v,skipEscape:!0})),typeof w=="string"?(w=unescape(w),w=p(n(m(w,v),!0),{...v,skipEscape:!0})):typeof w=="object"&&(w=p(n(w,!0),{...v,skipEscape:!0})),g.toLowerCase()===w.toLowerCase()}function p(g,w){const v={host:g.host,scheme:g.scheme,userinfo:g.userinfo,port:g.port,path:g.path,query:g.query,nid:g.nid,nss:g.nss,uuid:g.uuid,fragment:g.fragment,reference:g.reference,resourceName:g.resourceName,secure:g.secure,error:""},y=Object.assign({},w),S=[],b=i(y.scheme||v.scheme);b&&b.serialize&&b.serialize(v,y),v.path!==void 0&&(y.skipEscape?v.path=unescape(v.path):(v.path=escape(v.path),v.scheme!==void 0&&(v.path=v.path.split("%3A").join(":")))),y.reference!=="suffix"&&v.scheme&&S.push(v.scheme,":");const T=r(v);if(T!==void 0&&(y.reference!=="suffix"&&S.push("//"),S.push(T),v.path&&v.path[0]!=="/"&&S.push("/")),v.path!==void 0){let x=v.path;!y.absolutePath&&(!b||!b.absolutePath)&&(x=t(x)),T===void 0&&x[0]==="/"&&x[1]==="/"&&(x="/%2F"+x.slice(2)),S.push(x)}return v.query!==void 0&&S.push("?",v.query),v.fragment!==void 0&&S.push("#",v.fragment),S.join("")}const h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function m(g,w){const v=Object.assign({},w),y={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let S=!1;v.reference==="suffix"&&(v.scheme?g=v.scheme+":"+g:g="//"+g);const b=g.match(h);if(b){if(y.scheme=b[1],y.userinfo=b[3],y.host=b[4],y.port=parseInt(b[5],10),y.path=b[6]||"",y.query=b[7],y.fragment=b[8],isNaN(y.port)&&(y.port=b[5]),y.host)if(o(y.host)===!1){const R=e(y.host);y.host=R.host.toLowerCase(),S=R.isIPV6}else S=!0;y.scheme===void 0&&y.userinfo===void 0&&y.host===void 0&&y.port===void 0&&y.query===void 0&&!y.path?y.reference="same-document":y.scheme===void 0?y.reference="relative":y.fragment===void 0?y.reference="absolute":y.reference="uri",v.reference&&v.reference!=="suffix"&&v.reference!==y.reference&&(y.error=y.error||"URI is not a "+v.reference+" reference.");const T=i(v.scheme||y.scheme);if(!v.unicodeSupport&&(!T||!T.unicodeSupport)&&y.host&&(v.domainHost||T&&T.domainHost)&&S===!1&&s(y.host))try{y.host=URL.domainToASCII(y.host.toLowerCase())}catch(x){y.error=y.error||"Host's domain name can not be converted to ASCII: "+x}(!T||T&&!T.skipNormalize)&&(g.indexOf("%")!==-1&&(y.scheme!==void 0&&(y.scheme=unescape(y.scheme)),y.host!==void 0&&(y.host=unescape(y.host))),y.path&&(y.path=escape(unescape(y.path))),y.fragment&&(y.fragment=encodeURI(decodeURIComponent(y.fragment)))),T&&T.parse&&T.parse(y,v)}else y.error=y.error||"URI can not be parsed.";return y}const _={SCHEMES:a,normalize:l,resolve:c,resolveComponent:u,equal:f,serialize:p,parse:m};return gs.exports=_,gs.exports.default=_,gs.exports.fastUri=_,gs.exports}var qf;function mb(){if(qf)return ni;qf=1,Object.defineProperty(ni,"__esModule",{value:!0});const e=hb();return e.code='require("ajv/dist/runtime/uri").default',ni.default=e,ni}var jf;function gb(){return jf||(jf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Xa();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var r=Ue();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const n=kc(),o=ri(),s=gf(),a=Tc(),i=Ue(),l=Qa(),c=Ya(),u=Ge(),f=pb,p=mb(),h=(D,E)=>new RegExp(D,E);h.code="new RegExp";const m=["removeAdditional","useDefaults","coerceTypes"],_=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),g={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},w={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function y(D){var E,U,Z,I,M,B,oe,ne,be,W,A,F,J,Q,he,Pe,Ke,it,gt,ae,rt,_e,ue,Ie,ce;const te=D.strict,Ce=(E=D.code)===null||E===void 0?void 0:E.optimize,$=Ce===!0||Ce===void 0?1:Ce||0,Y=(Z=(U=D.code)===null||U===void 0?void 0:U.regExp)!==null&&Z!==void 0?Z:h,Fe=(I=D.uriResolver)!==null&&I!==void 0?I:p.default;return{strictSchema:(B=(M=D.strictSchema)!==null&&M!==void 0?M:te)!==null&&B!==void 0?B:!0,strictNumbers:(ne=(oe=D.strictNumbers)!==null&&oe!==void 0?oe:te)!==null&&ne!==void 0?ne:!0,strictTypes:(W=(be=D.strictTypes)!==null&&be!==void 0?be:te)!==null&&W!==void 0?W:"log",strictTuples:(F=(A=D.strictTuples)!==null&&A!==void 0?A:te)!==null&&F!==void 0?F:"log",strictRequired:(Q=(J=D.strictRequired)!==null&&J!==void 0?J:te)!==null&&Q!==void 0?Q:!1,code:D.code?{...D.code,optimize:$,regExp:Y}:{optimize:$,regExp:Y},loopRequired:(he=D.loopRequired)!==null&&he!==void 0?he:v,loopEnum:(Pe=D.loopEnum)!==null&&Pe!==void 0?Pe:v,meta:(Ke=D.meta)!==null&&Ke!==void 0?Ke:!0,messages:(it=D.messages)!==null&&it!==void 0?it:!0,inlineRefs:(gt=D.inlineRefs)!==null&&gt!==void 0?gt:!0,schemaId:(ae=D.schemaId)!==null&&ae!==void 0?ae:"$id",addUsedSchema:(rt=D.addUsedSchema)!==null&&rt!==void 0?rt:!0,validateSchema:(_e=D.validateSchema)!==null&&_e!==void 0?_e:!0,validateFormats:(ue=D.validateFormats)!==null&&ue!==void 0?ue:!0,unicodeRegExp:(Ie=D.unicodeRegExp)!==null&&Ie!==void 0?Ie:!0,int32range:(ce=D.int32range)!==null&&ce!==void 0?ce:!0,uriResolver:Fe}}class S{constructor(E={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,E=this.opts={...E,...y(E)};const{es5:U,lines:Z}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:_,es5:U,lines:Z}),this.logger=q(E.logger);const I=E.validateFormats;E.validateFormats=!1,this.RULES=(0,s.getRules)(),b.call(this,g,E,"NOT SUPPORTED"),b.call(this,w,E,"DEPRECATED","warn"),this._metaOpts=L.call(this),E.formats&&R.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),E.keywords&&C.call(this,E.keywords),typeof E.meta=="object"&&this.addMetaSchema(E.meta),x.call(this),E.validateFormats=I}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:E,meta:U,schemaId:Z}=this.opts;let I=f;Z==="id"&&(I={...f},I.id=I.$id,delete I.$id),U&&E&&this.addMetaSchema(I,I[Z],!1)}defaultMeta(){const{meta:E,schemaId:U}=this.opts;return this.opts.defaultMeta=typeof E=="object"?E[U]||E:void 0}validate(E,U){let Z;if(typeof E=="string"){if(Z=this.getSchema(E),!Z)throw new Error(`no schema with key or ref "${E}"`)}else Z=this.compile(E);const I=Z(U);return"$async"in Z||(this.errors=Z.errors),I}compile(E,U){const Z=this._addSchema(E,U);return Z.validate||this._compileSchemaEnv(Z)}compileAsync(E,U){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:Z}=this.opts;return I.call(this,E,U);async function I(W,A){await M.call(this,W.$schema);const F=this._addSchema(W,A);return F.validate||B.call(this,F)}async function M(W){W&&!this.getSchema(W)&&await I.call(this,{$ref:W},!0)}async function B(W){try{return this._compileSchemaEnv(W)}catch(A){if(!(A instanceof o.default))throw A;return oe.call(this,A),await ne.call(this,A.missingSchema),B.call(this,W)}}function oe({missingSchema:W,missingRef:A}){if(this.refs[W])throw new Error(`AnySchema ${W} is loaded but ${A} cannot be resolved`)}async function ne(W){const A=await be.call(this,W);this.refs[W]||await M.call(this,A.$schema),this.refs[W]||this.addSchema(A,W,U)}async function be(W){const A=this._loading[W];if(A)return A;try{return await(this._loading[W]=Z(W))}finally{delete this._loading[W]}}}addSchema(E,U,Z,I=this.opts.validateSchema){if(Array.isArray(E)){for(const B of E)this.addSchema(B,void 0,Z,I);return this}let M;if(typeof E=="object"){const{schemaId:B}=this.opts;if(M=E[B],M!==void 0&&typeof M!="string")throw new Error(`schema ${B} must be string`)}return U=(0,l.normalizeId)(U||M),this._checkUnique(U),this.schemas[U]=this._addSchema(E,Z,U,I,!0),this}addMetaSchema(E,U,Z=this.opts.validateSchema){return this.addSchema(E,U,!0,Z),this}validateSchema(E,U){if(typeof E=="boolean")return!0;let Z;if(Z=E.$schema,Z!==void 0&&typeof Z!="string")throw new Error("$schema must be a string");if(Z=Z||this.opts.defaultMeta||this.defaultMeta(),!Z)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const I=this.validate(Z,E);if(!I&&U){const M="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(M);else throw new Error(M)}return I}getSchema(E){let U;for(;typeof(U=T.call(this,E))=="string";)E=U;if(U===void 0){const{schemaId:Z}=this.opts,I=new a.SchemaEnv({schema:{},schemaId:Z});if(U=a.resolveSchema.call(this,I,E),!U)return;this.refs[E]=U}return U.validate||this._compileSchemaEnv(U)}removeSchema(E){if(E instanceof RegExp)return this._removeAllSchemas(this.schemas,E),this._removeAllSchemas(this.refs,E),this;switch(typeof E){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const U=T.call(this,E);return typeof U=="object"&&this._cache.delete(U.schema),delete this.schemas[E],delete this.refs[E],this}case"object":{const U=E;this._cache.delete(U);let Z=E[this.opts.schemaId];return Z&&(Z=(0,l.normalizeId)(Z),delete this.schemas[Z],delete this.refs[Z]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(E){for(const U of E)this.addKeyword(U);return this}addKeyword(E,U){let Z;if(typeof E=="string")Z=E,typeof U=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),U.keyword=Z);else if(typeof E=="object"&&U===void 0){if(U=E,Z=U.keyword,Array.isArray(Z)&&!Z.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(H.call(this,Z,U),!U)return(0,u.eachItem)(Z,M=>ee.call(this,M)),this;X.call(this,U);const I={...U,type:(0,c.getJSONTypes)(U.type),schemaType:(0,c.getJSONTypes)(U.schemaType)};return(0,u.eachItem)(Z,I.type.length===0?M=>ee.call(this,M,I):M=>I.type.forEach(B=>ee.call(this,M,I,B))),this}getKeyword(E){const U=this.RULES.all[E];return typeof U=="object"?U.definition:!!U}removeKeyword(E){const{RULES:U}=this;delete U.keywords[E],delete U.all[E];for(const Z of U.rules){const I=Z.rules.findIndex(M=>M.keyword===E);I>=0&&Z.rules.splice(I,1)}return this}addFormat(E,U){return typeof U=="string"&&(U=new RegExp(U)),this.formats[E]=U,this}errorsText(E=this.errors,{separator:U=", ",dataVar:Z="data"}={}){return!E||E.length===0?"No errors":E.map(I=>`${Z}${I.instancePath} ${I.message}`).reduce((I,M)=>I+U+M)}$dataMetaSchema(E,U){const Z=this.RULES.all;E=JSON.parse(JSON.stringify(E));for(const I of U){const M=I.split("/").slice(1);let B=E;for(const oe of M)B=B[oe];for(const oe in Z){const ne=Z[oe];if(typeof ne!="object")continue;const{$data:be}=ne.definition,W=B[oe];be&&W&&(B[oe]=ie(W))}}return E}_removeAllSchemas(E,U){for(const Z in E){const I=E[Z];(!U||U.test(Z))&&(typeof I=="string"?delete E[Z]:I&&!I.meta&&(this._cache.delete(I.schema),delete E[Z]))}}_addSchema(E,U,Z,I=this.opts.validateSchema,M=this.opts.addUsedSchema){let B;const{schemaId:oe}=this.opts;if(typeof E=="object")B=E[oe];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof E!="boolean")throw new Error("schema must be object or boolean")}let ne=this._cache.get(E);if(ne!==void 0)return ne;Z=(0,l.normalizeId)(B||Z);const be=l.getSchemaRefs.call(this,E,Z);return ne=new a.SchemaEnv({schema:E,schemaId:oe,meta:U,baseId:Z,localRefs:be}),this._cache.set(ne.schema,ne),M&&!Z.startsWith("#")&&(Z&&this._checkUnique(Z),this.refs[Z]=ne),I&&this.validateSchema(E,!0),ne}_checkUnique(E){if(this.schemas[E]||this.refs[E])throw new Error(`schema with key or id "${E}" already exists`)}_compileSchemaEnv(E){if(E.meta?this._compileMetaSchema(E):a.compileSchema.call(this,E),!E.validate)throw new Error("ajv implementation error");return E.validate}_compileMetaSchema(E){const U=this.opts;this.opts=this._metaOpts;try{a.compileSchema.call(this,E)}finally{this.opts=U}}}S.ValidationError=n.default,S.MissingRefError=o.default,e.default=S;function b(D,E,U,Z="error"){for(const I in D){const M=I;M in E&&this.logger[Z](`${U}: option ${I}. ${D[M]}`)}}function T(D){return D=(0,l.normalizeId)(D),this.schemas[D]||this.refs[D]}function x(){const D=this.opts.schemas;if(D)if(Array.isArray(D))this.addSchema(D);else for(const E in D)this.addSchema(D[E],E)}function R(){for(const D in this.opts.formats){const E=this.opts.formats[D];E&&this.addFormat(D,E)}}function C(D){if(Array.isArray(D)){this.addVocabulary(D);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const E in D){const U=D[E];U.keyword||(U.keyword=E),this.addKeyword(U)}}function L(){const D={...this.opts};for(const E of m)delete D[E];return D}const O={log(){},warn(){},error(){}};function q(D){if(D===!1)return O;if(D===void 0)return console;if(D.log&&D.warn&&D.error)return D;throw new Error("logger must implement log, warn and error methods")}const z=/^[a-z_$][a-z0-9_$:-]*$/i;function H(D,E){const{RULES:U}=this;if((0,u.eachItem)(D,Z=>{if(U.keywords[Z])throw new Error(`Keyword ${Z} is already defined`);if(!z.test(Z))throw new Error(`Keyword ${Z} has invalid name`)}),!!E&&E.$data&&!("code"in E||"validate"in E))throw new Error('$data keyword must have "code" or "validate" function')}function ee(D,E,U){var Z;const I=E?.post;if(U&&I)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:M}=this;let B=I?M.post:M.rules.find(({type:ne})=>ne===U);if(B||(B={type:U,rules:[]},M.rules.push(B)),M.keywords[D]=!0,!E)return;const oe={keyword:D,definition:{...E,type:(0,c.getJSONTypes)(E.type),schemaType:(0,c.getJSONTypes)(E.schemaType)}};E.before?re.call(this,B,oe,E.before):B.rules.push(oe),M.all[D]=oe,(Z=E.implements)===null||Z===void 0||Z.forEach(ne=>this.addKeyword(ne))}function re(D,E,U){const Z=D.rules.findIndex(I=>I.keyword===U);Z>=0?D.rules.splice(Z,0,E):(D.rules.push(E),this.logger.warn(`rule ${U} is not defined`))}function X(D){let{metaSchema:E}=D;E!==void 0&&(D.$data&&this.opts.$data&&(E=ie(E)),D.validateSchema=this.compile(E,!0))}const V={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ie(D){return{anyOf:[D,V]}}})(mc)),mc}var oi={},si={},ai={},Lf;function yb(){if(Lf)return ai;Lf=1,Object.defineProperty(ai,"__esModule",{value:!0});const e={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};return ai.default=e,ai}var xn={},Df;function vb(){if(Df)return xn;Df=1,Object.defineProperty(xn,"__esModule",{value:!0}),xn.callRef=xn.getValidate=void 0;const e=ri(),t=Pr(),r=Ue(),n=Cn(),o=Tc(),s=Ge(),a={keyword:"$ref",schemaType:"string",code(c){const{gen:u,schema:f,it:p}=c,{baseId:h,schemaEnv:m,validateName:_,opts:g,self:w}=p,{root:v}=m;if((f==="#"||f==="#/")&&h===v.baseId)return S();const y=o.resolveRef.call(w,v,h,f);if(y===void 0)throw new e.default(p.opts.uriResolver,h,f);if(y instanceof o.SchemaEnv)return b(y);return T(y);function S(){if(m===v)return l(c,_,m,m.$async);const x=u.scopeValue("root",{ref:v});return l(c,(0,r._)`${x}.validate`,v,v.$async)}function b(x){const R=i(c,x);l(c,R,x,x.$async)}function T(x){const R=u.scopeValue("schema",g.code.source===!0?{ref:x,code:(0,r.stringify)(x)}:{ref:x}),C=u.name("valid"),L=c.subschema({schema:x,dataTypes:[],schemaPath:r.nil,topSchemaRef:R,errSchemaPath:f},C);c.mergeEvaluated(L),c.ok(C)}}};function i(c,u){const{gen:f}=c;return u.validate?f.scopeValue("validate",{ref:u.validate}):(0,r._)`${f.scopeValue("wrapper",{ref:u})}.validate`}xn.getValidate=i;function l(c,u,f,p){const{gen:h,it:m}=c,{allErrors:_,schemaEnv:g,opts:w}=m,v=w.passContext?n.default.this:r.nil;p?y():S();function y(){if(!g.$async)throw new Error("async schema referenced by sync schema");const x=h.let("valid");h.try(()=>{h.code((0,r._)`await ${(0,t.callValidateCode)(c,u,v)}`),T(u),_||h.assign(x,!0)},R=>{h.if((0,r._)`!(${R} instanceof ${m.ValidationError})`,()=>h.throw(R)),b(R),_||h.assign(x,!1)}),c.ok(x)}function S(){c.result((0,t.callValidateCode)(c,u,v),()=>T(u),()=>b(u))}function b(x){const R=(0,r._)`${x}.errors`;h.assign(n.default.vErrors,(0,r._)`${n.default.vErrors} === null ? ${R} : ${n.default.vErrors}.concat(${R})`),h.assign(n.default.errors,(0,r._)`${n.default.vErrors}.length`)}function T(x){var R;if(!m.opts.unevaluated)return;const C=(R=f?.validate)===null||R===void 0?void 0:R.evaluated;if(m.props!==!0)if(C&&!C.dynamicProps)C.props!==void 0&&(m.props=s.mergeEvaluated.props(h,C.props,m.props));else{const L=h.var("props",(0,r._)`${x}.evaluated.props`);m.props=s.mergeEvaluated.props(h,L,m.props,r.Name)}if(m.items!==!0)if(C&&!C.dynamicItems)C.items!==void 0&&(m.items=s.mergeEvaluated.items(h,C.items,m.items));else{const L=h.var("items",(0,r._)`${x}.evaluated.items`);m.items=s.mergeEvaluated.items(h,L,m.items,r.Name)}}}return xn.callRef=l,xn.default=a,xn}var Uf;function _b(){if(Uf)return si;Uf=1,Object.defineProperty(si,"__esModule",{value:!0});const e=yb(),t=vb(),r=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",e.default,t.default];return si.default=r,si}var ii={},li={},zf;function wb(){if(zf)return li;zf=1,Object.defineProperty(li,"__esModule",{value:!0});const e=Ue(),t=e.operators,r={maximum:{okStr:"<=",ok:t.LTE,fail:t.GT},minimum:{okStr:">=",ok:t.GTE,fail:t.LT},exclusiveMaximum:{okStr:"<",ok:t.LT,fail:t.GTE},exclusiveMinimum:{okStr:">",ok:t.GT,fail:t.LTE}},n={message:({keyword:s,schemaCode:a})=>(0,e.str)`must be ${r[s].okStr} ${a}`,params:({keyword:s,schemaCode:a})=>(0,e._)`{comparison: ${r[s].okStr}, limit: ${a}}`},o={keyword:Object.keys(r),type:"number",schemaType:"number",$data:!0,error:n,code(s){const{keyword:a,data:i,schemaCode:l}=s;s.fail$data((0,e._)`${i} ${r[a].fail} ${l} || isNaN(${i})`)}};return li.default=o,li}var ci={},Zf;function bb(){if(Zf)return ci;Zf=1,Object.defineProperty(ci,"__esModule",{value:!0});const e=Ue(),r={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must be multiple of ${n}`,params:({schemaCode:n})=>(0,e._)`{multipleOf: ${n}}`},code(n){const{gen:o,data:s,schemaCode:a,it:i}=n,l=i.opts.multipleOfPrecision,c=o.let("res"),u=l?(0,e._)`Math.abs(Math.round(${c}) - ${c}) > 1e-${l}`:(0,e._)`${c} !== parseInt(${c})`;n.fail$data((0,e._)`(${a} === 0 || (${c} = ${s}/${a}, ${u}))`)}};return ci.default=r,ci}var ui={},di={},Ff;function kb(){if(Ff)return di;Ff=1,Object.defineProperty(di,"__esModule",{value:!0});function e(t){const r=t.length;let n=0,o=0,s;for(;o<r;)n++,s=t.charCodeAt(o++),s>=55296&&s<=56319&&o<r&&(s=t.charCodeAt(o),(s&64512)===56320&&o++);return n}return di.default=e,e.code='require("ajv/dist/runtime/ucs2length").default',di}var Vf;function Tb(){if(Vf)return ui;Vf=1,Object.defineProperty(ui,"__esModule",{value:!0});const e=Ue(),t=Ge(),r=kb(),o={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:s,schemaCode:a}){const i=s==="maxLength"?"more":"fewer";return(0,e.str)`must NOT have ${i} than ${a} characters`},params:({schemaCode:s})=>(0,e._)`{limit: ${s}}`},code(s){const{keyword:a,data:i,schemaCode:l,it:c}=s,u=a==="maxLength"?e.operators.GT:e.operators.LT,f=c.opts.unicode===!1?(0,e._)`${i}.length`:(0,e._)`${(0,t.useFunc)(s.gen,r.default)}(${i})`;s.fail$data((0,e._)`${f} ${u} ${l}`)}};return ui.default=o,ui}var pi={},Hf;function Sb(){if(Hf)return pi;Hf=1,Object.defineProperty(pi,"__esModule",{value:!0});const e=Pr(),t=Ge(),r=Ue(),o={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:s})=>(0,r.str)`must match pattern "${s}"`,params:({schemaCode:s})=>(0,r._)`{pattern: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:f}=s,p=f.opts.unicodeRegExp?"u":"";if(l){const{regExp:h}=f.opts.code,m=h.code==="new RegExp"?(0,r._)`new RegExp`:(0,t.useFunc)(a,h),_=a.let("valid");a.try(()=>a.assign(_,(0,r._)`${m}(${u}, ${p}).test(${i})`),()=>a.assign(_,!1)),s.fail$data((0,r._)`!${_}`)}else{const h=(0,e.usePattern)(s,c);s.fail$data((0,r._)`!${h}.test(${i})`)}}};return pi.default=o,pi}var fi={},Bf;function Cb(){if(Bf)return fi;Bf=1,Object.defineProperty(fi,"__esModule",{value:!0});const e=Ue(),r={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxProperties"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} properties`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxProperties"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`Object.keys(${s}).length ${i} ${a}`)}};return fi.default=r,fi}var hi={},Jf;function xb(){if(Jf)return hi;Jf=1,Object.defineProperty(hi,"__esModule",{value:!0});const e=Pr(),t=Ue(),r=Ge(),o={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:s}})=>(0,t.str)`must have required property '${s}'`,params:({params:{missingProperty:s}})=>(0,t._)`{missingProperty: ${s}}`},code(s){const{gen:a,schema:i,schemaCode:l,data:c,$data:u,it:f}=s,{opts:p}=f;if(!u&&i.length===0)return;const h=i.length>=p.loopRequired;if(f.allErrors?m():_(),p.strictRequired){const v=s.parentSchema.properties,{definedProperties:y}=s.it;for(const S of i)if(v?.[S]===void 0&&!y.has(S)){const b=f.schemaEnv.baseId+f.errSchemaPath,T=`required property "${S}" is not defined at "${b}" (strictRequired)`;(0,r.checkStrictMode)(f,T,f.opts.strictRequired)}}function m(){if(h||u)s.block$data(t.nil,g);else for(const v of i)(0,e.checkReportMissingProp)(s,v)}function _(){const v=a.let("missing");if(h||u){const y=a.let("valid",!0);s.block$data(y,()=>w(v,y)),s.ok(y)}else a.if((0,e.checkMissingProp)(s,i,v)),(0,e.reportMissingProp)(s,v),a.else()}function g(){a.forOf("prop",l,v=>{s.setParams({missingProperty:v}),a.if((0,e.noPropertyInData)(a,c,v,p.ownProperties),()=>s.error())})}function w(v,y){s.setParams({missingProperty:v}),a.forOf(v,l,()=>{a.assign(y,(0,e.propertyInData)(a,c,v,p.ownProperties)),a.if((0,t.not)(y),()=>{s.error(),a.break()})},t.nil)}}};return hi.default=o,hi}var mi={},Wf;function Ib(){if(Wf)return mi;Wf=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=Ue(),r={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:n,schemaCode:o}){const s=n==="maxItems"?"more":"fewer";return(0,e.str)`must NOT have ${s} than ${o} items`},params:({schemaCode:n})=>(0,e._)`{limit: ${n}}`},code(n){const{keyword:o,data:s,schemaCode:a}=n,i=o==="maxItems"?e.operators.GT:e.operators.LT;n.fail$data((0,e._)`${s}.length ${i} ${a}`)}};return mi.default=r,mi}var gi={},yi={},Gf;function xc(){if(Gf)return yi;Gf=1,Object.defineProperty(yi,"__esModule",{value:!0});const e=Cf();return e.code='require("ajv/dist/runtime/equal").default',yi.default=e,yi}var Kf;function $b(){if(Kf)return gi;Kf=1,Object.defineProperty(gi,"__esModule",{value:!0});const e=Ya(),t=Ue(),r=Ge(),n=xc(),s={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:a,j:i}})=>(0,t.str)`must NOT have duplicate items (items ## ${i} and ${a} are identical)`,params:({params:{i:a,j:i}})=>(0,t._)`{i: ${a}, j: ${i}}`},code(a){const{gen:i,data:l,$data:c,schema:u,parentSchema:f,schemaCode:p,it:h}=a;if(!c&&!u)return;const m=i.let("valid"),_=f.items?(0,e.getSchemaTypes)(f.items):[];a.block$data(m,g,(0,t._)`${p} === false`),a.ok(m);function g(){const S=i.let("i",(0,t._)`${l}.length`),b=i.let("j");a.setParams({i:S,j:b}),i.assign(m,!0),i.if((0,t._)`${S} > 1`,()=>(w()?v:y)(S,b))}function w(){return _.length>0&&!_.some(S=>S==="object"||S==="array")}function v(S,b){const T=i.name("item"),x=(0,e.checkDataTypes)(_,T,h.opts.strictNumbers,e.DataType.Wrong),R=i.const("indices",(0,t._)`{}`);i.for((0,t._)`;${S}--;`,()=>{i.let(T,(0,t._)`${l}[${S}]`),i.if(x,(0,t._)`continue`),_.length>1&&i.if((0,t._)`typeof ${T} == "string"`,(0,t._)`${T} += "_"`),i.if((0,t._)`typeof ${R}[${T}] == "number"`,()=>{i.assign(b,(0,t._)`${R}[${T}]`),a.error(),i.assign(m,!1).break()}).code((0,t._)`${R}[${T}] = ${S}`)})}function y(S,b){const T=(0,r.useFunc)(i,n.default),x=i.name("outer");i.label(x).for((0,t._)`;${S}--;`,()=>i.for((0,t._)`${b} = ${S}; ${b}--;`,()=>i.if((0,t._)`${T}(${l}[${S}], ${l}[${b}])`,()=>{a.error(),i.assign(m,!1).break(x)})))}}};return gi.default=s,gi}var vi={},Yf;function Eb(){if(Yf)return vi;Yf=1,Object.defineProperty(vi,"__esModule",{value:!0});const e=Ue(),t=Ge(),r=xc(),o={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:s})=>(0,e._)`{allowedValue: ${s}}`},code(s){const{gen:a,data:i,$data:l,schemaCode:c,schema:u}=s;l||u&&typeof u=="object"?s.fail$data((0,e._)`!${(0,t.useFunc)(a,r.default)}(${i}, ${c})`):s.fail((0,e._)`${u} !== ${i}`)}};return vi.default=o,vi}var _i={},Qf;function Rb(){if(Qf)return _i;Qf=1,Object.defineProperty(_i,"__esModule",{value:!0});const e=Ue(),t=Ge(),r=xc(),o={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:s})=>(0,e._)`{allowedValues: ${s}}`},code(s){const{gen:a,data:i,$data:l,schema:c,schemaCode:u,it:f}=s;if(!l&&c.length===0)throw new Error("enum must have non-empty array");const p=c.length>=f.opts.loopEnum;let h;const m=()=>h??(h=(0,t.useFunc)(a,r.default));let _;if(p||l)_=a.let("valid"),s.block$data(_,g);else{if(!Array.isArray(c))throw new Error("ajv implementation error");const v=a.const("vSchema",u);_=(0,e.or)(...c.map((y,S)=>w(v,S)))}s.pass(_);function g(){a.assign(_,!1),a.forOf("v",u,v=>a.if((0,e._)`${m()}(${i}, ${v})`,()=>a.assign(_,!0).break()))}function w(v,y){const S=c[y];return typeof S=="object"&&S!==null?(0,e._)`${m()}(${i}, ${v}[${y}])`:(0,e._)`${i} === ${S}`}}};return _i.default=o,_i}var Xf;function Pb(){if(Xf)return ii;Xf=1,Object.defineProperty(ii,"__esModule",{value:!0});const e=wb(),t=bb(),r=Tb(),n=Sb(),o=Cb(),s=xb(),a=Ib(),i=$b(),l=Eb(),c=Rb(),u=[e.default,t.default,r.default,n.default,o.default,s.default,a.default,i.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l.default,c.default];return ii.default=u,ii}var wi={},Eo={},eh;function th(){if(eh)return Eo;eh=1,Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.validateAdditionalItems=void 0;const e=Ue(),t=Ge(),n={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:s}})=>(0,e.str)`must NOT have more than ${s} items`,params:({params:{len:s}})=>(0,e._)`{limit: ${s}}`},code(s){const{parentSchema:a,it:i}=s,{items:l}=a;if(!Array.isArray(l)){(0,t.checkStrictMode)(i,'"additionalItems" is ignored when "items" is not an array of schemas');return}o(s,l)}};function o(s,a){const{gen:i,schema:l,data:c,keyword:u,it:f}=s;f.items=!0;const p=i.const("len",(0,e._)`${c}.length`);if(l===!1)s.setParams({len:a.length}),s.pass((0,e._)`${p} <= ${a.length}`);else if(typeof l=="object"&&!(0,t.alwaysValidSchema)(f,l)){const m=i.var("valid",(0,e._)`${p} <= ${a.length}`);i.if((0,e.not)(m),()=>h(m)),s.ok(m)}function h(m){i.forRange("i",a.length,p,_=>{s.subschema({keyword:u,dataProp:_,dataPropType:t.Type.Num},m),f.allErrors||i.if((0,e.not)(m),()=>i.break())})}}return Eo.validateAdditionalItems=o,Eo.default=n,Eo}var bi={},Ro={},rh;function nh(){if(rh)return Ro;rh=1,Object.defineProperty(Ro,"__esModule",{value:!0}),Ro.validateTuple=void 0;const e=Ue(),t=Ge(),r=Pr(),n={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(s){const{schema:a,it:i}=s;if(Array.isArray(a))return o(s,"additionalItems",a);i.items=!0,!(0,t.alwaysValidSchema)(i,a)&&s.ok((0,r.validateArray)(s))}};function o(s,a,i=s.schema){const{gen:l,parentSchema:c,data:u,keyword:f,it:p}=s;_(c),p.opts.unevaluated&&i.length&&p.items!==!0&&(p.items=t.mergeEvaluated.items(l,i.length,p.items));const h=l.name("valid"),m=l.const("len",(0,e._)`${u}.length`);i.forEach((g,w)=>{(0,t.alwaysValidSchema)(p,g)||(l.if((0,e._)`${m} > ${w}`,()=>s.subschema({keyword:f,schemaProp:w,dataProp:w},h)),s.ok(h))});function _(g){const{opts:w,errSchemaPath:v}=p,y=i.length,S=y===g.minItems&&(y===g.maxItems||g[a]===!1);if(w.strictTuples&&!S){const b=`"${f}" is ${y}-tuple, but minItems or maxItems/${a} are not specified or different at path "${v}"`;(0,t.checkStrictMode)(p,b,w.strictTuples)}}}return Ro.validateTuple=o,Ro.default=n,Ro}var oh;function Mb(){if(oh)return bi;oh=1,Object.defineProperty(bi,"__esModule",{value:!0});const e=nh(),t={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,e.validateTuple)(r,"items")};return bi.default=t,bi}var ki={},sh;function Ob(){if(sh)return ki;sh=1,Object.defineProperty(ki,"__esModule",{value:!0});const e=Ue(),t=Ge(),r=Pr(),n=th(),s={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:a}})=>(0,e.str)`must NOT have more than ${a} items`,params:({params:{len:a}})=>(0,e._)`{limit: ${a}}`},code(a){const{schema:i,parentSchema:l,it:c}=a,{prefixItems:u}=l;c.items=!0,!(0,t.alwaysValidSchema)(c,i)&&(u?(0,n.validateAdditionalItems)(a,u):a.ok((0,r.validateArray)(a)))}};return ki.default=s,ki}var Ti={},ah;function Nb(){if(ah)return Ti;ah=1,Object.defineProperty(Ti,"__esModule",{value:!0});const e=Ue(),t=Ge(),n={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:o,max:s}})=>s===void 0?(0,e.str)`must contain at least ${o} valid item(s)`:(0,e.str)`must contain at least ${o} and no more than ${s} valid item(s)`,params:({params:{min:o,max:s}})=>s===void 0?(0,e._)`{minContains: ${o}}`:(0,e._)`{minContains: ${o}, maxContains: ${s}}`},code(o){const{gen:s,schema:a,parentSchema:i,data:l,it:c}=o;let u,f;const{minContains:p,maxContains:h}=i;c.opts.next?(u=p===void 0?1:p,f=h):u=1;const m=s.const("len",(0,e._)`${l}.length`);if(o.setParams({min:u,max:f}),f===void 0&&u===0){(0,t.checkStrictMode)(c,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(f!==void 0&&u>f){(0,t.checkStrictMode)(c,'"minContains" > "maxContains" is always invalid'),o.fail();return}if((0,t.alwaysValidSchema)(c,a)){let y=(0,e._)`${m} >= ${u}`;f!==void 0&&(y=(0,e._)`${y} && ${m} <= ${f}`),o.pass(y);return}c.items=!0;const _=s.name("valid");f===void 0&&u===1?w(_,()=>s.if(_,()=>s.break())):u===0?(s.let(_,!0),f!==void 0&&s.if((0,e._)`${l}.length > 0`,g)):(s.let(_,!1),g()),o.result(_,()=>o.reset());function g(){const y=s.name("_valid"),S=s.let("count",0);w(y,()=>s.if(y,()=>v(S)))}function w(y,S){s.forRange("i",0,m,b=>{o.subschema({keyword:"contains",dataProp:b,dataPropType:t.Type.Num,compositeRule:!0},y),S()})}function v(y){s.code((0,e._)`${y}++`),f===void 0?s.if((0,e._)`${y} >= ${u}`,()=>s.assign(_,!0).break()):(s.if((0,e._)`${y} > ${f}`,()=>s.assign(_,!1).break()),u===1?s.assign(_,!0):s.if((0,e._)`${y} >= ${u}`,()=>s.assign(_,!0)))}}};return Ti.default=n,Ti}var Ic={},ih;function Ab(){return ih||(ih=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=Ue(),r=Ge(),n=Pr();e.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const f=c===1?"property":"properties";return(0,t.str)`must have ${f} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:f}})=>(0,t._)`{property: ${l},
6
6
  missingProperty: ${f},
7
7
  depsCount: ${c},
8
- deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);a(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const f in l){if(f==="__proto__")continue;const p=Array.isArray(l[f])?c:u;p[f]=l[f]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:f,it:p}=l;if(Object.keys(c).length===0)return;const h=u.let("missing");for(const m in c){const _=c[m];if(_.length===0)continue;const y=(0,n.propertyInData)(u,f,m,p.opts.ownProperties);l.setParams({property:m,depsCount:_.length,deps:_.join(", ")}),p.allErrors?u.if(y,()=>{for(const w of _)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${y} && (${(0,n.checkMissingProp)(l,_,h)})`),(0,n.reportMissingProp)(l,h),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:f,keyword:p,it:h}=l,m=u.name("valid");for(const _ in c)(0,r.alwaysValidSchema)(h,c[_])||(u.if((0,n.propertyInData)(u,f,_,h.opts.ownProperties),()=>{const y=l.subschema({keyword:p,schemaProp:_},m);l.mergeValidEvaluated(y,m)},()=>u.var(m,!0)),l.ok(m))}e.validateSchemaDeps=i,e.default=o})(kc)),kc}var _i={},sh;function xb(){if(sh)return _i;sh=1,Object.defineProperty(_i,"__esModule",{value:!0});const e=Ne(),t=Ze(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,e._)`{propertyName: ${o.propertyName}}`},code(o){const{gen:s,schema:a,data:i,it:l}=o;if((0,t.alwaysValidSchema)(l,a))return;const c=s.name("valid");s.forIn("key",i,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),s.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||s.break()})}),o.ok(c)}};return _i.default=n,_i}var wi={},ah;function ih(){if(ah)return wi;ah=1,Object.defineProperty(wi,"__esModule",{value:!0});const e=Pr(),t=Ne(),r=Tn(),n=Ze(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,t._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:f,it:p}=a;if(!f)throw new Error("ajv implementation error");const{allErrors:h,opts:m}=p;if(p.props=!0,m.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const _=(0,e.allSchemaProperties)(c.properties),y=(0,e.allSchemaProperties)(c.patternProperties);w(),a.ok((0,t._)`${f} === ${r.default.errors}`);function w(){i.forIn("key",u,k=>{!_.length&&!y.length?S(k):i.if(v(k),()=>S(k))})}function v(k){let C;if(_.length>8){const R=(0,n.schemaRefOrVal)(p,c.properties,"properties");C=(0,e.isOwnProperty)(i,R,k)}else _.length?C=(0,t.or)(..._.map(R=>(0,t._)`${k} === ${R}`)):C=t.nil;return y.length&&(C=(0,t.or)(C,...y.map(R=>(0,t._)`${(0,e.usePattern)(a,R)}.test(${k})`))),(0,t.not)(C)}function g(k){i.code((0,t._)`delete ${u}[${k}]`)}function S(k){if(m.removeAdditional==="all"||m.removeAdditional&&l===!1){g(k);return}if(l===!1){a.setParams({additionalProperty:k}),a.error(),h||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const C=i.name("valid");m.removeAdditional==="failing"?(b(k,C,!1),i.if((0,t.not)(C),()=>{a.reset(),g(k)})):(b(k,C),h||i.if((0,t.not)(C),()=>i.break()))}}function b(k,C,R){const I={keyword:"additionalProperties",dataProp:k,dataPropType:n.Type.Str};R===!1&&Object.assign(I,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(I,C)}}};return wi.default=s,wi}var bi={},lh;function Eb(){if(lh)return bi;lh=1,Object.defineProperty(bi,"__esModule",{value:!0});const e=Ga(),t=Pr(),r=Ze(),n=ih(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const f=(0,t.allSchemaProperties)(i);for(const y of f)u.definedProperties.add(y);u.opts.unevaluated&&f.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(f),u.props));const p=f.filter(y=>!(0,r.alwaysValidSchema)(u,i[y]));if(p.length===0)return;const h=a.name("valid");for(const y of p)m(y)?_(y):(a.if((0,t.propertyInData)(a,c,y,u.opts.ownProperties)),_(y),u.allErrors||a.else().var(h,!0),a.endIf()),s.it.definedProperties.add(y),s.ok(h);function m(y){return u.opts.useDefaults&&!u.compositeRule&&i[y].default!==void 0}function _(y){s.subschema({keyword:"properties",schemaProp:y,dataProp:y},h)}}};return bi.default=o,bi}var Ti={},ch;function $b(){if(ch)return Ti;ch=1,Object.defineProperty(Ti,"__esModule",{value:!0});const e=Pr(),t=Ne(),r=Ze(),n=Ze(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=s,{opts:f}=u,p=(0,e.allSchemaProperties)(i),h=p.filter(S=>(0,r.alwaysValidSchema)(u,i[S]));if(p.length===0||h.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const m=f.strictSchema&&!f.allowMatchingProperties&&c.properties,_=a.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:y}=u;w();function w(){for(const S of p)m&&v(S),u.allErrors?g(S):(a.var(_,!0),g(S),a.if(_))}function v(S){for(const b in m)new RegExp(S).test(b)&&(0,r.checkStrictMode)(u,`property ${b} matches pattern ${S} (use allowMatchingProperties)`)}function g(S){a.forIn("key",l,b=>{a.if((0,t._)`${(0,e.usePattern)(s,S)}.test(${b})`,()=>{const k=h.includes(S);k||s.subschema({keyword:"patternProperties",schemaProp:S,dataProp:b,dataPropType:n.Type.Str},_),u.opts.unevaluated&&y!==!0?a.assign((0,t._)`${y}[${b}]`,!0):!k&&!u.allErrors&&a.if((0,t.not)(_),()=>a.break())})})}}};return Ti.default=o,Ti}var ki={},uh;function Rb(){if(uh)return ki;uh=1,Object.defineProperty(ki,"__esModule",{value:!0});const e=Ze(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:s}=r;if((0,e.alwaysValidSchema)(s,o)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return ki.default=t,ki}var Si={},dh;function Pb(){if(dh)return Si;dh=1,Object.defineProperty(Si,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Pr().validateUnion,error:{message:"must match a schema in anyOf"}};return Si.default=t,Si}var Ci={},ph;function Mb(){if(ph)return Ci;ph=1,Object.defineProperty(Ci,"__esModule",{value:!0});const e=Ne(),t=Ze(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:a,parentSchema:i,it:l}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=a,u=s.let("valid",!1),f=s.let("passing",null),p=s.name("_valid");o.setParams({passing:f}),s.block(h),o.result(u,()=>o.reset(),()=>o.error(!0));function h(){c.forEach((m,_)=>{let y;(0,t.alwaysValidSchema)(l,m)?s.var(p,!0):y=o.subschema({keyword:"oneOf",schemaProp:_,compositeRule:!0},p),_>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(f,(0,e._)`[${f}, ${_}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(f,_),y&&o.mergeEvaluated(y,e.Name)})})}}};return Ci.default=n,Ci}var Ii={},fh;function Nb(){if(fh)return Ii;fh=1,Object.defineProperty(Ii,"__esModule",{value:!0});const e=Ze(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const a=n.name("valid");o.forEach((i,l)=>{if((0,e.alwaysValidSchema)(s,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},a);r.ok(a),r.mergeEvaluated(c)})}};return Ii.default=t,Ii}var xi={},hh;function Ob(){if(hh)return xi;hh=1,Object.defineProperty(xi,"__esModule",{value:!0});const e=Ne(),t=Ze(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:a,parentSchema:i,it:l}=s;i.then===void 0&&i.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const f=a.let("valid",!0),p=a.name("_valid");if(h(),s.reset(),c&&u){const _=a.let("ifClause");s.setParams({ifClause:_}),a.if(p,m("then",_),m("else",_))}else c?a.if(p,m("then")):a.if((0,e.not)(p),m("else"));s.pass(f,()=>s.error(!0));function h(){const _=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(_)}function m(_,y){return()=>{const w=s.subschema({keyword:_},p);a.assign(f,p),s.mergeValidEvaluated(w,f),y?a.assign(y,(0,e._)`${_}`):s.setParams({ifClause:_})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return xi.default=n,xi}var Ei={},mh;function Ab(){if(mh)return Ei;mh=1,Object.defineProperty(Ei,"__esModule",{value:!0});const e=Ze(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:o}){n.if===void 0&&(0,e.checkStrictMode)(o,`"${r}" without "if" is ignored`)}};return Ei.default=t,Ei}var gh;function qb(){if(gh)return mi;gh=1,Object.defineProperty(mi,"__esModule",{value:!0});const e=Qf(),t=kb(),r=eh(),n=Sb(),o=Cb(),s=Ib(),a=xb(),i=ih(),l=Eb(),c=$b(),u=Rb(),f=Pb(),p=Mb(),h=Nb(),m=Ob(),_=Ab();function y(w=!1){const v=[u.default,f.default,p.default,h.default,m.default,_.default,a.default,i.default,s.default,l.default,c.default];return w?v.push(t.default,n.default):v.push(e.default,r.default),v.push(o.default),v}return mi.default=y,mi}var $i={},Ri={},yh;function Lb(){if(yh)return Ri;yh=1,Object.defineProperty(Ri,"__esModule",{value:!0});const e=Ne(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:a,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:f,errSchemaPath:p,schemaEnv:h,self:m}=u;if(!f.validateFormats)return;i?_():y();function _(){const w=s.scopeValue("formats",{ref:m.formats,code:f.code.formats}),v=s.const("fDef",(0,e._)`${w}[${c}]`),g=s.let("fType"),S=s.let("format");s.if((0,e._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>s.assign(g,(0,e._)`${v}.type || "string"`).assign(S,(0,e._)`${v}.validate`),()=>s.assign(g,(0,e._)`"string"`).assign(S,v)),n.fail$data((0,e.or)(b(),k()));function b(){return f.strictSchema===!1?e.nil:(0,e._)`${c} && !${S}`}function k(){const C=h.$async?(0,e._)`(${v}.async ? await ${S}(${a}) : ${S}(${a}))`:(0,e._)`${S}(${a})`,R=(0,e._)`(typeof ${S} == "function" ? ${C} : ${S}.test(${a}))`;return(0,e._)`${S} && ${S} !== true && ${g} === ${o} && !${R}`}}function y(){const w=m.formats[l];if(!w){b();return}if(w===!0)return;const[v,g,S]=k(w);v===o&&n.pass(C());function b(){if(f.strictSchema===!1){m.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function k(R){const I=R instanceof RegExp?(0,e.regexpCode)(R):f.code.formats?(0,e._)`${f.code.formats}${(0,e.getProperty)(l)}`:void 0,j=s.scopeValue("formats",{key:l,ref:R,code:I});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,e._)`${j}.validate`]:["string",R,j]}function C(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!h.$async)throw new Error("async format in sync schema");return(0,e._)`await ${S}(${a})`}return typeof g=="function"?(0,e._)`${S}(${a})`:(0,e._)`${S}.test(${a})`}}}};return Ri.default=r,Ri}var vh;function jb(){if(vh)return $i;vh=1,Object.defineProperty($i,"__esModule",{value:!0});const t=[Lb().default];return $i.default=t,$i}var Wn={},_h;function Db(){return _h||(_h=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.contentVocabulary=Wn.metadataVocabulary=void 0,Wn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Wn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Wn}var wh;function Ub(){if(wh)return Xa;wh=1,Object.defineProperty(Xa,"__esModule",{value:!0});const e=ub(),t=Tb(),r=qb(),n=jb(),o=Db(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return Xa.default=s,Xa}var Pi={},ps={},bh;function zb(){if(bh)return ps;bh=1,Object.defineProperty(ps,"__esModule",{value:!0}),ps.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(ps.DiscrError=e={})),ps}var Th;function Zb(){if(Th)return Pi;Th=1,Object.defineProperty(Pi,"__esModule",{value:!0});const e=Ne(),t=zb(),r=_c(),n=Ya(),o=Ze(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,e._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:f,it:p}=i,{oneOf:h}=f;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const m=u.propertyName;if(typeof m!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");const _=l.let("valid",!1),y=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(m)}`);l.if((0,e._)`typeof ${y} == "string"`,()=>w(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:y,tagName:m})),i.ok(_);function w(){const S=g();l.if(!1);for(const b in S)l.elseIf((0,e._)`${y} === ${b}`),l.assign(_,v(S[b]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:y,tagName:m}),l.endIf()}function v(S){const b=l.name("valid"),k=i.subschema({keyword:"oneOf",schemaProp:S},b);return i.mergeEvaluated(k,e.Name),b}function g(){var S;const b={},k=R(f);let C=!0;for(let N=0;N<h.length;N++){let L=h[N];if(L?.$ref&&!(0,o.schemaHasRulesButRef)(L,p.self.RULES)){const H=L.$ref;if(L=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,H),L instanceof r.SchemaEnv&&(L=L.schema),L===void 0)throw new n.default(p.opts.uriResolver,p.baseId,H)}const z=(S=L?.properties)===null||S===void 0?void 0:S[m];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${m}"`);C=C&&(k||R(L)),I(z,N)}if(!C)throw new Error(`discriminator: "${m}" must be required`);return b;function R({required:N}){return Array.isArray(N)&&N.includes(m)}function I(N,L){if(N.const)j(N.const,L);else if(N.enum)for(const z of N.enum)j(z,L);else throw new Error(`discriminator: "properties/${m}" must have "const" or "enum"`)}function j(N,L){if(typeof N!="string"||N in b)throw new Error(`discriminator: "${m}" values must be unique strings`);b[N]=L}}}};return Pi.default=a,Pi}const Fb={$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 kh;function Sh(){return kh||(kh=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=ib(),n=Ub(),o=Zb(),s=Fb,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const m=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(m,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=Ga();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Ne();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var f=vc();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=Ya();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(Za,Za.exports)),Za.exports}var Vb=Sh();const Ch=Vn(Vb);var De;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(i=>typeof o[o[i]]!="number"),a={};for(const i of s)a[i]=o[i];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(De||(De={}));var Sc;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Sc||(Sc={}));const ue=De.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),an=e=>{switch(typeof e){case"undefined":return ue.undefined;case"string":return ue.string;case"number":return Number.isNaN(e)?ue.nan:ue.number;case"boolean":return ue.boolean;case"function":return ue.function;case"bigint":return ue.bigint;case"symbol":return ue.symbol;case"object":return Array.isArray(e)?ue.array:e===null?ue.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ue.promise:typeof Map<"u"&&e instanceof Map?ue.map:typeof Set<"u"&&e instanceof Set?ue.set:typeof Date<"u"&&e instanceof Date?ue.date:ue.object;default:return ue.unknown}},re=De.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Hb=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class cr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof cr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,De.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r={},n=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}cr.create=e=>new cr(e);const ko=(e,t)=>{let r;switch(e.code){case re.invalid_type:e.received===ue.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case re.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,De.jsonStringifyReplacer)}`;break;case re.unrecognized_keys:r=`Unrecognized key(s) in object: ${De.joinValues(e.keys,", ")}`;break;case re.invalid_union:r="Invalid input";break;case re.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${De.joinValues(e.options)}`;break;case re.invalid_enum_value:r=`Invalid enum value. Expected ${De.joinValues(e.options)}, received '${e.received}'`;break;case re.invalid_arguments:r="Invalid function arguments";break;case re.invalid_return_type:r="Invalid function return type";break;case re.invalid_date:r="Invalid date";break;case re.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:De.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case re.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case re.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case re.custom:r="Invalid input";break;case re.invalid_intersection_types:r="Intersection results could not be merged";break;case re.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case re.not_finite:r="Number must be finite";break;default:r=t.defaultError,De.assertNever(e)}return{message:r}};let Ih=ko;function Bb(e){Ih=e}function Mi(){return Ih}const Ni=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)i=c(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}},Wb=[];function le(e,t){const r=Mi(),n=Ni({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===ko?void 0:ko].filter(o=>!!o)});e.common.issues.push(n)}class jt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return Ce;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const s=await o.key,a=await o.value;n.push({key:s,value:a})}return jt.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return Ce;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:t.value,value:n}}}const Ce=Object.freeze({status:"aborted"}),So=e=>({status:"dirty",value:e}),Ht=e=>({status:"valid",value:e}),Cc=e=>e.status==="aborted",Ic=e=>e.status==="dirty",Gn=e=>e.status==="valid",fs=e=>typeof Promise<"u"&&e instanceof Promise;var ye;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ye||(ye={}));class Jr{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const xh=(e,t)=>{if(Gn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new cr(e.common.issues);return this._error=r,this._error}}};function Re(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,i)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:o}}let Pe=class{get description(){return this._def.description}_getType(t){return an(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:an(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new jt,ctx:{common:t.parent.common,data:t.data,parsedType:an(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(fs(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:an(t)},o=this._parseSync({data:t,path:n.path,parent:n});return xh(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:an(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return Gn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Gn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:an(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(fs(o)?o:Promise.resolve(o));return xh(n,s)}refine(t,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:re.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new Mr({schema:this,typeName:B.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Nr.create(this,this._def)}nullable(){return Cn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yn.create(this)}promise(){return $o.create(this,this._def)}or(t){return vs.create([this,t],this._def)}and(t){return _s.create(this,t,this._def)}transform(t){return new Mr({...Re(this._def),schema:this,typeName:B.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new Ss({...Re(this._def),innerType:this,defaultValue:r,typeName:B.ZodDefault})}brand(){return new $c({typeName:B.ZodBranded,type:this,...Re(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new Cs({...Re(this._def),innerType:this,catchValue:r,typeName:B.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Is.create(this,t)}readonly(){return xs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Gb=/^c[^\s-]{8,}$/i,Jb=/^[0-9a-z]+$/,Kb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yb=/^[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,Qb=/^[a-z0-9_-]{21}$/i,Xb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,e3=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,t3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,r3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let xc;const n3=/^(?:(?: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])$/,o3=/^(?:(?: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])$/,s3=/^(([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]))$/,a3=/^(([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])$/,i3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,l3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Eh="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",c3=new RegExp(`^${Eh}$`);function $h(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function u3(e){return new RegExp(`^${$h(e)}$`)}function Rh(e){let t=`${Eh}T${$h(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function d3(e,t){return!!((t==="v4"||!t)&&n3.test(e)||(t==="v6"||!t)&&s3.test(e))}function p3(e,t){if(!Xb.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function f3(e,t){return!!((t==="v4"||!t)&&o3.test(e)||(t==="v6"||!t)&&a3.test(e))}let Co=class za extends Pe{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ue.string){const s=this._getOrReturnCtx(t);return le(s,{code:re.invalid_type,expected:ue.string,received:s.parsedType}),Ce}const n=new jt;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),le(o,{code:re.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),le(o,{code:re.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(t,o),a?le(o,{code:re.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&le(o,{code:re.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")t3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"email",code:re.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")xc||(xc=new RegExp(r3,"u")),xc.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"emoji",code:re.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Yb.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"uuid",code:re.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Qb.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"nanoid",code:re.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Gb.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"cuid",code:re.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Jb.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"cuid2",code:re.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Kb.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"ulid",code:re.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),le(o,{validation:"url",code:re.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"regex",code:re.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),le(o,{code:re.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),le(o,{code:re.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),le(o,{code:re.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Rh(s).test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{code:re.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?c3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{code:re.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?u3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{code:re.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?e3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"duration",code:re.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?d3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"ip",code:re.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?p3(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"jwt",code:re.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?f3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"cidr",code:re.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?i3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"base64",code:re.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?l3.test(t.data)||(o=this._getOrReturnCtx(t,o),le(o,{validation:"base64url",code:re.invalid_string,message:s.message}),n.dirty()):De.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:re.invalid_string,...ye.errToObj(n)})}_addCheck(t){return new za({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ye.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ye.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ye.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ye.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ye.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ye.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ye.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ye.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ye.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ye.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ye.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ye.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ye.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ye.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ye.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ye.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...ye.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...ye.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...ye.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...ye.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...ye.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...ye.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...ye.errToObj(r)})}nonempty(t){return this.min(1,ye.errToObj(t))}trim(){return new za({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new za({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new za({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Co.create=e=>new Co({checks:[],typeName:B.ZodString,coerce:e?.coerce??!1,...Re(e)});function h3(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}let hs=class Qp extends Pe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ue.number){const s=this._getOrReturnCtx(t);return le(s,{code:re.invalid_type,expected:ue.number,received:s.parsedType}),Ce}let n;const o=new jt;for(const s of this._def.checks)s.kind==="int"?De.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),le(n,{code:re.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:re.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:re.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?h3(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),le(n,{code:re.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),le(n,{code:re.not_finite,message:s.message}),o.dirty()):De.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,ye.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ye.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ye.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ye.toString(r))}setLimit(t,r,n,o){return new Qp({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ye.toString(o)}]})}_addCheck(t){return new Qp({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ye.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ye.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ye.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ye.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ye.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ye.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:ye.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ye.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ye.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&De.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};hs.create=e=>new hs({checks:[],typeName:B.ZodNumber,coerce:e?.coerce||!1,...Re(e)});class Sn extends Pe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ue.bigint)return this._getInvalidInput(t);let n;const o=new jt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:re.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:re.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),le(n,{code:re.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):De.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return le(r,{code:re.invalid_type,expected:ue.bigint,received:r.parsedType}),Ce}gte(t,r){return this.setLimit("min",t,!0,ye.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ye.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ye.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ye.toString(r))}setLimit(t,r,n,o){return new Sn({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ye.toString(o)}]})}_addCheck(t){return new Sn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ye.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ye.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ye.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ye.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ye.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}Sn.create=e=>new Sn({checks:[],typeName:B.ZodBigInt,coerce:e?.coerce??!1,...Re(e)});let ms=class extends Pe{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ue.boolean){const n=this._getOrReturnCtx(t);return le(n,{code:re.invalid_type,expected:ue.boolean,received:n.parsedType}),Ce}return Ht(t.data)}};ms.create=e=>new ms({typeName:B.ZodBoolean,coerce:e?.coerce||!1,...Re(e)});class Jn extends Pe{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ue.date){const s=this._getOrReturnCtx(t);return le(s,{code:re.invalid_type,expected:ue.date,received:s.parsedType}),Ce}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return le(s,{code:re.invalid_date}),Ce}const n=new jt;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),le(o,{code:re.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),le(o,{code:re.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):De.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Jn({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:ye.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:ye.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}}Jn.create=e=>new Jn({checks:[],coerce:e?.coerce||!1,typeName:B.ZodDate,...Re(e)});class Oi extends Pe{_parse(t){if(this._getType(t)!==ue.symbol){const n=this._getOrReturnCtx(t);return le(n,{code:re.invalid_type,expected:ue.symbol,received:n.parsedType}),Ce}return Ht(t.data)}}Oi.create=e=>new Oi({typeName:B.ZodSymbol,...Re(e)});class gs extends Pe{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return le(n,{code:re.invalid_type,expected:ue.undefined,received:n.parsedType}),Ce}return Ht(t.data)}}gs.create=e=>new gs({typeName:B.ZodUndefined,...Re(e)});let ys=class extends Pe{_parse(t){if(this._getType(t)!==ue.null){const n=this._getOrReturnCtx(t);return le(n,{code:re.invalid_type,expected:ue.null,received:n.parsedType}),Ce}return Ht(t.data)}};ys.create=e=>new ys({typeName:B.ZodNull,...Re(e)});let Io=class extends Pe{constructor(){super(...arguments),this._any=!0}_parse(t){return Ht(t.data)}};Io.create=e=>new Io({typeName:B.ZodAny,...Re(e)});let Kn=class extends Pe{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Ht(t.data)}};Kn.create=e=>new Kn({typeName:B.ZodUnknown,...Re(e)});let ln=class extends Pe{_parse(t){const r=this._getOrReturnCtx(t);return le(r,{code:re.invalid_type,expected:ue.never,received:r.parsedType}),Ce}};ln.create=e=>new ln({typeName:B.ZodNever,...Re(e)});class Ai extends Pe{_parse(t){if(this._getType(t)!==ue.undefined){const n=this._getOrReturnCtx(t);return le(n,{code:re.invalid_type,expected:ue.void,received:n.parsedType}),Ce}return Ht(t.data)}}Ai.create=e=>new Ai({typeName:B.ZodVoid,...Re(e)});let Yn=class uc extends Pe{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ue.array)return le(r,{code:re.invalid_type,expected:ue.array,received:r.parsedType}),Ce;if(o.exactLength!==null){const a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(le(r,{code:a?re.too_big:re.too_small,minimum:i?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(le(r,{code:re.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(le(r,{code:re.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>o.type._parseAsync(new Jr(r,a,r.path,i)))).then(a=>jt.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Jr(r,a,r.path,i)));return jt.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new uc({...this._def,minLength:{value:t,message:ye.toString(r)}})}max(t,r){return new uc({...this._def,maxLength:{value:t,message:ye.toString(r)}})}length(t,r){return new uc({...this._def,exactLength:{value:t,message:ye.toString(r)}})}nonempty(t){return this.min(1,t)}};Yn.create=(e,t)=>new Yn({type:e,minLength:null,maxLength:null,exactLength:null,typeName:B.ZodArray,...Re(t)});function xo(e){if(e instanceof wr){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Nr.create(xo(n))}return new wr({...e._def,shape:()=>t})}else return e instanceof Yn?new Yn({...e._def,type:xo(e.element)}):e instanceof Nr?Nr.create(xo(e.unwrap())):e instanceof Cn?Cn.create(xo(e.unwrap())):e instanceof Kr?Kr.create(e.items.map(t=>xo(t))):e}let wr=class Gr extends Pe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=De.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ue.object){const c=this._getOrReturnCtx(t);return le(c,{code:re.invalid_type,expected:ue.object,received:c.parsedType}),Ce}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof ln&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||i.push(c);const l=[];for(const c of a){const u=s[c],f=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Jr(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof ln){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")i.length>0&&(le(o,{code:re.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 f=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Jr(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const f=await u.key,p=await u.value;c.push({key:f,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>jt.mergeObjectSync(n,c)):jt.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return ye.errToObj,new Gr({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:ye.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Gr({...this._def,unknownKeys:"strip"})}passthrough(){return new Gr({...this._def,unknownKeys:"passthrough"})}extend(t){return new Gr({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Gr({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:B.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new Gr({...this._def,catchall:t})}pick(t){const r={};for(const n of De.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Gr({...this._def,shape:()=>r})}omit(t){const r={};for(const n of De.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new Gr({...this._def,shape:()=>r})}deepPartial(){return xo(this)}partial(t){const r={};for(const n of De.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new Gr({...this._def,shape:()=>r})}required(t){const r={};for(const n of De.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Nr;)s=s._def.innerType;r[n]=s}return new Gr({...this._def,shape:()=>r})}keyof(){return Nh(De.objectKeys(this.shape))}};wr.create=(e,t)=>new wr({shape:()=>e,unknownKeys:"strip",catchall:ln.create(),typeName:B.ZodObject,...Re(t)}),wr.strictCreate=(e,t)=>new wr({shape:()=>e,unknownKeys:"strict",catchall:ln.create(),typeName:B.ZodObject,...Re(t)}),wr.lazycreate=(e,t)=>new wr({shape:e,unknownKeys:"strip",catchall:ln.create(),typeName:B.ZodObject,...Re(t)});let vs=class extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new cr(i.ctx.common.issues));return le(r,{code:re.invalid_union,unionErrors:a}),Ce}if(r.common.async)return Promise.all(n.map(async s=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new cr(l));return le(r,{code:re.invalid_union,unionErrors:i}),Ce}}get options(){return this._def.options}};vs.create=(e,t)=>new vs({options:e,typeName:B.ZodUnion,...Re(t)});const cn=e=>e instanceof ws?cn(e.schema):e instanceof Mr?cn(e.innerType()):e instanceof bs?[e.value]:e instanceof Ts?e.options:e instanceof ks?De.objectValues(e.enum):e instanceof Ss?cn(e._def.innerType):e instanceof gs?[void 0]:e instanceof ys?[null]:e instanceof Nr?[void 0,...cn(e.unwrap())]:e instanceof Cn?[null,...cn(e.unwrap())]:e instanceof $c||e instanceof xs?cn(e.unwrap()):e instanceof Cs?cn(e._def.innerType):[];let Ph=class Bw extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ue.object)return le(r,{code:re.invalid_type,expected:ue.object,received:r.parsedType}),Ce;const n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(le(r,{code:re.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Ce)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){const o=new Map;for(const s of r){const a=cn(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const i of a){if(o.has(i))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(i)}`);o.set(i,s)}}return new Bw({typeName:B.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...Re(n)})}};function Ec(e,t){const r=an(e),n=an(t);if(e===t)return{valid:!0,data:e};if(r===ue.object&&n===ue.object){const o=De.objectKeys(t),s=De.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=Ec(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(r===ue.array&&n===ue.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],i=t[s],l=Ec(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===ue.date&&n===ue.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}let _s=class extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if(Cc(s)||Cc(a))return Ce;const i=Ec(s.value,a.value);return i.valid?((Ic(s)||Ic(a))&&r.dirty(),{status:r.value,value:i.data}):(le(n,{code:re.invalid_intersection_types}),Ce)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};_s.create=(e,t,r)=>new _s({left:e,right:t,typeName:B.ZodIntersection,...Re(r)});class Kr extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.array)return le(n,{code:re.invalid_type,expected:ue.array,received:n.parsedType}),Ce;if(n.data.length<this._def.items.length)return le(n,{code:re.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ce;!this._def.rest&&n.data.length>this._def.items.length&&(le(n,{code:re.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new Jr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>jt.mergeArray(r,a)):jt.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new Kr({...this._def,rest:t})}}Kr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Kr({items:e,typeName:B.ZodTuple,rest:null,...Re(t)})};let Mh=class Xp extends Pe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.object)return le(n,{code:re.invalid_type,expected:ue.object,received:n.parsedType}),Ce;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in n.data)o.push({key:s._parse(new Jr(n,i,n.path,i)),value:a._parse(new Jr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?jt.mergeObjectAsync(r,o):jt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Pe?new Xp({keyType:t,valueType:r,typeName:B.ZodRecord,...Re(n)}):new Xp({keyType:Co.create(),valueType:t,typeName:B.ZodRecord,...Re(r)})}};class qi extends Pe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.map)return le(n,{code:re.invalid_type,expected:ue.map,received:n.parsedType}),Ce;const o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new Jr(n,i,n.path,[c,"key"])),value:s._parse(new Jr(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 Ce;(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 Ce;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}qi.create=(e,t,r)=>new qi({valueType:t,keyType:e,typeName:B.ZodMap,...Re(r)});class Qn extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ue.set)return le(n,{code:re.invalid_type,expected:ue.set,received:n.parsedType}),Ce;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(le(n,{code:re.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(le(n,{code:re.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const u of l){if(u.status==="aborted")return Ce;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...n.data.values()].map((l,c)=>s._parse(new Jr(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new Qn({...this._def,minSize:{value:t,message:ye.toString(r)}})}max(t,r){return new Qn({...this._def,maxSize:{value:t,message:ye.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}Qn.create=(e,t)=>new Qn({valueType:e,minSize:null,maxSize:null,typeName:B.ZodSet,...Re(t)});class Eo extends Pe{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ue.function)return le(r,{code:re.invalid_type,expected:ue.function,received:r.parsedType}),Ce;function n(i,l){return Ni({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Mi(),ko].filter(c=>!!c),issueData:{code:re.invalid_arguments,argumentsError:l}})}function o(i,l){return Ni({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Mi(),ko].filter(c=>!!c),issueData:{code:re.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof $o){const i=this;return Ht(async function(...l){const c=new cr([]),u=await i._def.args.parseAsync(l,s).catch(h=>{throw c.addIssue(n(l,h)),c}),f=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(f,s).catch(h=>{throw c.addIssue(o(f,h)),c})})}else{const i=this;return Ht(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new cr([n(l,c.error)]);const u=Reflect.apply(a,this,c.data),f=i._def.returns.safeParse(u,s);if(!f.success)throw new cr([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Eo({...this._def,args:Kr.create(t).rest(Kn.create())})}returns(t){return new Eo({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new Eo({args:t||Kr.create([]).rest(Kn.create()),returns:r||Kn.create(),typeName:B.ZodFunction,...Re(n)})}}let ws=class extends Pe{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ws.create=(e,t)=>new ws({getter:e,typeName:B.ZodLazy,...Re(t)});let bs=class extends Pe{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return le(r,{received:r.data,code:re.invalid_literal,expected:this._def.value}),Ce}return{status:"valid",value:t.data}}get value(){return this._def.value}};bs.create=(e,t)=>new bs({value:e,typeName:B.ZodLiteral,...Re(t)});function Nh(e,t){return new Ts({values:e,typeName:B.ZodEnum,...Re(t)})}let Ts=class ef extends Pe{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return le(r,{expected:De.joinValues(n),received:r.parsedType,code:re.invalid_type}),Ce}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return le(r,{received:r.data,code:re.invalid_enum_value,options:n}),Ce}return Ht(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return ef.create(t,{...this._def,...r})}exclude(t,r=this._def){return ef.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};Ts.create=Nh;class ks extends Pe{_parse(t){const r=De.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==ue.string&&n.parsedType!==ue.number){const o=De.objectValues(r);return le(n,{expected:De.joinValues(o),received:n.parsedType,code:re.invalid_type}),Ce}if(this._cache||(this._cache=new Set(De.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=De.objectValues(r);return le(n,{received:n.data,code:re.invalid_enum_value,options:o}),Ce}return Ht(t.data)}get enum(){return this._def.values}}ks.create=(e,t)=>new ks({values:e,typeName:B.ZodNativeEnum,...Re(t)});class $o extends Pe{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ue.promise&&r.common.async===!1)return le(r,{code:re.invalid_type,expected:ue.promise,received:r.parsedType}),Ce;const n=r.parsedType===ue.promise?r.data:Promise.resolve(r.data);return Ht(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}$o.create=(e,t)=>new $o({type:e,typeName:B.ZodPromise,...Re(t)});class Mr extends Pe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{le(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return Ce;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?Ce:l.status==="dirty"||r.value==="dirty"?So(l.value):l});{if(r.value==="aborted")return Ce;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?Ce:i.status==="dirty"||r.value==="dirty"?So(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,s);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Ce:(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"?Ce:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(o.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Gn(a))return Ce;const i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Gn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):Ce);De.assertNever(o)}}Mr.create=(e,t,r)=>new Mr({schema:e,typeName:B.ZodEffects,effect:t,...Re(r)}),Mr.createWithPreprocess=(e,t,r)=>new Mr({schema:t,effect:{type:"preprocess",transform:e},typeName:B.ZodEffects,...Re(r)});let Nr=class extends Pe{_parse(t){return this._getType(t)===ue.undefined?Ht(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Nr.create=(e,t)=>new Nr({innerType:e,typeName:B.ZodOptional,...Re(t)});let Cn=class extends Pe{_parse(t){return this._getType(t)===ue.null?Ht(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Cn.create=(e,t)=>new Cn({innerType:e,typeName:B.ZodNullable,...Re(t)});let Ss=class extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===ue.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ss.create=(e,t)=>new Ss({innerType:e,typeName:B.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Re(t)});let Cs=class extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return fs(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new cr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new cr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Cs.create=(e,t)=>new Cs({innerType:e,typeName:B.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Re(t)});class Li extends Pe{_parse(t){if(this._getType(t)!==ue.nan){const n=this._getOrReturnCtx(t);return le(n,{code:re.invalid_type,expected:ue.nan,received:n.parsedType}),Ce}return{status:"valid",value:t.data}}}Li.create=e=>new Li({typeName:B.ZodNaN,...Re(e)});const m3=Symbol("zod_brand");class $c extends Pe{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Is extends Pe{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Ce:s.status==="dirty"?(r.dirty(),So(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Ce:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new Is({in:t,out:r,typeName:B.ZodPipeline})}}let xs=class extends Pe{_parse(t){const r=this._def.innerType._parse(t),n=o=>(Gn(o)&&(o.value=Object.freeze(o.value)),o);return fs(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};xs.create=(e,t)=>new xs({innerType:e,typeName:B.ZodReadonly,...Re(t)});function Oh(e,t){const r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Ah(e,t={},r){return e?Io.create().superRefine((n,o)=>{const s=e(n);if(s instanceof Promise)return s.then(a=>{if(!a){const i=Oh(t,n),l=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:l})}});if(!s){const a=Oh(t,n),i=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:i})}}):Io.create()}const g3={object:wr.lazycreate};var B;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(B||(B={}));const y3=(e,t={message:`Input not instance of ${e.name}`})=>Ah(r=>r instanceof e,t),Fe=Co.create,br=hs.create,v3=Li.create,_3=Sn.create,qh=ms.create,w3=Jn.create,b3=Oi.create,T3=gs.create,k3=ys.create,S3=Io.create,C3=Kn.create,I3=ln.create,x3=Ai.create,un=Yn.create,Qt=wr.create,E3=wr.strictCreate,ji=vs.create,$3=Ph.create,R3=_s.create,P3=Kr.create,M3=Mh.create,N3=qi.create,O3=Qn.create,A3=Eo.create,q3=ws.create,L3=bs.create,Es=Ts.create,j3=ks.create,D3=$o.create,Lh=Mr.create,U3=Nr.create,z3=Cn.create,Z3=Mr.createWithPreprocess,F3=Is.create,V3=Object.freeze(Object.defineProperty({__proto__:null,BRAND:m3,DIRTY:So,EMPTY_PATH:Wb,INVALID:Ce,NEVER:Ce,OK:Ht,ParseStatus:jt,Schema:Pe,ZodAny:Io,ZodArray:Yn,ZodBigInt:Sn,ZodBoolean:ms,ZodBranded:$c,ZodCatch:Cs,ZodDate:Jn,ZodDefault:Ss,ZodDiscriminatedUnion:Ph,ZodEffects:Mr,ZodEnum:Ts,ZodError:cr,get ZodFirstPartyTypeKind(){return B},ZodFunction:Eo,ZodIntersection:_s,ZodIssueCode:re,ZodLazy:ws,ZodLiteral:bs,ZodMap:qi,ZodNaN:Li,ZodNativeEnum:ks,ZodNever:ln,ZodNull:ys,ZodNullable:Cn,ZodNumber:hs,ZodObject:wr,ZodOptional:Nr,ZodParsedType:ue,ZodPipeline:Is,ZodPromise:$o,ZodReadonly:xs,ZodRecord:Mh,ZodSchema:Pe,ZodSet:Qn,ZodString:Co,ZodSymbol:Oi,ZodTransformer:Mr,ZodTuple:Kr,ZodType:Pe,ZodUndefined:gs,ZodUnion:vs,ZodUnknown:Kn,ZodVoid:Ai,addIssueToContext:le,any:S3,array:un,bigint:_3,boolean:qh,coerce:{string:(e=>Co.create({...e,coerce:!0})),number:(e=>hs.create({...e,coerce:!0})),boolean:(e=>ms.create({...e,coerce:!0})),bigint:(e=>Sn.create({...e,coerce:!0})),date:(e=>Jn.create({...e,coerce:!0}))},custom:Ah,date:w3,datetimeRegex:Rh,defaultErrorMap:ko,discriminatedUnion:$3,effect:Lh,enum:Es,function:A3,getErrorMap:Mi,getParsedType:an,instanceof:y3,intersection:R3,isAborted:Cc,isAsync:fs,isDirty:Ic,isValid:Gn,late:g3,lazy:q3,literal:L3,makeIssue:Ni,map:N3,nan:v3,nativeEnum:j3,never:I3,null:k3,nullable:z3,number:br,object:Qt,get objectUtil(){return Sc},oboolean:()=>qh().optional(),onumber:()=>br().optional(),optional:U3,ostring:()=>Fe().optional(),pipeline:F3,preprocess:Z3,promise:D3,quotelessJson:Hb,record:M3,set:O3,setErrorMap:Bb,strictObject:E3,string:Fe,symbol:b3,transformer:Lh,tuple:P3,undefined:T3,union:ji,unknown:C3,get util(){return De},void:x3},Symbol.toStringTag,{value:"Module"})),jh=Object.freeze({status:"aborted"});function J(e,t,r){function n(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(e),t(i,l);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=l}const o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const c=r?.Parent?new s:this;n(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class $s extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Dh={};function In(e){return Dh}function Uh(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function H3(e,t){return typeof t=="bigint"?t.toString():t}function Rc(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Pc(e){return e==null}function Mc(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function B3(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function Be(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Rs(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ps(e){return JSON.stringify(e)}const zh=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Di(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const W3=Rc(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ui(e){if(Di(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(Di(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const G3=new Set(["string","number","symbol"]);function Ms(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xn(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function ge(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function J3(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const K3={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 Y3(e,t){const r={},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return xn(e,{...e._zod.def,shape:r,checks:[]})}function Q3(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return xn(e,{...e._zod.def,shape:r,checks:[]})}function X3(e,t){if(!Ui(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return Rs(this,"shape",n),n},checks:[]};return xn(e,r)}function eT(e,t){return xn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return Rs(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function tT(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(const s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return xn(t,{...t._zod.def,shape:o,checks:[]})}function rT(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return xn(t,{...t._zod.def,shape:o,checks:[]})}function Ns(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Xn(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function zi(e){return typeof e=="string"?e:e?.message}function En(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=zi(e.inst?._zod.def?.error?.(e))??zi(t?.error?.(e))??zi(r.customError?.(e))??zi(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Nc(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Os(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Zh=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,H3,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Fh=J("$ZodError",Zh),Zi=J("$ZodError",Zh,{Parent:Error});function nT(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function oT(e,t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>o({issues:i}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(e),n}const Vh=e=>(t,r,n,o)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new $s;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>En(l,s,In())));throw zh(i,o?.callee),i}return a.value},sT=Vh(Zi),Hh=e=>async(t,r,n,o)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>En(l,s,In())));throw zh(i,o?.callee),i}return a.value},aT=Hh(Zi),Bh=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new $s;return s.issues.length?{success:!1,error:new(e??Fh)(s.issues.map(a=>En(a,o,In())))}:{success:!0,data:s.value}},Oc=Bh(Zi),Wh=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>En(a,o,In())))}:{success:!0,data:s.value}},Ac=Wh(Zi),iT=/^[cC][^\s-]{8,}$/,lT=/^[0-9a-z]+$/,cT=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,uT=/^[0-9a-vA-V]{20}$/,dT=/^[A-Za-z0-9]{27}$/,pT=/^[a-zA-Z0-9_-]{21}$/,fT=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,hT=/^([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})$/,Gh=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,mT=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,gT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function yT(){return new RegExp(gT,"u")}const vT=/^(?:(?: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])$/,_T=/^(([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})$/,wT=/^((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])$/,bT=/^(([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])$/,TT=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Jh=/^[A-Za-z0-9_-]*$/,kT=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,ST=/^\+(?:[0-9]){6,14}[0-9]$/,Kh="(?:(?:\\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])))",CT=new RegExp(`^${Kh}$`);function Yh(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function IT(e){return new RegExp(`^${Yh(e)}$`)}function xT(e){const t=Yh({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Kh}T(?:${n})$`)}const ET=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},$T=/^\d+$/,RT=/^-?\d+(?:\.\d+)?/i,PT=/true|false/i,MT=/null/i,NT=/^[^A-Z]*$/,OT=/^[^a-z]*$/,Xt=J("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Qh={number:"number",bigint:"bigint",object:"date"},Xh=J("$ZodCheckLessThan",(e,t)=>{Xt.init(e,t);const r=Qh[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),em=J("$ZodCheckGreaterThan",(e,t)=>{Xt.init(e,t);const r=Qh[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),AT=J("$ZodCheckMultipleOf",(e,t)=>{Xt.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):B3(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),qT=J("$ZodCheckNumberFormat",(e,t)=>{Xt.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=K3[t.format];e._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,i.minimum=o,i.maximum=s,r&&(i.pattern=$T)}),e._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:t.format,code:"invalid_type",input:i,inst:e});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}i<o&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),i>s&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:s,inst:e})}}),LT=J("$ZodCheckMaxLength",(e,t)=>{var r;Xt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Pc(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const a=Nc(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),jT=J("$ZodCheckMinLength",(e,t)=>{var r;Xt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Pc(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const a=Nc(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),DT=J("$ZodCheckLengthEquals",(e,t)=>{var r;Xt.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Pc(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,s=o.length;if(s===t.length)return;const a=Nc(o),i=s>t.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Fi=J("$ZodCheckStringFormat",(e,t)=>{var r,n;Xt.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),UT=J("$ZodCheckRegex",(e,t)=>{Fi.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),zT=J("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=NT),Fi.init(e,t)}),ZT=J("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=OT),Fi.init(e,t)}),FT=J("$ZodCheckIncludes",(e,t)=>{Xt.init(e,t);const r=Ms(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),VT=J("$ZodCheckStartsWith",(e,t)=>{Xt.init(e,t);const r=new RegExp(`^${Ms(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),HT=J("$ZodCheckEndsWith",(e,t)=>{Xt.init(e,t);const r=new RegExp(`.*${Ms(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),BT=J("$ZodCheckOverwrite",(e,t)=>{Xt.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class WT{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
8
+ deps: ${u}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(l){const[c,u]=s(l);a(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const f in l){if(f==="__proto__")continue;const p=Array.isArray(l[f])?c:u;p[f]=l[f]}return[c,u]}function a(l,c=l.schema){const{gen:u,data:f,it:p}=l;if(Object.keys(c).length===0)return;const h=u.let("missing");for(const m in c){const _=c[m];if(_.length===0)continue;const g=(0,n.propertyInData)(u,f,m,p.opts.ownProperties);l.setParams({property:m,depsCount:_.length,deps:_.join(", ")}),p.allErrors?u.if(g,()=>{for(const w of _)(0,n.checkReportMissingProp)(l,w)}):(u.if((0,t._)`${g} && (${(0,n.checkMissingProp)(l,_,h)})`),(0,n.reportMissingProp)(l,h),u.else())}}e.validatePropertyDeps=a;function i(l,c=l.schema){const{gen:u,data:f,keyword:p,it:h}=l,m=u.name("valid");for(const _ in c)(0,r.alwaysValidSchema)(h,c[_])||(u.if((0,n.propertyInData)(u,f,_,h.opts.ownProperties),()=>{const g=l.subschema({keyword:p,schemaProp:_},m);l.mergeValidEvaluated(g,m)},()=>u.var(m,!0)),l.ok(m))}e.validateSchemaDeps=i,e.default=o})(Ic)),Ic}var Si={},lh;function qb(){if(lh)return Si;lh=1,Object.defineProperty(Si,"__esModule",{value:!0});const e=Ue(),t=Ge(),n={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:o})=>(0,e._)`{propertyName: ${o.propertyName}}`},code(o){const{gen:s,schema:a,data:i,it:l}=o;if((0,t.alwaysValidSchema)(l,a))return;const c=s.name("valid");s.forIn("key",i,u=>{o.setParams({propertyName:u}),o.subschema({keyword:"propertyNames",data:u,dataTypes:["string"],propertyName:u,compositeRule:!0},c),s.if((0,e.not)(c),()=>{o.error(!0),l.allErrors||s.break()})}),o.ok(c)}};return Si.default=n,Si}var Ci={},ch;function uh(){if(ch)return Ci;ch=1,Object.defineProperty(Ci,"__esModule",{value:!0});const e=Pr(),t=Ue(),r=Cn(),n=Ge(),s={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:a})=>(0,t._)`{additionalProperty: ${a.additionalProperty}}`},code(a){const{gen:i,schema:l,parentSchema:c,data:u,errsCount:f,it:p}=a;if(!f)throw new Error("ajv implementation error");const{allErrors:h,opts:m}=p;if(p.props=!0,m.removeAdditional!=="all"&&(0,n.alwaysValidSchema)(p,l))return;const _=(0,e.allSchemaProperties)(c.properties),g=(0,e.allSchemaProperties)(c.patternProperties);w(),a.ok((0,t._)`${f} === ${r.default.errors}`);function w(){i.forIn("key",u,T=>{!_.length&&!g.length?S(T):i.if(v(T),()=>S(T))})}function v(T){let x;if(_.length>8){const R=(0,n.schemaRefOrVal)(p,c.properties,"properties");x=(0,e.isOwnProperty)(i,R,T)}else _.length?x=(0,t.or)(..._.map(R=>(0,t._)`${T} === ${R}`)):x=t.nil;return g.length&&(x=(0,t.or)(x,...g.map(R=>(0,t._)`${(0,e.usePattern)(a,R)}.test(${T})`))),(0,t.not)(x)}function y(T){i.code((0,t._)`delete ${u}[${T}]`)}function S(T){if(m.removeAdditional==="all"||m.removeAdditional&&l===!1){y(T);return}if(l===!1){a.setParams({additionalProperty:T}),a.error(),h||i.break();return}if(typeof l=="object"&&!(0,n.alwaysValidSchema)(p,l)){const x=i.name("valid");m.removeAdditional==="failing"?(b(T,x,!1),i.if((0,t.not)(x),()=>{a.reset(),y(T)})):(b(T,x),h||i.if((0,t.not)(x),()=>i.break()))}}function b(T,x,R){const C={keyword:"additionalProperties",dataProp:T,dataPropType:n.Type.Str};R===!1&&Object.assign(C,{compositeRule:!0,createErrors:!1,allErrors:!1}),a.subschema(C,x)}}};return Ci.default=s,Ci}var xi={},dh;function jb(){if(dh)return xi;dh=1,Object.defineProperty(xi,"__esModule",{value:!0});const e=Xa(),t=Pr(),r=Ge(),n=uh(),o={keyword:"properties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,parentSchema:l,data:c,it:u}=s;u.opts.removeAdditional==="all"&&l.additionalProperties===void 0&&n.default.code(new e.KeywordCxt(u,n.default,"additionalProperties"));const f=(0,t.allSchemaProperties)(i);for(const g of f)u.definedProperties.add(g);u.opts.unevaluated&&f.length&&u.props!==!0&&(u.props=r.mergeEvaluated.props(a,(0,r.toHash)(f),u.props));const p=f.filter(g=>!(0,r.alwaysValidSchema)(u,i[g]));if(p.length===0)return;const h=a.name("valid");for(const g of p)m(g)?_(g):(a.if((0,t.propertyInData)(a,c,g,u.opts.ownProperties)),_(g),u.allErrors||a.else().var(h,!0),a.endIf()),s.it.definedProperties.add(g),s.ok(h);function m(g){return u.opts.useDefaults&&!u.compositeRule&&i[g].default!==void 0}function _(g){s.subschema({keyword:"properties",schemaProp:g,dataProp:g},h)}}};return xi.default=o,xi}var Ii={},ph;function Lb(){if(ph)return Ii;ph=1,Object.defineProperty(Ii,"__esModule",{value:!0});const e=Pr(),t=Ue(),r=Ge(),n=Ge(),o={keyword:"patternProperties",type:"object",schemaType:"object",code(s){const{gen:a,schema:i,data:l,parentSchema:c,it:u}=s,{opts:f}=u,p=(0,e.allSchemaProperties)(i),h=p.filter(S=>(0,r.alwaysValidSchema)(u,i[S]));if(p.length===0||h.length===p.length&&(!u.opts.unevaluated||u.props===!0))return;const m=f.strictSchema&&!f.allowMatchingProperties&&c.properties,_=a.name("valid");u.props!==!0&&!(u.props instanceof t.Name)&&(u.props=(0,n.evaluatedPropsToName)(a,u.props));const{props:g}=u;w();function w(){for(const S of p)m&&v(S),u.allErrors?y(S):(a.var(_,!0),y(S),a.if(_))}function v(S){for(const b in m)new RegExp(S).test(b)&&(0,r.checkStrictMode)(u,`property ${b} matches pattern ${S} (use allowMatchingProperties)`)}function y(S){a.forIn("key",l,b=>{a.if((0,t._)`${(0,e.usePattern)(s,S)}.test(${b})`,()=>{const T=h.includes(S);T||s.subschema({keyword:"patternProperties",schemaProp:S,dataProp:b,dataPropType:n.Type.Str},_),u.opts.unevaluated&&g!==!0?a.assign((0,t._)`${g}[${b}]`,!0):!T&&!u.allErrors&&a.if((0,t.not)(_),()=>a.break())})})}}};return Ii.default=o,Ii}var $i={},fh;function Db(){if(fh)return $i;fh=1,Object.defineProperty($i,"__esModule",{value:!0});const e=Ge(),t={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){const{gen:n,schema:o,it:s}=r;if((0,e.alwaysValidSchema)(s,o)){r.fail();return}const a=n.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),r.failResult(a,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};return $i.default=t,$i}var Ei={},hh;function Ub(){if(hh)return Ei;hh=1,Object.defineProperty(Ei,"__esModule",{value:!0});const t={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Pr().validateUnion,error:{message:"must match a schema in anyOf"}};return Ei.default=t,Ei}var Ri={},mh;function zb(){if(mh)return Ri;mh=1,Object.defineProperty(Ri,"__esModule",{value:!0});const e=Ue(),t=Ge(),n={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:o})=>(0,e._)`{passingSchemas: ${o.passing}}`},code(o){const{gen:s,schema:a,parentSchema:i,it:l}=o;if(!Array.isArray(a))throw new Error("ajv implementation error");if(l.opts.discriminator&&i.discriminator)return;const c=a,u=s.let("valid",!1),f=s.let("passing",null),p=s.name("_valid");o.setParams({passing:f}),s.block(h),o.result(u,()=>o.reset(),()=>o.error(!0));function h(){c.forEach((m,_)=>{let g;(0,t.alwaysValidSchema)(l,m)?s.var(p,!0):g=o.subschema({keyword:"oneOf",schemaProp:_,compositeRule:!0},p),_>0&&s.if((0,e._)`${p} && ${u}`).assign(u,!1).assign(f,(0,e._)`[${f}, ${_}]`).else(),s.if(p,()=>{s.assign(u,!0),s.assign(f,_),g&&o.mergeEvaluated(g,e.Name)})})}}};return Ri.default=n,Ri}var Pi={},gh;function Zb(){if(gh)return Pi;gh=1,Object.defineProperty(Pi,"__esModule",{value:!0});const e=Ge(),t={keyword:"allOf",schemaType:"array",code(r){const{gen:n,schema:o,it:s}=r;if(!Array.isArray(o))throw new Error("ajv implementation error");const a=n.name("valid");o.forEach((i,l)=>{if((0,e.alwaysValidSchema)(s,i))return;const c=r.subschema({keyword:"allOf",schemaProp:l},a);r.ok(a),r.mergeEvaluated(c)})}};return Pi.default=t,Pi}var Mi={},yh;function Fb(){if(yh)return Mi;yh=1,Object.defineProperty(Mi,"__esModule",{value:!0});const e=Ue(),t=Ge(),n={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:s})=>(0,e.str)`must match "${s.ifClause}" schema`,params:({params:s})=>(0,e._)`{failingKeyword: ${s.ifClause}}`},code(s){const{gen:a,parentSchema:i,it:l}=s;i.then===void 0&&i.else===void 0&&(0,t.checkStrictMode)(l,'"if" without "then" and "else" is ignored');const c=o(l,"then"),u=o(l,"else");if(!c&&!u)return;const f=a.let("valid",!0),p=a.name("_valid");if(h(),s.reset(),c&&u){const _=a.let("ifClause");s.setParams({ifClause:_}),a.if(p,m("then",_),m("else",_))}else c?a.if(p,m("then")):a.if((0,e.not)(p),m("else"));s.pass(f,()=>s.error(!0));function h(){const _=s.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},p);s.mergeEvaluated(_)}function m(_,g){return()=>{const w=s.subschema({keyword:_},p);a.assign(f,p),s.mergeValidEvaluated(w,f),g?a.assign(g,(0,e._)`${_}`):s.setParams({ifClause:_})}}}};function o(s,a){const i=s.schema[a];return i!==void 0&&!(0,t.alwaysValidSchema)(s,i)}return Mi.default=n,Mi}var Oi={},vh;function Vb(){if(vh)return Oi;vh=1,Object.defineProperty(Oi,"__esModule",{value:!0});const e=Ge(),t={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:n,it:o}){n.if===void 0&&(0,e.checkStrictMode)(o,`"${r}" without "if" is ignored`)}};return Oi.default=t,Oi}var _h;function Hb(){if(_h)return wi;_h=1,Object.defineProperty(wi,"__esModule",{value:!0});const e=th(),t=Mb(),r=nh(),n=Ob(),o=Nb(),s=Ab(),a=qb(),i=uh(),l=jb(),c=Lb(),u=Db(),f=Ub(),p=zb(),h=Zb(),m=Fb(),_=Vb();function g(w=!1){const v=[u.default,f.default,p.default,h.default,m.default,_.default,a.default,i.default,s.default,l.default,c.default];return w?v.push(t.default,n.default):v.push(e.default,r.default),v.push(o.default),v}return wi.default=g,wi}var Ni={},Ai={},wh;function Bb(){if(wh)return Ai;wh=1,Object.defineProperty(Ai,"__esModule",{value:!0});const e=Ue(),r={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:n})=>(0,e.str)`must match format "${n}"`,params:({schemaCode:n})=>(0,e._)`{format: ${n}}`},code(n,o){const{gen:s,data:a,$data:i,schema:l,schemaCode:c,it:u}=n,{opts:f,errSchemaPath:p,schemaEnv:h,self:m}=u;if(!f.validateFormats)return;i?_():g();function _(){const w=s.scopeValue("formats",{ref:m.formats,code:f.code.formats}),v=s.const("fDef",(0,e._)`${w}[${c}]`),y=s.let("fType"),S=s.let("format");s.if((0,e._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>s.assign(y,(0,e._)`${v}.type || "string"`).assign(S,(0,e._)`${v}.validate`),()=>s.assign(y,(0,e._)`"string"`).assign(S,v)),n.fail$data((0,e.or)(b(),T()));function b(){return f.strictSchema===!1?e.nil:(0,e._)`${c} && !${S}`}function T(){const x=h.$async?(0,e._)`(${v}.async ? await ${S}(${a}) : ${S}(${a}))`:(0,e._)`${S}(${a})`,R=(0,e._)`(typeof ${S} == "function" ? ${x} : ${S}.test(${a}))`;return(0,e._)`${S} && ${S} !== true && ${y} === ${o} && !${R}`}}function g(){const w=m.formats[l];if(!w){b();return}if(w===!0)return;const[v,y,S]=T(w);v===o&&n.pass(x());function b(){if(f.strictSchema===!1){m.logger.warn(R());return}throw new Error(R());function R(){return`unknown format "${l}" ignored in schema at path "${p}"`}}function T(R){const C=R instanceof RegExp?(0,e.regexpCode)(R):f.code.formats?(0,e._)`${f.code.formats}${(0,e.getProperty)(l)}`:void 0,L=s.scopeValue("formats",{key:l,ref:R,code:C});return typeof R=="object"&&!(R instanceof RegExp)?[R.type||"string",R.validate,(0,e._)`${L}.validate`]:["string",R,L]}function x(){if(typeof w=="object"&&!(w instanceof RegExp)&&w.async){if(!h.$async)throw new Error("async format in sync schema");return(0,e._)`await ${S}(${a})`}return typeof y=="function"?(0,e._)`${S}(${a})`:(0,e._)`${S}.test(${a})`}}}};return Ai.default=r,Ai}var bh;function Jb(){if(bh)return Ni;bh=1,Object.defineProperty(Ni,"__esModule",{value:!0});const t=[Bb().default];return Ni.default=t,Ni}var Yn={},kh;function Wb(){return kh||(kh=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.contentVocabulary=Yn.metadataVocabulary=void 0,Yn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],Yn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]),Yn}var Th;function Gb(){if(Th)return oi;Th=1,Object.defineProperty(oi,"__esModule",{value:!0});const e=_b(),t=Pb(),r=Hb(),n=Jb(),o=Wb(),s=[e.default,t.default,(0,r.default)(),n.default,o.metadataVocabulary,o.contentVocabulary];return oi.default=s,oi}var qi={},ys={},Sh;function Kb(){if(Sh)return ys;Sh=1,Object.defineProperty(ys,"__esModule",{value:!0}),ys.DiscrError=void 0;var e;return(function(t){t.Tag="tag",t.Mapping="mapping"})(e||(ys.DiscrError=e={})),ys}var Ch;function Yb(){if(Ch)return qi;Ch=1,Object.defineProperty(qi,"__esModule",{value:!0});const e=Ue(),t=Kb(),r=Tc(),n=ri(),o=Ge(),a={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:i,tagName:l}})=>i===t.DiscrError.Tag?`tag "${l}" must be string`:`value of tag "${l}" must be in oneOf`,params:({params:{discrError:i,tag:l,tagName:c}})=>(0,e._)`{error: ${i}, tag: ${c}, tagValue: ${l}}`},code(i){const{gen:l,data:c,schema:u,parentSchema:f,it:p}=i,{oneOf:h}=f;if(!p.opts.discriminator)throw new Error("discriminator: requires discriminator option");const m=u.propertyName;if(typeof m!="string")throw new Error("discriminator: requires propertyName");if(u.mapping)throw new Error("discriminator: mapping is not supported");if(!h)throw new Error("discriminator: requires oneOf keyword");const _=l.let("valid",!1),g=l.const("tag",(0,e._)`${c}${(0,e.getProperty)(m)}`);l.if((0,e._)`typeof ${g} == "string"`,()=>w(),()=>i.error(!1,{discrError:t.DiscrError.Tag,tag:g,tagName:m})),i.ok(_);function w(){const S=y();l.if(!1);for(const b in S)l.elseIf((0,e._)`${g} === ${b}`),l.assign(_,v(S[b]));l.else(),i.error(!1,{discrError:t.DiscrError.Mapping,tag:g,tagName:m}),l.endIf()}function v(S){const b=l.name("valid"),T=i.subschema({keyword:"oneOf",schemaProp:S},b);return i.mergeEvaluated(T,e.Name),b}function y(){var S;const b={},T=R(f);let x=!0;for(let O=0;O<h.length;O++){let q=h[O];if(q?.$ref&&!(0,o.schemaHasRulesButRef)(q,p.self.RULES)){const H=q.$ref;if(q=r.resolveRef.call(p.self,p.schemaEnv.root,p.baseId,H),q instanceof r.SchemaEnv&&(q=q.schema),q===void 0)throw new n.default(p.opts.uriResolver,p.baseId,H)}const z=(S=q?.properties)===null||S===void 0?void 0:S[m];if(typeof z!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${m}"`);x=x&&(T||R(q)),C(z,O)}if(!x)throw new Error(`discriminator: "${m}" must be required`);return b;function R({required:O}){return Array.isArray(O)&&O.includes(m)}function C(O,q){if(O.const)L(O.const,q);else if(O.enum)for(const z of O.enum)L(z,q);else throw new Error(`discriminator: "properties/${m}" must have "const" or "enum"`)}function L(O,q){if(typeof O!="string"||O in b)throw new Error(`discriminator: "${m}" values must be unique strings`);b[O]=q}}}};return qi.default=a,qi}const Qb={$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 xh;function Ih(){return xh||(xh=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const r=gb(),n=Gb(),o=Yb(),s=Qb,a=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),n.default.forEach(m=>this.addVocabulary(m)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const m=this.opts.$data?this.$dataMetaSchema(s,a):s;this.addMetaSchema(m,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}t.Ajv=l,e.exports=t=l,e.exports.Ajv=l,Object.defineProperty(t,"__esModule",{value:!0}),t.default=l;var c=Xa();Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Ue();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var f=kc();Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=ri();Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(Ja,Ja.exports)),Ja.exports}var Xb=Ih();const $h=Wn(Xb);var Be;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{const s={};for(const a of o)s[a]=a;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(i=>typeof o[o[i]]!="number"),a={};for(const i of s)a[i]=o[i];return e.objectValues(a)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const a in o)Object.prototype.hasOwnProperty.call(o,a)&&s.push(a);return s},e.find=(o,s)=>{for(const a of o)if(s(a))return a},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Be||(Be={}));var $c;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})($c||($c={}));const me=Be.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),un=e=>{switch(typeof e){case"undefined":return me.undefined;case"string":return me.string;case"number":return Number.isNaN(e)?me.nan:me.number;case"boolean":return me.boolean;case"function":return me.function;case"bigint":return me.bigint;case"symbol":return me.symbol;case"object":return Array.isArray(e)?me.array:e===null?me.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?me.promise:typeof Map<"u"&&e instanceof Map?me.map:typeof Set<"u"&&e instanceof Set?me.set:typeof Date<"u"&&e instanceof Date?me.date:me.object;default:return me.unknown}},se=Be.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"]),e3=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class dr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof dr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Be.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r={},n=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}dr.create=e=>new dr(e);const Po=(e,t)=>{let r;switch(e.code){case se.invalid_type:e.received===me.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case se.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Be.jsonStringifyReplacer)}`;break;case se.unrecognized_keys:r=`Unrecognized key(s) in object: ${Be.joinValues(e.keys,", ")}`;break;case se.invalid_union:r="Invalid input";break;case se.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Be.joinValues(e.options)}`;break;case se.invalid_enum_value:r=`Invalid enum value. Expected ${Be.joinValues(e.options)}, received '${e.received}'`;break;case se.invalid_arguments:r="Invalid function arguments";break;case se.invalid_return_type:r="Invalid function return type";break;case se.invalid_date:r="Invalid date";break;case se.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Be.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case se.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case se.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case se.custom:r="Invalid input";break;case se.invalid_intersection_types:r="Intersection results could not be merged";break;case se.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case se.not_finite:r="Number must be finite";break;default:r=t.defaultError,Be.assertNever(e)}return{message:r}};let Eh=Po;function t3(e){Eh=e}function ji(){return Eh}const Li=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],a={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let i="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)i=c(a,{data:t,defaultError:i}).message;return{...o,path:s,message:i}},r3=[];function pe(e,t){const r=ji(),n=Li({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Po?void 0:Po].filter(o=>!!o)});e.common.issues.push(n)}class Ft{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return Oe;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const s=await o.key,a=await o.value;n.push({key:s,value:a})}return Ft.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:a}=o;if(s.status==="aborted"||a.status==="aborted")return Oe;s.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(n[s.value]=a.value)}return{status:t.value,value:n}}}const Oe=Object.freeze({status:"aborted"}),Mo=e=>({status:"dirty",value:e}),Gt=e=>({status:"valid",value:e}),Ec=e=>e.status==="aborted",Rc=e=>e.status==="dirty",Qn=e=>e.status==="valid",vs=e=>typeof Promise<"u"&&e instanceof Promise;var ke;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(ke||(ke={}));class Gr{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Rh=(e,t)=>{if(Qn(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new dr(e.common.issues);return this._error=r,this._error}}};function je(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(a,i)=>{const{message:l}=e;return a.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??n??i.defaultError}:a.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:o}}let Le=class{get description(){return this._def.description}_getType(t){return un(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:un(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Ft,ctx:{common:t.parent.common,data:t.data,parsedType:un(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const r=this._parse(t);if(vs(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){const r=this._parse(t);return Promise.resolve(r)}parse(t,r){const n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:un(t)},o=this._parseSync({data:t,path:n.path,parent:n});return Rh(n,o)}"~validate"(t){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:un(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:r});return Qn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Qn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){const n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:un(t)},o=this._parse({data:t,path:n.path,parent:n}),s=await(vs(o)?o:Promise.resolve(o));return Rh(n,s)}refine(t,r){const n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{const a=t(o),i=()=>s.addIssue({code:se.custom,...n(o)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(i(),!1)):a?!0:(i(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new Mr({schema:this,typeName:G.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Or.create(this,this._def)}nullable(){return $n.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return to.create(this)}promise(){return jo.create(this,this._def)}or(t){return Ts.create([this,t],this._def)}and(t){return Ss.create(this,t,this._def)}transform(t){return new Mr({...je(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const r=typeof t=="function"?t:()=>t;return new Es({...je(this._def),innerType:this,defaultValue:r,typeName:G.ZodDefault})}brand(){return new Oc({typeName:G.ZodBranded,type:this,...je(this._def)})}catch(t){const r=typeof t=="function"?t:()=>t;return new Rs({...je(this._def),innerType:this,catchValue:r,typeName:G.ZodCatch})}describe(t){const r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Ps.create(this,t)}readonly(){return Ms.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const n3=/^c[^\s-]{8,}$/i,o3=/^[0-9a-z]+$/,s3=/^[0-9A-HJKMNP-TV-Z]{26}$/i,a3=/^[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,i3=/^[a-z0-9_-]{21}$/i,l3=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,c3=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,u3=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,d3="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Pc;const p3=/^(?:(?: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])$/,f3=/^(?:(?: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])$/,h3=/^(([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]))$/,m3=/^(([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])$/,g3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,y3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ph="((\\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])))",v3=new RegExp(`^${Ph}$`);function Mh(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function _3(e){return new RegExp(`^${Mh(e)}$`)}function Oh(e){let t=`${Ph}T${Mh(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function w3(e,t){return!!((t==="v4"||!t)&&p3.test(e)||(t==="v6"||!t)&&h3.test(e))}function b3(e,t){if(!l3.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function k3(e,t){return!!((t==="v4"||!t)&&f3.test(e)||(t==="v6"||!t)&&m3.test(e))}let Oo=class Ba extends Le{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==me.string){const s=this._getOrReturnCtx(t);return pe(s,{code:se.invalid_type,expected:me.string,received:s.parsedType}),Oe}const n=new Ft;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),pe(o,{code:se.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),pe(o,{code:se.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const a=t.data.length>s.value,i=t.data.length<s.value;(a||i)&&(o=this._getOrReturnCtx(t,o),a?pe(o,{code:se.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&pe(o,{code:se.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")u3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"email",code:se.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Pc||(Pc=new RegExp(d3,"u")),Pc.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"emoji",code:se.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")a3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"uuid",code:se.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")i3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"nanoid",code:se.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")n3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"cuid",code:se.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")o3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"cuid2",code:se.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")s3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"ulid",code:se.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),pe(o,{validation:"url",code:se.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"regex",code:se.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),pe(o,{code:se.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),pe(o,{code:se.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),pe(o,{code:se.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Oh(s).test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{code:se.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?v3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{code:se.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?_3(s).test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{code:se.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?c3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"duration",code:se.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?w3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"ip",code:se.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?b3(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"jwt",code:se.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?k3(t.data,s.version)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"cidr",code:se.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?g3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"base64",code:se.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?y3.test(t.data)||(o=this._getOrReturnCtx(t,o),pe(o,{validation:"base64url",code:se.invalid_string,message:s.message}),n.dirty()):Be.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:se.invalid_string,...ke.errToObj(n)})}_addCheck(t){return new Ba({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ke.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ke.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ke.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ke.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ke.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ke.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ke.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ke.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ke.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ke.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ke.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ke.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ke.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...ke.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...ke.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...ke.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...ke.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...ke.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...ke.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...ke.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...ke.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...ke.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...ke.errToObj(r)})}nonempty(t){return this.min(1,ke.errToObj(t))}trim(){return new Ba({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ba({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ba({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Oo.create=e=>new Oo({checks:[],typeName:G.ZodString,coerce:e?.coerce??!1,...je(e)});function T3(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}let _s=class tf extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==me.number){const s=this._getOrReturnCtx(t);return pe(s,{code:se.invalid_type,expected:me.number,received:s.parsedType}),Oe}let n;const o=new Ft;for(const s of this._def.checks)s.kind==="int"?Be.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),pe(n,{code:se.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),pe(n,{code:se.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),pe(n,{code:se.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?T3(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),pe(n,{code:se.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),pe(n,{code:se.not_finite,message:s.message}),o.dirty()):Be.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,ke.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ke.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ke.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ke.toString(r))}setLimit(t,r,n,o){return new tf({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ke.toString(o)}]})}_addCheck(t){return new tf({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ke.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ke.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ke.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ke.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ke.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ke.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:ke.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ke.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ke.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Be.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};_s.create=e=>new _s({checks:[],typeName:G.ZodNumber,coerce:e?.coerce||!1,...je(e)});class In extends Le{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==me.bigint)return this._getInvalidInput(t);let n;const o=new Ft;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),pe(n,{code:se.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),pe(n,{code:se.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),pe(n,{code:se.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):Be.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return pe(r,{code:se.invalid_type,expected:me.bigint,received:r.parsedType}),Oe}gte(t,r){return this.setLimit("min",t,!0,ke.toString(r))}gt(t,r){return this.setLimit("min",t,!1,ke.toString(r))}lte(t,r){return this.setLimit("max",t,!0,ke.toString(r))}lt(t,r){return this.setLimit("max",t,!1,ke.toString(r))}setLimit(t,r,n,o){return new In({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:ke.toString(o)}]})}_addCheck(t){return new In({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ke.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ke.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ke.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ke.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:ke.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}}In.create=e=>new In({checks:[],typeName:G.ZodBigInt,coerce:e?.coerce??!1,...je(e)});let ws=class extends Le{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==me.boolean){const n=this._getOrReturnCtx(t);return pe(n,{code:se.invalid_type,expected:me.boolean,received:n.parsedType}),Oe}return Gt(t.data)}};ws.create=e=>new ws({typeName:G.ZodBoolean,coerce:e?.coerce||!1,...je(e)});class Xn extends Le{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==me.date){const s=this._getOrReturnCtx(t);return pe(s,{code:se.invalid_type,expected:me.date,received:s.parsedType}),Oe}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return pe(s,{code:se.invalid_date}),Oe}const n=new Ft;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),pe(o,{code:se.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),pe(o,{code:se.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Be.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Xn({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:ke.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:ke.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}}Xn.create=e=>new Xn({checks:[],coerce:e?.coerce||!1,typeName:G.ZodDate,...je(e)});class Di extends Le{_parse(t){if(this._getType(t)!==me.symbol){const n=this._getOrReturnCtx(t);return pe(n,{code:se.invalid_type,expected:me.symbol,received:n.parsedType}),Oe}return Gt(t.data)}}Di.create=e=>new Di({typeName:G.ZodSymbol,...je(e)});class bs extends Le{_parse(t){if(this._getType(t)!==me.undefined){const n=this._getOrReturnCtx(t);return pe(n,{code:se.invalid_type,expected:me.undefined,received:n.parsedType}),Oe}return Gt(t.data)}}bs.create=e=>new bs({typeName:G.ZodUndefined,...je(e)});let ks=class extends Le{_parse(t){if(this._getType(t)!==me.null){const n=this._getOrReturnCtx(t);return pe(n,{code:se.invalid_type,expected:me.null,received:n.parsedType}),Oe}return Gt(t.data)}};ks.create=e=>new ks({typeName:G.ZodNull,...je(e)});let No=class extends Le{constructor(){super(...arguments),this._any=!0}_parse(t){return Gt(t.data)}};No.create=e=>new No({typeName:G.ZodAny,...je(e)});let eo=class extends Le{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Gt(t.data)}};eo.create=e=>new eo({typeName:G.ZodUnknown,...je(e)});let dn=class extends Le{_parse(t){const r=this._getOrReturnCtx(t);return pe(r,{code:se.invalid_type,expected:me.never,received:r.parsedType}),Oe}};dn.create=e=>new dn({typeName:G.ZodNever,...je(e)});class Ui extends Le{_parse(t){if(this._getType(t)!==me.undefined){const n=this._getOrReturnCtx(t);return pe(n,{code:se.invalid_type,expected:me.void,received:n.parsedType}),Oe}return Gt(t.data)}}Ui.create=e=>new Ui({typeName:G.ZodVoid,...je(e)});let to=class hc extends Le{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==me.array)return pe(r,{code:se.invalid_type,expected:me.array,received:r.parsedType}),Oe;if(o.exactLength!==null){const a=r.data.length>o.exactLength.value,i=r.data.length<o.exactLength.value;(a||i)&&(pe(r,{code:a?se.too_big:se.too_small,minimum:i?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(pe(r,{code:se.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(pe(r,{code:se.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,i)=>o.type._parseAsync(new Gr(r,a,r.path,i)))).then(a=>Ft.mergeArray(n,a));const s=[...r.data].map((a,i)=>o.type._parseSync(new Gr(r,a,r.path,i)));return Ft.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new hc({...this._def,minLength:{value:t,message:ke.toString(r)}})}max(t,r){return new hc({...this._def,maxLength:{value:t,message:ke.toString(r)}})}length(t,r){return new hc({...this._def,exactLength:{value:t,message:ke.toString(r)}})}nonempty(t){return this.min(1,t)}};to.create=(e,t)=>new to({type:e,minLength:null,maxLength:null,exactLength:null,typeName:G.ZodArray,...je(t)});function Ao(e){if(e instanceof br){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=Or.create(Ao(n))}return new br({...e._def,shape:()=>t})}else return e instanceof to?new to({...e._def,type:Ao(e.element)}):e instanceof Or?Or.create(Ao(e.unwrap())):e instanceof $n?$n.create(Ao(e.unwrap())):e instanceof Kr?Kr.create(e.items.map(t=>Ao(t))):e}let br=class Wr extends Le{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=Be.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==me.object){const c=this._getOrReturnCtx(t);return pe(c,{code:se.invalid_type,expected:me.object,received:c.parsedType}),Oe}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof dn&&this._def.unknownKeys==="strip"))for(const c in o.data)a.includes(c)||i.push(c);const l=[];for(const c of a){const u=s[c],f=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Gr(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof dn){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")i.length>0&&(pe(o,{code:se.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 f=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Gr(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const f=await u.key,p=await u.value;c.push({key:f,value:p,alwaysSet:u.alwaysSet})}return c}).then(c=>Ft.mergeObjectSync(n,c)):Ft.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return ke.errToObj,new Wr({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:ke.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Wr({...this._def,unknownKeys:"strip"})}passthrough(){return new Wr({...this._def,unknownKeys:"passthrough"})}extend(t){return new Wr({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Wr({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:G.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new Wr({...this._def,catchall:t})}pick(t){const r={};for(const n of Be.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Wr({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Be.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new Wr({...this._def,shape:()=>r})}deepPartial(){return Ao(this)}partial(t){const r={};for(const n of Be.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new Wr({...this._def,shape:()=>r})}required(t){const r={};for(const n of Be.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Or;)s=s._def.innerType;r[n]=s}return new Wr({...this._def,shape:()=>r})}keyof(){return qh(Be.objectKeys(this.shape))}};br.create=(e,t)=>new br({shape:()=>e,unknownKeys:"strip",catchall:dn.create(),typeName:G.ZodObject,...je(t)}),br.strictCreate=(e,t)=>new br({shape:()=>e,unknownKeys:"strict",catchall:dn.create(),typeName:G.ZodObject,...je(t)}),br.lazycreate=(e,t)=>new br({shape:e,unknownKeys:"strip",catchall:dn.create(),typeName:G.ZodObject,...je(t)});let Ts=class extends Le{_parse(t){const{ctx:r}=this._processInputParams(t),n=this._def.options;function o(s){for(const i of s)if(i.result.status==="valid")return i.result;for(const i of s)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;const a=s.map(i=>new dr(i.ctx.common.issues));return pe(r,{code:se.invalid_union,unionErrors:a}),Oe}if(r.common.async)return Promise.all(n.map(async s=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(o);{let s;const a=[];for(const l of n){const c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=a.map(l=>new dr(l));return pe(r,{code:se.invalid_union,unionErrors:i}),Oe}}get options(){return this._def.options}};Ts.create=(e,t)=>new Ts({options:e,typeName:G.ZodUnion,...je(t)});const pn=e=>e instanceof Cs?pn(e.schema):e instanceof Mr?pn(e.innerType()):e instanceof xs?[e.value]:e instanceof Is?e.options:e instanceof $s?Be.objectValues(e.enum):e instanceof Es?pn(e._def.innerType):e instanceof bs?[void 0]:e instanceof ks?[null]:e instanceof Or?[void 0,...pn(e.unwrap())]:e instanceof $n?[null,...pn(e.unwrap())]:e instanceof Oc||e instanceof Ms?pn(e.unwrap()):e instanceof Rs?pn(e._def.innerType):[];let Nh=class tb extends Le{_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==me.object)return pe(r,{code:se.invalid_type,expected:me.object,received:r.parsedType}),Oe;const n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(pe(r,{code:se.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Oe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){const o=new Map;for(const s of r){const a=pn(s.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const i of a){if(o.has(i))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(i)}`);o.set(i,s)}}return new tb({typeName:G.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...je(n)})}};function Mc(e,t){const r=un(e),n=un(t);if(e===t)return{valid:!0,data:e};if(r===me.object&&n===me.object){const o=Be.objectKeys(t),s=Be.objectKeys(e).filter(i=>o.indexOf(i)!==-1),a={...e,...t};for(const i of s){const l=Mc(e[i],t[i]);if(!l.valid)return{valid:!1};a[i]=l.data}return{valid:!0,data:a}}else if(r===me.array&&n===me.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const a=e[s],i=t[s],l=Mc(a,i);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===me.date&&n===me.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}let Ss=class extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=(s,a)=>{if(Ec(s)||Ec(a))return Oe;const i=Mc(s.value,a.value);return i.valid?((Rc(s)||Rc(a))&&r.dirty(),{status:r.value,value:i.data}):(pe(n,{code:se.invalid_intersection_types}),Oe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>o(s,a)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ss.create=(e,t,r)=>new Ss({left:e,right:t,typeName:G.ZodIntersection,...je(r)});class Kr extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==me.array)return pe(n,{code:se.invalid_type,expected:me.array,received:n.parsedType}),Oe;if(n.data.length<this._def.items.length)return pe(n,{code:se.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Oe;!this._def.rest&&n.data.length>this._def.items.length&&(pe(n,{code:se.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((a,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new Gr(n,a,n.path,i)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>Ft.mergeArray(r,a)):Ft.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new Kr({...this._def,rest:t})}}Kr.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Kr({items:e,typeName:G.ZodTuple,rest:null,...je(t)})};let Ah=class rf extends Le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==me.object)return pe(n,{code:se.invalid_type,expected:me.object,received:n.parsedType}),Oe;const o=[],s=this._def.keyType,a=this._def.valueType;for(const i in n.data)o.push({key:s._parse(new Gr(n,i,n.path,i)),value:a._parse(new Gr(n,n.data[i],n.path,i)),alwaysSet:i in n.data});return n.common.async?Ft.mergeObjectAsync(r,o):Ft.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Le?new rf({keyType:t,valueType:r,typeName:G.ZodRecord,...je(n)}):new rf({keyType:Oo.create(),valueType:t,typeName:G.ZodRecord,...je(r)})}};class zi extends Le{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==me.map)return pe(n,{code:se.invalid_type,expected:me.map,received:n.parsedType}),Oe;const o=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([i,l],c)=>({key:o._parse(new Gr(n,i,n.path,[c,"key"])),value:s._parse(new Gr(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 Oe;(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 Oe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}zi.create=(e,t,r)=>new zi({valueType:t,keyType:e,typeName:G.ZodMap,...je(r)});class ro extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==me.set)return pe(n,{code:se.invalid_type,expected:me.set,received:n.parsedType}),Oe;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(pe(n,{code:se.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(pe(n,{code:se.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function a(l){const c=new Set;for(const u of l){if(u.status==="aborted")return Oe;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...n.data.values()].map((l,c)=>s._parse(new Gr(n,l,n.path,c)));return n.common.async?Promise.all(i).then(l=>a(l)):a(i)}min(t,r){return new ro({...this._def,minSize:{value:t,message:ke.toString(r)}})}max(t,r){return new ro({...this._def,maxSize:{value:t,message:ke.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}}ro.create=(e,t)=>new ro({valueType:e,minSize:null,maxSize:null,typeName:G.ZodSet,...je(t)});class qo extends Le{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==me.function)return pe(r,{code:se.invalid_type,expected:me.function,received:r.parsedType}),Oe;function n(i,l){return Li({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ji(),Po].filter(c=>!!c),issueData:{code:se.invalid_arguments,argumentsError:l}})}function o(i,l){return Li({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ji(),Po].filter(c=>!!c),issueData:{code:se.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof jo){const i=this;return Gt(async function(...l){const c=new dr([]),u=await i._def.args.parseAsync(l,s).catch(h=>{throw c.addIssue(n(l,h)),c}),f=await Reflect.apply(a,this,u);return await i._def.returns._def.type.parseAsync(f,s).catch(h=>{throw c.addIssue(o(f,h)),c})})}else{const i=this;return Gt(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new dr([n(l,c.error)]);const u=Reflect.apply(a,this,c.data),f=i._def.returns.safeParse(u,s);if(!f.success)throw new dr([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new qo({...this._def,args:Kr.create(t).rest(eo.create())})}returns(t){return new qo({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new qo({args:t||Kr.create([]).rest(eo.create()),returns:r||eo.create(),typeName:G.ZodFunction,...je(n)})}}let Cs=class extends Le{get schema(){return this._def.getter()}_parse(t){const{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Cs.create=(e,t)=>new Cs({getter:e,typeName:G.ZodLazy,...je(t)});let xs=class extends Le{_parse(t){if(t.data!==this._def.value){const r=this._getOrReturnCtx(t);return pe(r,{received:r.data,code:se.invalid_literal,expected:this._def.value}),Oe}return{status:"valid",value:t.data}}get value(){return this._def.value}};xs.create=(e,t)=>new xs({value:e,typeName:G.ZodLiteral,...je(t)});function qh(e,t){return new Is({values:e,typeName:G.ZodEnum,...je(t)})}let Is=class nf extends Le{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return pe(r,{expected:Be.joinValues(n),received:r.parsedType,code:se.invalid_type}),Oe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return pe(r,{received:r.data,code:se.invalid_enum_value,options:n}),Oe}return Gt(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return nf.create(t,{...this._def,...r})}exclude(t,r=this._def){return nf.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};Is.create=qh;class $s extends Le{_parse(t){const r=Be.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==me.string&&n.parsedType!==me.number){const o=Be.objectValues(r);return pe(n,{expected:Be.joinValues(o),received:n.parsedType,code:se.invalid_type}),Oe}if(this._cache||(this._cache=new Set(Be.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Be.objectValues(r);return pe(n,{received:n.data,code:se.invalid_enum_value,options:o}),Oe}return Gt(t.data)}get enum(){return this._def.values}}$s.create=(e,t)=>new $s({values:e,typeName:G.ZodNativeEnum,...je(t)});class jo extends Le{unwrap(){return this._def.type}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==me.promise&&r.common.async===!1)return pe(r,{code:se.invalid_type,expected:me.promise,received:r.parsedType}),Oe;const n=r.parsedType===me.promise?r.data:Promise.resolve(r.data);return Gt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}}jo.create=(e,t)=>new jo({type:e,typeName:G.ZodPromise,...je(t)});class Mr extends Le{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:a=>{pe(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const a=o.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async i=>{if(r.value==="aborted")return Oe;const l=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});return l.status==="aborted"?Oe:l.status==="dirty"||r.value==="dirty"?Mo(l.value):l});{if(r.value==="aborted")return Oe;const i=this._def.schema._parseSync({data:a,path:n.path,parent:n});return i.status==="aborted"?Oe:i.status==="dirty"||r.value==="dirty"?Mo(i.value):i}}if(o.type==="refinement"){const a=i=>{const l=o.refinement(i,s);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Oe:(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"?Oe:(i.status==="dirty"&&r.dirty(),a(i.value).then(()=>({status:r.value,value:i.value}))))}if(o.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Qn(a))return Oe;const i=o.transform(a.value,s);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Qn(a)?Promise.resolve(o.transform(a.value,s)).then(i=>({status:r.value,value:i})):Oe);Be.assertNever(o)}}Mr.create=(e,t,r)=>new Mr({schema:e,typeName:G.ZodEffects,effect:t,...je(r)}),Mr.createWithPreprocess=(e,t,r)=>new Mr({schema:t,effect:{type:"preprocess",transform:e},typeName:G.ZodEffects,...je(r)});let Or=class extends Le{_parse(t){return this._getType(t)===me.undefined?Gt(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Or.create=(e,t)=>new Or({innerType:e,typeName:G.ZodOptional,...je(t)});let $n=class extends Le{_parse(t){return this._getType(t)===me.null?Gt(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};$n.create=(e,t)=>new $n({innerType:e,typeName:G.ZodNullable,...je(t)});let Es=class extends Le{_parse(t){const{ctx:r}=this._processInputParams(t);let n=r.data;return r.parsedType===me.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Es.create=(e,t)=>new Es({innerType:e,typeName:G.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...je(t)});let Rs=class extends Le{_parse(t){const{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return vs(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new dr(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new dr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Rs.create=(e,t)=>new Rs({innerType:e,typeName:G.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...je(t)});class Zi extends Le{_parse(t){if(this._getType(t)!==me.nan){const n=this._getOrReturnCtx(t);return pe(n,{code:se.invalid_type,expected:me.nan,received:n.parsedType}),Oe}return{status:"valid",value:t.data}}}Zi.create=e=>new Zi({typeName:G.ZodNaN,...je(e)});const S3=Symbol("zod_brand");class Oc extends Le{_parse(t){const{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Ps extends Le{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Oe:s.status==="dirty"?(r.dirty(),Mo(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Oe:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new Ps({in:t,out:r,typeName:G.ZodPipeline})}}let Ms=class extends Le{_parse(t){const r=this._def.innerType._parse(t),n=o=>(Qn(o)&&(o.value=Object.freeze(o.value)),o);return vs(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Ms.create=(e,t)=>new Ms({innerType:e,typeName:G.ZodReadonly,...je(t)});function jh(e,t){const r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function Lh(e,t={},r){return e?No.create().superRefine((n,o)=>{const s=e(n);if(s instanceof Promise)return s.then(a=>{if(!a){const i=jh(t,n),l=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:l})}});if(!s){const a=jh(t,n),i=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:i})}}):No.create()}const C3={object:br.lazycreate};var G;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(G||(G={}));const x3=(e,t={message:`Input not instance of ${e.name}`})=>Lh(r=>r instanceof e,t),Ye=Oo.create,kr=_s.create,I3=Zi.create,$3=In.create,Dh=ws.create,E3=Xn.create,R3=Di.create,P3=bs.create,M3=ks.create,O3=No.create,N3=eo.create,A3=dn.create,q3=Ui.create,fn=to.create,tr=br.create,j3=br.strictCreate,Fi=Ts.create,L3=Nh.create,D3=Ss.create,U3=Kr.create,z3=Ah.create,Z3=zi.create,F3=ro.create,V3=qo.create,H3=Cs.create,B3=xs.create,Os=Is.create,J3=$s.create,W3=jo.create,Uh=Mr.create,G3=Or.create,K3=$n.create,Y3=Mr.createWithPreprocess,Q3=Ps.create,X3=Object.freeze(Object.defineProperty({__proto__:null,BRAND:S3,DIRTY:Mo,EMPTY_PATH:r3,INVALID:Oe,NEVER:Oe,OK:Gt,ParseStatus:Ft,Schema:Le,ZodAny:No,ZodArray:to,ZodBigInt:In,ZodBoolean:ws,ZodBranded:Oc,ZodCatch:Rs,ZodDate:Xn,ZodDefault:Es,ZodDiscriminatedUnion:Nh,ZodEffects:Mr,ZodEnum:Is,ZodError:dr,get ZodFirstPartyTypeKind(){return G},ZodFunction:qo,ZodIntersection:Ss,ZodIssueCode:se,ZodLazy:Cs,ZodLiteral:xs,ZodMap:zi,ZodNaN:Zi,ZodNativeEnum:$s,ZodNever:dn,ZodNull:ks,ZodNullable:$n,ZodNumber:_s,ZodObject:br,ZodOptional:Or,ZodParsedType:me,ZodPipeline:Ps,ZodPromise:jo,ZodReadonly:Ms,ZodRecord:Ah,ZodSchema:Le,ZodSet:ro,ZodString:Oo,ZodSymbol:Di,ZodTransformer:Mr,ZodTuple:Kr,ZodType:Le,ZodUndefined:bs,ZodUnion:Ts,ZodUnknown:eo,ZodVoid:Ui,addIssueToContext:pe,any:O3,array:fn,bigint:$3,boolean:Dh,coerce:{string:(e=>Oo.create({...e,coerce:!0})),number:(e=>_s.create({...e,coerce:!0})),boolean:(e=>ws.create({...e,coerce:!0})),bigint:(e=>In.create({...e,coerce:!0})),date:(e=>Xn.create({...e,coerce:!0}))},custom:Lh,date:E3,datetimeRegex:Oh,defaultErrorMap:Po,discriminatedUnion:L3,effect:Uh,enum:Os,function:V3,getErrorMap:ji,getParsedType:un,instanceof:x3,intersection:D3,isAborted:Ec,isAsync:vs,isDirty:Rc,isValid:Qn,late:C3,lazy:H3,literal:B3,makeIssue:Li,map:Z3,nan:I3,nativeEnum:J3,never:A3,null:M3,nullable:K3,number:kr,object:tr,get objectUtil(){return $c},oboolean:()=>Dh().optional(),onumber:()=>kr().optional(),optional:G3,ostring:()=>Ye().optional(),pipeline:Q3,preprocess:Y3,promise:W3,quotelessJson:e3,record:z3,set:F3,setErrorMap:t3,strictObject:j3,string:Ye,symbol:R3,transformer:Uh,tuple:U3,undefined:P3,union:Fi,unknown:N3,get util(){return Be},void:q3},Symbol.toStringTag,{value:"Module"})),zh=Object.freeze({status:"aborted"});function K(e,t,r){function n(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(e),t(i,l);for(const u in a.prototype)u in i||Object.defineProperty(i,u,{value:a.prototype[u].bind(i)});i._zod.constr=a,i._zod.def=l}const o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:e});function a(i){var l;const c=r?.Parent?new s:this;n(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i=>r?.Parent&&i instanceof r.Parent?!0:i?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class Ns extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Zh={};function En(e){return Zh}function Fh(e){const t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function e9(e,t){return typeof t=="bigint"?t.toString():t}function Nc(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ac(e){return e==null}function qc(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function t9(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),a=Number.parseInt(t.toFixed(o).replace(".",""));return s%a/10**o}function et(e,t,r){Object.defineProperty(e,t,{get(){{const n=r();return e[t]=n,n}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function As(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function qs(e){return JSON.stringify(e)}const Vh=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function Vi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const r9=Nc(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Hi(e){if(Vi(e)===!1)return!1;const t=e.constructor;if(t===void 0)return!0;const r=t.prototype;return!(Vi(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const n9=new Set(["string","number","symbol"]);function js(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rn(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function we(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function o9(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const s9={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 a9(e,t){const r={},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(r[o]=n.shape[o])}return Rn(e,{...e._zod.def,shape:r,checks:[]})}function i9(e,t){const r={...e._zod.def.shape},n=e._zod.def;for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete r[o]}return Rn(e,{...e._zod.def,shape:r,checks:[]})}function l9(e,t){if(!Hi(t))throw new Error("Invalid input to extend: expected a plain object");const r={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return As(this,"shape",n),n},checks:[]};return Rn(e,r)}function c9(e,t){return Rn(e,{...e._zod.def,get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return As(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function u9(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(const s in n)o[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return Rn(t,{...t._zod.def,shape:o,checks:[]})}function d9(e,t,r){const n=t._zod.def.shape,o={...n};if(r)for(const s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(const s in n)o[s]=new e({type:"nonoptional",innerType:n[s]});return Rn(t,{...t._zod.def,shape:o,checks:[]})}function Ls(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function no(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Bi(e){return typeof e=="string"?e:e?.message}function Pn(e,t,r){const n={...e,path:e.path??[]};if(!e.message){const o=Bi(e.inst?._zod.def?.error?.(e))??Bi(t?.error?.(e))??Bi(r.customError?.(e))??Bi(r.localeError?.(e))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function jc(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ds(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}const Hh=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,e9,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Bh=K("$ZodError",Hh),Ji=K("$ZodError",Hh,{Parent:Error});function p9(e,t=r=>r.message){const r={},n=[];for(const o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function f9(e,t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const a of s.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(i=>o({issues:i}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let i=n,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(a))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return o(e),n}const Jh=e=>(t,r,n,o)=>{const s=n?Object.assign(n,{async:!1}):{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Ns;if(a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>Pn(l,s,En())));throw Vh(i,o?.callee),i}return a.value},h9=Jh(Ji),Wh=e=>async(t,r,n,o)=>{const s=n?Object.assign(n,{async:!0}):{async:!0};let a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const i=new(o?.Err??e)(a.issues.map(l=>Pn(l,s,En())));throw Vh(i,o?.callee),i}return a.value},m9=Wh(Ji),Gh=e=>(t,r,n)=>{const o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ns;return s.issues.length?{success:!1,error:new(e??Bh)(s.issues.map(a=>Pn(a,o,En())))}:{success:!0,data:s.value}},Lc=Gh(Ji),Kh=e=>async(t,r,n)=>{const o=n?Object.assign(n,{async:!0}):{async:!0};let s=t._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(a=>Pn(a,o,En())))}:{success:!0,data:s.value}},Dc=Kh(Ji),g9=/^[cC][^\s-]{8,}$/,y9=/^[0-9a-z]+$/,v9=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,_9=/^[0-9a-vA-V]{20}$/,w9=/^[A-Za-z0-9]{27}$/,b9=/^[a-zA-Z0-9_-]{21}$/,k9=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,T9=/^([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})$/,Yh=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,S9=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,C9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function x9(){return new RegExp(C9,"u")}const I9=/^(?:(?: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])$/,$9=/^(([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})$/,E9=/^((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])$/,R9=/^(([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])$/,P9=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Qh=/^[A-Za-z0-9_-]*$/,M9=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,O9=/^\+(?:[0-9]){6,14}[0-9]$/,Xh="(?:(?:\\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])))",N9=new RegExp(`^${Xh}$`);function em(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function A9(e){return new RegExp(`^${em(e)}$`)}function q9(e){const t=em({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");const n=`${t}(?:${r.join("|")})`;return new RegExp(`^${Xh}T(?:${n})$`)}const j9=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},L9=/^\d+$/,D9=/^-?\d+(?:\.\d+)?/i,U9=/true|false/i,z9=/null/i,Z9=/^[^A-Z]*$/,F9=/^[^a-z]*$/,rr=K("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),tm={number:"number",bigint:"bigint",object:"date"},rm=K("$ZodCheckLessThan",(e,t)=>{rr.init(e,t);const r=tm[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,s=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),nm=K("$ZodCheckGreaterThan",(e,t)=>{rr.init(e,t);const r=tm[typeof t.value];e._zod.onattach.push(n=>{const o=n._zod.bag,s=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),V9=K("$ZodCheckMultipleOf",(e,t)=>{rr.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):t9(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),H9=K("$ZodCheckNumberFormat",(e,t)=>{rr.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[o,s]=s9[t.format];e._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,i.minimum=o,i.maximum=s,r&&(i.pattern=L9)}),e._zod.check=a=>{const i=a.value;if(r){if(!Number.isInteger(i)){a.issues.push({expected:n,format:t.format,code:"invalid_type",input:i,inst:e});return}if(!Number.isSafeInteger(i)){i>0?a.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):a.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}i<o&&a.issues.push({origin:"number",input:i,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),i>s&&a.issues.push({origin:"number",input:i,code:"too_big",maximum:s,inst:e})}}),B9=K("$ZodCheckMaxLength",(e,t)=>{var r;rr.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ac(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const o=n.value;if(o.length<=t.maximum)return;const a=jc(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),J9=K("$ZodCheckMinLength",(e,t)=>{var r;rr.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ac(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const o=n.value;if(o.length>=t.minimum)return;const a=jc(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),W9=K("$ZodCheckLengthEquals",(e,t)=>{var r;rr.init(e,t),(r=e._zod.def).when??(r.when=n=>{const o=n.value;return!Ac(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{const o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{const o=n.value,s=o.length;if(s===t.length)return;const a=jc(o),i=s>t.length;n.issues.push({origin:a,...i?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Wi=K("$ZodCheckStringFormat",(e,t)=>{var r,n;rr.init(e,t),e._zod.onattach.push(o=>{const s=o._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),G9=K("$ZodCheckRegex",(e,t)=>{Wi.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),K9=K("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Z9),Wi.init(e,t)}),Y9=K("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=F9),Wi.init(e,t)}),Q9=K("$ZodCheckIncludes",(e,t)=>{rr.init(e,t);const r=js(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{const s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),X9=K("$ZodCheckStartsWith",(e,t)=>{rr.init(e,t);const r=new RegExp(`^${js(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),ek=K("$ZodCheckEndsWith",(e,t)=>{rr.init(e,t);const r=new RegExp(`.*${js(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{const o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),tk=K("$ZodCheckOverwrite",(e,t)=>{rr.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});class rk{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const n=t.split(`
9
9
  `).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),s=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(const a of s)this.content.push(a)}compile(){const t=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,o.join(`
10
- `))}}const GT={major:4,minor:0,patch:0},tt=J("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=GT;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,a,i)=>{let l=Ns(s),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&i?.async===!1)throw new $s;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(l||(l=Ns(s,f)))});else{if(s.issues.length===f)continue;l||(l=Ns(s,f))}}return c?c.then(()=>s):s};e._zod.run=(s,a)=>{const i=e._zod.parse(s,a);if(i instanceof Promise){if(a.async===!1)throw new $s;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=Oc(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ac(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),qc=J("$ZodString",(e,t)=>{tt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??ET(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ct=J("$ZodStringFormat",(e,t)=>{Fi.init(e,t),qc.init(e,t)}),JT=J("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=hT),ct.init(e,t)}),KT=J("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Gh(n))}else t.pattern??(t.pattern=Gh());ct.init(e,t)}),YT=J("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=mT),ct.init(e,t)}),QT=J("$ZodURL",(e,t)=>{ct.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:kT.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),XT=J("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=yT()),ct.init(e,t)}),e9=J("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=pT),ct.init(e,t)}),t9=J("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=iT),ct.init(e,t)}),r9=J("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=lT),ct.init(e,t)}),n9=J("$ZodULID",(e,t)=>{t.pattern??(t.pattern=cT),ct.init(e,t)}),o9=J("$ZodXID",(e,t)=>{t.pattern??(t.pattern=uT),ct.init(e,t)}),s9=J("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=dT),ct.init(e,t)}),a9=J("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=xT(t)),ct.init(e,t)}),i9=J("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=CT),ct.init(e,t)}),l9=J("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=IT(t)),ct.init(e,t)}),c9=J("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=fT),ct.init(e,t)}),u9=J("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=vT),ct.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),d9=J("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=_T),ct.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),p9=J("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=wT),ct.init(e,t)}),f9=J("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=bT),ct.init(e,t),e._zod.check=r=>{const[n,o]=r.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function tm(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const h9=J("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=TT),ct.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{tm(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function m9(e){if(!Jh.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return tm(r)}const g9=J("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Jh),ct.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{m9(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),y9=J("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ST),ct.init(e,t)});function v9(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const _9=J("$ZodJWT",(e,t)=>{ct.init(e,t),e._zod.check=r=>{v9(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),rm=J("$ZodNumber",(e,t)=>{tt.init(e,t),e._zod.pattern=e._zod.bag.pattern??RT,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),w9=J("$ZodNumber",(e,t)=>{qT.init(e,t),rm.init(e,t)}),b9=J("$ZodBoolean",(e,t)=>{tt.init(e,t),e._zod.pattern=PT,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),T9=J("$ZodNull",(e,t)=>{tt.init(e,t),e._zod.pattern=MT,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),k9=J("$ZodAny",(e,t)=>{tt.init(e,t),e._zod.parse=r=>r}),S9=J("$ZodUnknown",(e,t)=>{tt.init(e,t),e._zod.parse=r=>r}),C9=J("$ZodNever",(e,t)=>{tt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function nm(e,t,r){e.issues.length&&t.issues.push(...Xn(r,e.issues)),t.value[r]=e.value}const I9=J("$ZodArray",(e,t)=>{tt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const i=o[a],l=t.element._zod.run({value:i,issues:[]},n);l instanceof Promise?s.push(l.then(c=>nm(c,r,a))):nm(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function Vi(e,t,r){e.issues.length&&t.issues.push(...Xn(r,e.issues)),t.value[r]=e.value}function om(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...Xn(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const sm=J("$ZodObject",(e,t)=>{tt.init(e,t);const r=Rc(()=>{const f=Object.keys(t.shape);for(const h of f)if(!(t.shape[h]instanceof tt))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const p=J3(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(p)}});Be(e._zod,"propValues",()=>{const f=t.shape,p={};for(const h in f){const m=f[h]._zod;if(m.values){p[h]??(p[h]=new Set);for(const _ of m.values)p[h].add(_)}}return p});const n=f=>{const p=new WT(["shape","payload","ctx"]),h=r.value,m=v=>{const g=Ps(v);return`shape[${g}]._zod.run({ value: input[${g}], issues: [] }, ctx)`};p.write("const input = payload.value;");const _=Object.create(null);let y=0;for(const v of h.keys)_[v]=`key_${y++}`;p.write("const newResult = {}");for(const v of h.keys)if(h.optionalKeys.has(v)){const g=_[v];p.write(`const ${g} = ${m(v)};`);const S=Ps(v);p.write(`
11
- if (${g}.issues.length) {
10
+ `))}}const nk={major:4,minor:0,patch:0},lt=K("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=nk;const n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(const o of n)for(const s of o._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,a,i)=>{let l=Ls(s),c;for(const u of a){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(l)continue;const f=s.issues.length,p=u._zod.check(s);if(p instanceof Promise&&i?.async===!1)throw new Ns;if(c||p instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(l||(l=Ls(s,f)))});else{if(s.issues.length===f)continue;l||(l=Ls(s,f))}}return c?c.then(()=>s):s};e._zod.run=(s,a)=>{const i=e._zod.parse(s,a);if(i instanceof Promise){if(a.async===!1)throw new Ns;return i.then(l=>o(l,n,a))}return o(i,n,a)}}e["~standard"]={validate:o=>{try{const s=Lc(e,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Dc(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Uc=K("$ZodString",(e,t)=>{lt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??j9(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),ht=K("$ZodStringFormat",(e,t)=>{Wi.init(e,t),Uc.init(e,t)}),ok=K("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=T9),ht.init(e,t)}),sk=K("$ZodUUID",(e,t)=>{if(t.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Yh(n))}else t.pattern??(t.pattern=Yh());ht.init(e,t)}),ak=K("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=S9),ht.init(e,t)}),ik=K("$ZodURL",(e,t)=>{ht.init(e,t),e._zod.check=r=>{try{const n=r.value,o=new URL(n),s=o.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:M9.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),lk=K("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=x9()),ht.init(e,t)}),ck=K("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=b9),ht.init(e,t)}),uk=K("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=g9),ht.init(e,t)}),dk=K("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=y9),ht.init(e,t)}),pk=K("$ZodULID",(e,t)=>{t.pattern??(t.pattern=v9),ht.init(e,t)}),fk=K("$ZodXID",(e,t)=>{t.pattern??(t.pattern=_9),ht.init(e,t)}),hk=K("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=w9),ht.init(e,t)}),mk=K("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=q9(t)),ht.init(e,t)}),gk=K("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=N9),ht.init(e,t)}),yk=K("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=A9(t)),ht.init(e,t)}),vk=K("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=k9),ht.init(e,t)}),_k=K("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=I9),ht.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv4"})}),wk=K("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=$9),ht.init(e,t),e._zod.onattach.push(r=>{const n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),bk=K("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=E9),ht.init(e,t)}),kk=K("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=R9),ht.init(e,t),e._zod.check=r=>{const[n,o]=r.value.split("/");try{if(!o)throw new Error;const s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function om(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Tk=K("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=P9),ht.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{om(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function Sk(e){if(!Qh.test(e))return!1;const t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return om(r)}const Ck=K("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Qh),ht.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{Sk(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),xk=K("$ZodE164",(e,t)=>{t.pattern??(t.pattern=O9),ht.init(e,t)});function Ik(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const $k=K("$ZodJWT",(e,t)=>{ht.init(e,t),e._zod.check=r=>{Ik(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),sm=K("$ZodNumber",(e,t)=>{lt.init(e,t),e._zod.pattern=e._zod.bag.pattern??D9,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;const s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Ek=K("$ZodNumber",(e,t)=>{H9.init(e,t),sm.init(e,t)}),Rk=K("$ZodBoolean",(e,t)=>{lt.init(e,t),e._zod.pattern=U9,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),Pk=K("$ZodNull",(e,t)=>{lt.init(e,t),e._zod.pattern=z9,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),Mk=K("$ZodAny",(e,t)=>{lt.init(e,t),e._zod.parse=r=>r}),Ok=K("$ZodUnknown",(e,t)=>{lt.init(e,t),e._zod.parse=r=>r}),Nk=K("$ZodNever",(e,t)=>{lt.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function am(e,t,r){e.issues.length&&t.issues.push(...no(r,e.issues)),t.value[r]=e.value}const Ak=K("$ZodArray",(e,t)=>{lt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);const s=[];for(let a=0;a<o.length;a++){const i=o[a],l=t.element._zod.run({value:i,issues:[]},n);l instanceof Promise?s.push(l.then(c=>am(c,r,a))):am(l,r,a)}return s.length?Promise.all(s).then(()=>r):r}});function Gi(e,t,r){e.issues.length&&t.issues.push(...no(r,e.issues)),t.value[r]=e.value}function im(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...no(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}const lm=K("$ZodObject",(e,t)=>{lt.init(e,t);const r=Nc(()=>{const f=Object.keys(t.shape);for(const h of f)if(!(t.shape[h]instanceof lt))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);const p=o9(t.shape);return{shape:t.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(p)}});et(e._zod,"propValues",()=>{const f=t.shape,p={};for(const h in f){const m=f[h]._zod;if(m.values){p[h]??(p[h]=new Set);for(const _ of m.values)p[h].add(_)}}return p});const n=f=>{const p=new rk(["shape","payload","ctx"]),h=r.value,m=v=>{const y=qs(v);return`shape[${y}]._zod.run({ value: input[${y}], issues: [] }, ctx)`};p.write("const input = payload.value;");const _=Object.create(null);let g=0;for(const v of h.keys)_[v]=`key_${g++}`;p.write("const newResult = {}");for(const v of h.keys)if(h.optionalKeys.has(v)){const y=_[v];p.write(`const ${y} = ${m(v)};`);const S=qs(v);p.write(`
11
+ if (${y}.issues.length) {
12
12
  if (input[${S}] === undefined) {
13
13
  if (${S} in input) {
14
14
  newResult[${S}] = undefined;
15
15
  }
16
16
  } else {
17
17
  payload.issues = payload.issues.concat(
18
- ${g}.issues.map((iss) => ({
18
+ ${y}.issues.map((iss) => ({
19
19
  ...iss,
20
20
  path: iss.path ? [${S}, ...iss.path] : [${S}],
21
21
  }))
22
22
  );
23
23
  }
24
- } else if (${g}.value === undefined) {
24
+ } else if (${y}.value === undefined) {
25
25
  if (${S} in input) newResult[${S}] = undefined;
26
26
  } else {
27
- newResult[${S}] = ${g}.value;
27
+ newResult[${S}] = ${y}.value;
28
28
  }
29
- `)}else{const g=_[v];p.write(`const ${g} = ${m(v)};`),p.write(`
30
- if (${g}.issues.length) payload.issues = payload.issues.concat(${g}.issues.map(iss => ({
29
+ `)}else{const y=_[v];p.write(`const ${y} = ${m(v)};`),p.write(`
30
+ if (${y}.issues.length) payload.issues = payload.issues.concat(${y}.issues.map(iss => ({
31
31
  ...iss,
32
- path: iss.path ? [${Ps(v)}, ...iss.path] : [${Ps(v)}]
33
- })));`),p.write(`newResult[${Ps(v)}] = ${g}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(v,g)=>w(f,v,g)};let o;const s=Di,a=!Dh.jitless,l=a&&W3.value,c=t.catchall;let u;e._zod.parse=(f,p)=>{u??(u=r.value);const h=f.value;if(!s(h))return f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f;const m=[];if(a&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),f=o(f,p);else{f.value={};const g=u.shape;for(const S of u.keys){const b=g[S],k=b._zod.run({value:h[S],issues:[]},p),C=b._zod.optin==="optional"&&b._zod.optout==="optional";k instanceof Promise?m.push(k.then(R=>C?om(R,f,S,h):Vi(R,f,S))):C?om(k,f,S,h):Vi(k,f,S)}}if(!c)return m.length?Promise.all(m).then(()=>f):f;const _=[],y=u.keySet,w=c._zod,v=w.def.type;for(const g of Object.keys(h)){if(y.has(g))continue;if(v==="never"){_.push(g);continue}const S=w.run({value:h[g],issues:[]},p);S instanceof Promise?m.push(S.then(b=>Vi(b,f,g))):Vi(S,f,g)}return _.length&&f.issues.push({code:"unrecognized_keys",keys:_,input:h,inst:e}),m.length?Promise.all(m).then(()=>f):f}});function am(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>En(s,n,In())))}),t}const im=J("$ZodUnion",(e,t)=>{tt.init(e,t),Be(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Be(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Be(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Be(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Mc(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)s.push(i),o=!0;else{if(i.issues.length===0)return i;s.push(i)}}return o?Promise.all(s).then(a=>am(a,r,e,n)):am(s,r,e,n)}}),x9=J("$ZodDiscriminatedUnion",(e,t)=>{im.init(e,t);const r=e._zod.parse;Be(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[i,l]of Object.entries(a)){o[i]||(o[i]=new Set);for(const c of l)o[i].add(c)}}return o});const n=Rc(()=>{const o=t.options,s=new Map;for(const a of o){const i=a._zod.propValues[t.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!Di(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=n.value.get(a?.[t.discriminator]);return i?i._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),E9=J("$ZodIntersection",(e,t)=>{tt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>lm(r,l,c)):lm(r,s,a)}});function Lc(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ui(e)&&Ui(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(const s of n){const a=Lc(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const o=e[n],s=t[n],a=Lc(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function lm(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ns(e))return e;const n=Lc(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const $9=J("$ZodRecord",(e,t)=>{tt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Ui(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Xn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Xn(l,c.issues)),r.value[l]=c.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>En(c,n,In())),input:a,path:[a],inst:e}),r.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...Xn(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...Xn(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),R9=J("$ZodEnum",(e,t)=>{tt.init(e,t);const r=Uh(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>G3.has(typeof n)).map(n=>typeof n=="string"?Ms(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),P9=J("$ZodLiteral",(e,t)=>{tt.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Ms(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{const o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),M9=J("$ZodTransform",(e,t)=>{tt.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new $s;return r.value=o,r}}),N9=J("$ZodOptional",(e,t)=>{tt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Be(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Be(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Mc(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),O9=J("$ZodNullable",(e,t)=>{tt.init(e,t),Be(e._zod,"optin",()=>t.innerType._zod.optin),Be(e._zod,"optout",()=>t.innerType._zod.optout),Be(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${Mc(r.source)}|null)$`):void 0}),Be(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),A9=J("$ZodDefault",(e,t)=>{tt.init(e,t),e._zod.optin="optional",Be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>cm(s,t)):cm(o,t)}});function cm(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const q9=J("$ZodPrefault",(e,t)=>{tt.init(e,t),e._zod.optin="optional",Be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),L9=J("$ZodNonOptional",(e,t)=>{tt.init(e,t),Be(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>um(s,e)):um(o,e)}});function um(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const j9=J("$ZodCatch",(e,t)=>{tt.init(e,t),e._zod.optin="optional",Be(e._zod,"optout",()=>t.innerType._zod.optout),Be(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(a=>En(a,n,In()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>En(s,n,In()))},input:r.value}),r.issues=[]),r)}}),D9=J("$ZodPipe",(e,t)=>{tt.init(e,t),Be(e._zod,"values",()=>t.in._zod.values),Be(e._zod,"optin",()=>t.in._zod.optin),Be(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>dm(s,t,n)):dm(o,t,n)}});function dm(e,t,r){return Ns(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const U9=J("$ZodReadonly",(e,t)=>{tt.init(e,t),Be(e._zod,"propValues",()=>t.innerType._zod.propValues),Be(e._zod,"values",()=>t.innerType._zod.values),Be(e._zod,"optin",()=>t.innerType._zod.optin),Be(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(pm):pm(o)}});function pm(e){return e.value=Object.freeze(e.value),e}const z9=J("$ZodLazy",(e,t)=>{tt.init(e,t),Be(e._zod,"innerType",()=>t.getter()),Be(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),Be(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),Be(e._zod,"optin",()=>e._zod.innerType._zod.optin),Be(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Z9=J("$ZodCustom",(e,t)=>{Xt.init(e,t),tt.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>fm(s,r,n,e));fm(o,r,n,e)}});function fm(e,t,r,n){if(!e){const o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Os(o))}}class hm{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){const n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function F9(){return new hm}const As=F9();function V9(e,t){return new e({type:"string",...ge(t)})}function H9(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ge(t)})}function mm(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ge(t)})}function B9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ge(t)})}function W9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ge(t)})}function G9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ge(t)})}function J9(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ge(t)})}function gm(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ge(t)})}function K9(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ge(t)})}function Y9(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ge(t)})}function Q9(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ge(t)})}function X9(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ge(t)})}function ek(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ge(t)})}function tk(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ge(t)})}function rk(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ge(t)})}function nk(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ge(t)})}function ok(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ge(t)})}function sk(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ge(t)})}function ak(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ge(t)})}function ym(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ge(t)})}function ik(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ge(t)})}function lk(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ge(t)})}function ck(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ge(t)})}function uk(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ge(t)})}function dk(e,t){return new e({type:"string",format:"date",check:"string_format",...ge(t)})}function pk(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ge(t)})}function fk(e,t){return new e({type:"string",format:"duration",check:"string_format",...ge(t)})}function hk(e,t){return new e({type:"number",checks:[],...ge(t)})}function mk(e,t){return new e({type:"number",coerce:!0,checks:[],...ge(t)})}function gk(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ge(t)})}function yk(e,t){return new e({type:"boolean",...ge(t)})}function vk(e,t){return new e({type:"null",...ge(t)})}function _k(e){return new e({type:"any"})}function wk(e){return new e({type:"unknown"})}function bk(e,t){return new e({type:"never",...ge(t)})}function vm(e,t){return new Xh({check:"less_than",...ge(t),value:e,inclusive:!1})}function jc(e,t){return new Xh({check:"less_than",...ge(t),value:e,inclusive:!0})}function _m(e,t){return new em({check:"greater_than",...ge(t),value:e,inclusive:!1})}function Dc(e,t){return new em({check:"greater_than",...ge(t),value:e,inclusive:!0})}function wm(e,t){return new AT({check:"multiple_of",...ge(t),value:e})}function bm(e,t){return new LT({check:"max_length",...ge(t),maximum:e})}function Hi(e,t){return new jT({check:"min_length",...ge(t),minimum:e})}function Tm(e,t){return new DT({check:"length_equals",...ge(t),length:e})}function Tk(e,t){return new UT({check:"string_format",format:"regex",...ge(t),pattern:e})}function kk(e){return new zT({check:"string_format",format:"lowercase",...ge(e)})}function Sk(e){return new ZT({check:"string_format",format:"uppercase",...ge(e)})}function Ck(e,t){return new FT({check:"string_format",format:"includes",...ge(t),includes:e})}function Ik(e,t){return new VT({check:"string_format",format:"starts_with",...ge(t),prefix:e})}function xk(e,t){return new HT({check:"string_format",format:"ends_with",...ge(t),suffix:e})}function qs(e){return new BT({check:"overwrite",tx:e})}function Ek(e){return qs(t=>t.normalize(e))}function $k(){return qs(e=>e.trim())}function Rk(){return qs(e=>e.toLowerCase())}function Pk(){return qs(e=>e.toUpperCase())}function Mk(e,t,r){return new e({type:"array",element:t,...ge(r)})}function Nk(e,t,r){const n=ge(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Ok(e,t,r){return new e({type:"custom",check:"custom",fn:t,...ge(r)})}class km{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??As,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,i);const l=t._zod.toJSONSchema?.();if(l)i.schema=l;else{const f={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)i.ref=p,this.process(p,f),this.seen.get(p).isParent=!0;else{const h=i.schema;switch(o.type){case"string":{const m=h;m.type="string";const{minimum:_,maximum:y,format:w,patterns:v,contentEncoding:g}=t._zod.bag;if(typeof _=="number"&&(m.minLength=_),typeof y=="number"&&(m.maxLength=y),w&&(m.format=s[w]??w,m.format===""&&delete m.format),g&&(m.contentEncoding=g),v&&v.size>0){const S=[...v];S.length===1?m.pattern=S[0].source:S.length>1&&(i.schema.allOf=[...S.map(b=>({...this.target==="draft-7"?{type:"string"}:{},pattern:b.source}))])}break}case"number":{const m=h,{minimum:_,maximum:y,format:w,multipleOf:v,exclusiveMaximum:g,exclusiveMinimum:S}=t._zod.bag;typeof w=="string"&&w.includes("int")?m.type="integer":m.type="number",typeof S=="number"&&(m.exclusiveMinimum=S),typeof _=="number"&&(m.minimum=_,typeof S=="number"&&(S>=_?delete m.minimum:delete m.exclusiveMinimum)),typeof g=="number"&&(m.exclusiveMaximum=g),typeof y=="number"&&(m.maximum=y,typeof g=="number"&&(g<=y?delete m.maximum:delete m.exclusiveMaximum)),typeof v=="number"&&(m.multipleOf=v);break}case"boolean":{const m=h;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const m=h,{minimum:_,maximum:y}=t._zod.bag;typeof _=="number"&&(m.minItems=_),typeof y=="number"&&(m.maxItems=y),m.type="array",m.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const m=h;m.type="object",m.properties={};const _=o.shape;for(const v in _)m.properties[v]=this.process(_[v],{...f,path:[...f.path,"properties",v]});const y=new Set(Object.keys(_)),w=new Set([...y].filter(v=>{const g=o.shape[v]._zod;return this.io==="input"?g.optin===void 0:g.optout===void 0}));w.size>0&&(m.required=Array.from(w)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=h;m.anyOf=o.options.map((_,y)=>this.process(_,{...f,path:[...f.path,"anyOf",y]}));break}case"intersection":{const m=h,_=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),y=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),w=g=>"allOf"in g&&Object.keys(g).length===1,v=[...w(_)?_.allOf:[_],...w(y)?y.allOf:[y]];m.allOf=v;break}case"tuple":{const m=h;m.type="array";const _=o.items.map((v,g)=>this.process(v,{...f,path:[...f.path,"prefixItems",g]}));if(this.target==="draft-2020-12"?m.prefixItems=_:m.items=_,o.rest){const v=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?m.items=v:m.additionalItems=v}o.rest&&(m.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:y,maximum:w}=t._zod.bag;typeof y=="number"&&(m.minItems=y),typeof w=="number"&&(m.maxItems=w);break}case"record":{const m=h;m.type="object",m.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...f,path:[...f.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 m=h,_=Uh(o.entries);_.every(y=>typeof y=="number")&&(m.type="number"),_.every(y=>typeof y=="string")&&(m.type="string"),m.enum=_;break}case"literal":{const m=h,_=[];for(const y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");_.push(Number(y))}else _.push(y);if(_.length!==0)if(_.length===1){const y=_[0];m.type=y===null?"null":typeof y,m.const=y}else _.every(y=>typeof y=="number")&&(m.type="number"),_.every(y=>typeof y=="string")&&(m.type="string"),_.every(y=>typeof y=="boolean")&&(m.type="string"),_.every(y=>y===null)&&(m.type="null"),m.enum=_;break}case"file":{const m=h,_={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:w,mime:v}=t._zod.bag;y!==void 0&&(_.minLength=y),w!==void 0&&(_.maxLength=w),v?v.length===1?(_.contentMediaType=v[0],Object.assign(m,_)):m.anyOf=v.map(g=>({..._,contentMediaType:g})):Object.assign(m,_);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const m=this.process(o.innerType,f);h.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"success":{const m=h;m.type="boolean";break}case"default":{this.process(o.innerType,f),i.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),i.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),i.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const m=h,_=t._zod.pattern;if(!_)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=_.source;break}case"pipe":{const m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,f),i.ref=m;break}case"readonly":{this.process(o.innerType,f),i.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,f),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"lazy":{const m=t._zod.innerType;this.process(m,f),i.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),this.io==="input"&&Ct(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const f=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const _=n.external.registry.get(u[0])?.id,y=n.external.uri??(v=>v);if(_)return{ref:y(_)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${y("__shared")}#/${f}/${w}`}}if(u[1]===o)return{ref:"#"};const h=`#/${f}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:h+m}},a=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:p,defId:h}=s(u);f.def={...f.schema},h&&(f.defId=h);const m=f.schema;for(const _ in m)delete m[_];m.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.cycle?.join("/")}/<root>
32
+ path: iss.path ? [${qs(v)}, ...iss.path] : [${qs(v)}]
33
+ })));`),p.write(`newResult[${qs(v)}] = ${y}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");const w=p.compile();return(v,y)=>w(f,v,y)};let o;const s=Vi,a=!Zh.jitless,l=a&&r9.value,c=t.catchall;let u;e._zod.parse=(f,p)=>{u??(u=r.value);const h=f.value;if(!s(h))return f.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),f;const m=[];if(a&&l&&p?.async===!1&&p.jitless!==!0)o||(o=n(t.shape)),f=o(f,p);else{f.value={};const y=u.shape;for(const S of u.keys){const b=y[S],T=b._zod.run({value:h[S],issues:[]},p),x=b._zod.optin==="optional"&&b._zod.optout==="optional";T instanceof Promise?m.push(T.then(R=>x?im(R,f,S,h):Gi(R,f,S))):x?im(T,f,S,h):Gi(T,f,S)}}if(!c)return m.length?Promise.all(m).then(()=>f):f;const _=[],g=u.keySet,w=c._zod,v=w.def.type;for(const y of Object.keys(h)){if(g.has(y))continue;if(v==="never"){_.push(y);continue}const S=w.run({value:h[y],issues:[]},p);S instanceof Promise?m.push(S.then(b=>Gi(b,f,y))):Gi(S,f,y)}return _.length&&f.issues.push({code:"unrecognized_keys",keys:_,input:h,inst:e}),m.length?Promise.all(m).then(()=>f):f}});function cm(e,t,r,n){for(const o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(s=>Pn(s,n,En())))}),t}const um=K("$ZodUnion",(e,t)=>{lt.init(e,t),et(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),et(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),et(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),et(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>qc(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1;const s=[];for(const a of t.options){const i=a._zod.run({value:r.value,issues:[]},n);if(i instanceof Promise)s.push(i),o=!0;else{if(i.issues.length===0)return i;s.push(i)}}return o?Promise.all(s).then(a=>cm(a,r,e,n)):cm(s,r,e,n)}}),qk=K("$ZodDiscriminatedUnion",(e,t)=>{um.init(e,t);const r=e._zod.parse;et(e._zod,"propValues",()=>{const o={};for(const s of t.options){const a=s._zod.propValues;if(!a||Object.keys(a).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[i,l]of Object.entries(a)){o[i]||(o[i]=new Set);for(const c of l)o[i].add(c)}}return o});const n=Nc(()=>{const o=t.options,s=new Map;for(const a of o){const i=a._zod.propValues[t.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(a)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,a)}}return s});e._zod.parse=(o,s)=>{const a=o.value;if(!Vi(a))return o.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),o;const i=n.value.get(a?.[t.discriminator]);return i?i._zod.run(o,s):t.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:a,path:[t.discriminator],inst:e}),o)}}),jk=K("$ZodIntersection",(e,t)=>{lt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value,s=t.left._zod.run({value:o,issues:[]},n),a=t.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([l,c])=>dm(r,l,c)):dm(r,s,a)}});function zc(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Hi(e)&&Hi(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),o={...e,...t};for(const s of n){const a=zc(e[s],t[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const o=e[n],s=t[n],a=zc(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function dm(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),Ls(e))return e;const n=zc(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}const Lk=K("$ZodRecord",(e,t)=>{lt.init(e,t),e._zod.parse=(r,n)=>{const o=r.value;if(!Hi(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;const s=[];if(t.keyType._zod.values){const a=t.keyType._zod.values;r.value={};for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=t.valueType._zod.run({value:o[l],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...no(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...no(l,c.issues)),r.value[l]=c.value)}let i;for(const l in o)a.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:i})}else{r.value={};for(const a of Reflect.ownKeys(o)){if(a==="__proto__")continue;const i=t.keyType._zod.run({value:a,issues:[]},n);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(c=>Pn(c,n,En())),input:a,path:[a],inst:e}),r.value[i.value]=i.value;continue}const l=t.valueType._zod.run({value:o[a],issues:[]},n);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...no(a,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...no(a,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Dk=K("$ZodEnum",(e,t)=>{lt.init(e,t);const r=Fh(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>n9.has(typeof n)).map(n=>typeof n=="string"?js(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{const s=n.value;return e._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:e}),n}}),Uk=K("$ZodLiteral",(e,t)=>{lt.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?js(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{const o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),zk=K("$ZodTransform",(e,t)=>{lt.init(e,t),e._zod.parse=(r,n)=>{const o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(a=>(r.value=a,r));if(o instanceof Promise)throw new Ns;return r.value=o,r}}),Zk=K("$ZodOptional",(e,t)=>{lt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",et(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),et(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${qc(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),Fk=K("$ZodNullable",(e,t)=>{lt.init(e,t),et(e._zod,"optin",()=>t.innerType._zod.optin),et(e._zod,"optout",()=>t.innerType._zod.optout),et(e._zod,"pattern",()=>{const r=t.innerType._zod.pattern;return r?new RegExp(`^(${qc(r.source)}|null)$`):void 0}),et(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),Vk=K("$ZodDefault",(e,t)=>{lt.init(e,t),e._zod.optin="optional",et(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>pm(s,t)):pm(o,t)}});function pm(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Hk=K("$ZodPrefault",(e,t)=>{lt.init(e,t),e._zod.optin="optional",et(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),Bk=K("$ZodNonOptional",(e,t)=>{lt.init(e,t),et(e._zod,"values",()=>{const r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>fm(s,e)):fm(o,e)}});function fm(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Jk=K("$ZodCatch",(e,t)=>{lt.init(e,t),e._zod.optin="optional",et(e._zod,"optout",()=>t.innerType._zod.optout),et(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=t.catchValue({...r,error:{issues:s.issues.map(a=>Pn(a,n,En()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(s=>Pn(s,n,En()))},input:r.value}),r.issues=[]),r)}}),Wk=K("$ZodPipe",(e,t)=>{lt.init(e,t),et(e._zod,"values",()=>t.in._zod.values),et(e._zod,"optin",()=>t.in._zod.optin),et(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{const o=t.in._zod.run(r,n);return o instanceof Promise?o.then(s=>hm(s,t,n)):hm(o,t,n)}});function hm(e,t,r){return Ls(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}const Gk=K("$ZodReadonly",(e,t)=>{lt.init(e,t),et(e._zod,"propValues",()=>t.innerType._zod.propValues),et(e._zod,"values",()=>t.innerType._zod.values),et(e._zod,"optin",()=>t.innerType._zod.optin),et(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{const o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(mm):mm(o)}});function mm(e){return e.value=Object.freeze(e.value),e}const Kk=K("$ZodLazy",(e,t)=>{lt.init(e,t),et(e._zod,"innerType",()=>t.getter()),et(e._zod,"pattern",()=>e._zod.innerType._zod.pattern),et(e._zod,"propValues",()=>e._zod.innerType._zod.propValues),et(e._zod,"optin",()=>e._zod.innerType._zod.optin),et(e._zod,"optout",()=>e._zod.innerType._zod.optout),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),Yk=K("$ZodCustom",(e,t)=>{rr.init(e,t),lt.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(s=>gm(s,r,n,e));gm(o,r,n,e)}});function gm(e,t,r,n){if(!e){const o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Ds(o))}}class ym{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){const n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){const r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){const r=t._zod.parent;if(r){const n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}}function Qk(){return new ym}const Us=Qk();function Xk(e,t){return new e({type:"string",...we(t)})}function eT(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...we(t)})}function vm(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...we(t)})}function tT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...we(t)})}function rT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...we(t)})}function nT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...we(t)})}function oT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...we(t)})}function _m(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...we(t)})}function sT(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...we(t)})}function aT(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...we(t)})}function iT(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...we(t)})}function lT(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...we(t)})}function cT(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...we(t)})}function uT(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...we(t)})}function dT(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...we(t)})}function pT(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...we(t)})}function fT(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...we(t)})}function hT(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...we(t)})}function mT(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...we(t)})}function wm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...we(t)})}function gT(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...we(t)})}function yT(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...we(t)})}function vT(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...we(t)})}function _T(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...we(t)})}function wT(e,t){return new e({type:"string",format:"date",check:"string_format",...we(t)})}function bT(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...we(t)})}function kT(e,t){return new e({type:"string",format:"duration",check:"string_format",...we(t)})}function TT(e,t){return new e({type:"number",checks:[],...we(t)})}function ST(e,t){return new e({type:"number",coerce:!0,checks:[],...we(t)})}function CT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...we(t)})}function xT(e,t){return new e({type:"boolean",...we(t)})}function IT(e,t){return new e({type:"null",...we(t)})}function $T(e){return new e({type:"any"})}function ET(e){return new e({type:"unknown"})}function RT(e,t){return new e({type:"never",...we(t)})}function bm(e,t){return new rm({check:"less_than",...we(t),value:e,inclusive:!1})}function Zc(e,t){return new rm({check:"less_than",...we(t),value:e,inclusive:!0})}function km(e,t){return new nm({check:"greater_than",...we(t),value:e,inclusive:!1})}function Fc(e,t){return new nm({check:"greater_than",...we(t),value:e,inclusive:!0})}function Tm(e,t){return new V9({check:"multiple_of",...we(t),value:e})}function Sm(e,t){return new B9({check:"max_length",...we(t),maximum:e})}function Ki(e,t){return new J9({check:"min_length",...we(t),minimum:e})}function Cm(e,t){return new W9({check:"length_equals",...we(t),length:e})}function PT(e,t){return new G9({check:"string_format",format:"regex",...we(t),pattern:e})}function MT(e){return new K9({check:"string_format",format:"lowercase",...we(e)})}function OT(e){return new Y9({check:"string_format",format:"uppercase",...we(e)})}function NT(e,t){return new Q9({check:"string_format",format:"includes",...we(t),includes:e})}function AT(e,t){return new X9({check:"string_format",format:"starts_with",...we(t),prefix:e})}function qT(e,t){return new ek({check:"string_format",format:"ends_with",...we(t),suffix:e})}function zs(e){return new tk({check:"overwrite",tx:e})}function jT(e){return zs(t=>t.normalize(e))}function LT(){return zs(e=>e.trim())}function DT(){return zs(e=>e.toLowerCase())}function UT(){return zs(e=>e.toUpperCase())}function zT(e,t,r){return new e({type:"array",element:t,...we(r)})}function ZT(e,t,r){const n=we(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function FT(e,t,r){return new e({type:"custom",check:"custom",fn:t,...we(r)})}class xm{constructor(t){this.counter=0,this.metadataRegistry=t?.metadata??Us,this.target=t?.target??"draft-2020-12",this.unrepresentable=t?.unrepresentable??"throw",this.override=t?.override??(()=>{}),this.io=t?.io??"output",this.seen=new Map}process(t,r={path:[],schemaPath:[]}){var n;const o=t._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},a=this.seen.get(t);if(a)return a.count++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(t,i);const l=t._zod.toJSONSchema?.();if(l)i.schema=l;else{const f={...r,schemaPath:[...r.schemaPath,t],path:r.path},p=t._zod.parent;if(p)i.ref=p,this.process(p,f),this.seen.get(p).isParent=!0;else{const h=i.schema;switch(o.type){case"string":{const m=h;m.type="string";const{minimum:_,maximum:g,format:w,patterns:v,contentEncoding:y}=t._zod.bag;if(typeof _=="number"&&(m.minLength=_),typeof g=="number"&&(m.maxLength=g),w&&(m.format=s[w]??w,m.format===""&&delete m.format),y&&(m.contentEncoding=y),v&&v.size>0){const S=[...v];S.length===1?m.pattern=S[0].source:S.length>1&&(i.schema.allOf=[...S.map(b=>({...this.target==="draft-7"?{type:"string"}:{},pattern:b.source}))])}break}case"number":{const m=h,{minimum:_,maximum:g,format:w,multipleOf:v,exclusiveMaximum:y,exclusiveMinimum:S}=t._zod.bag;typeof w=="string"&&w.includes("int")?m.type="integer":m.type="number",typeof S=="number"&&(m.exclusiveMinimum=S),typeof _=="number"&&(m.minimum=_,typeof S=="number"&&(S>=_?delete m.minimum:delete m.exclusiveMinimum)),typeof y=="number"&&(m.exclusiveMaximum=y),typeof g=="number"&&(m.maximum=g,typeof y=="number"&&(y<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof v=="number"&&(m.multipleOf=v);break}case"boolean":{const m=h;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const m=h,{minimum:_,maximum:g}=t._zod.bag;typeof _=="number"&&(m.minItems=_),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...f,path:[...f.path,"items"]});break}case"object":{const m=h;m.type="object",m.properties={};const _=o.shape;for(const v in _)m.properties[v]=this.process(_[v],{...f,path:[...f.path,"properties",v]});const g=new Set(Object.keys(_)),w=new Set([...g].filter(v=>{const y=o.shape[v]._zod;return this.io==="input"?y.optin===void 0:y.optout===void 0}));w.size>0&&(m.required=Array.from(w)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{const m=h;m.anyOf=o.options.map((_,g)=>this.process(_,{...f,path:[...f.path,"anyOf",g]}));break}case"intersection":{const m=h,_=this.process(o.left,{...f,path:[...f.path,"allOf",0]}),g=this.process(o.right,{...f,path:[...f.path,"allOf",1]}),w=y=>"allOf"in y&&Object.keys(y).length===1,v=[...w(_)?_.allOf:[_],...w(g)?g.allOf:[g]];m.allOf=v;break}case"tuple":{const m=h;m.type="array";const _=o.items.map((v,y)=>this.process(v,{...f,path:[...f.path,"prefixItems",y]}));if(this.target==="draft-2020-12"?m.prefixItems=_:m.items=_,o.rest){const v=this.process(o.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?m.items=v:m.additionalItems=v}o.rest&&(m.items=this.process(o.rest,{...f,path:[...f.path,"items"]}));const{minimum:g,maximum:w}=t._zod.bag;typeof g=="number"&&(m.minItems=g),typeof w=="number"&&(m.maxItems=w);break}case"record":{const m=h;m.type="object",m.propertyNames=this.process(o.keyType,{...f,path:[...f.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...f,path:[...f.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 m=h,_=Fh(o.entries);_.every(g=>typeof g=="number")&&(m.type="number"),_.every(g=>typeof g=="string")&&(m.type="string"),m.enum=_;break}case"literal":{const m=h,_=[];for(const g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");_.push(Number(g))}else _.push(g);if(_.length!==0)if(_.length===1){const g=_[0];m.type=g===null?"null":typeof g,m.const=g}else _.every(g=>typeof g=="number")&&(m.type="number"),_.every(g=>typeof g=="string")&&(m.type="string"),_.every(g=>typeof g=="boolean")&&(m.type="string"),_.every(g=>g===null)&&(m.type="null"),m.enum=_;break}case"file":{const m=h,_={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:w,mime:v}=t._zod.bag;g!==void 0&&(_.minLength=g),w!==void 0&&(_.maxLength=w),v?v.length===1?(_.contentMediaType=v[0],Object.assign(m,_)):m.anyOf=v.map(y=>({..._,contentMediaType:y})):Object.assign(m,_);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const m=this.process(o.innerType,f);h.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"success":{const m=h;m.type="boolean";break}case"default":{this.process(o.innerType,f),i.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,f),i.ref=o.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,f),i.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const m=h,_=t._zod.pattern;if(!_)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=_.source;break}case"pipe":{const m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,f),i.ref=m;break}case"readonly":{this.process(o.innerType,f),i.ref=o.innerType,h.readOnly=!0;break}case"promise":{this.process(o.innerType,f),i.ref=o.innerType;break}case"optional":{this.process(o.innerType,f),i.ref=o.innerType;break}case"lazy":{const m=t._zod.innerType;this.process(m,f),i.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),this.io==="input"&&Et(t)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(t).schema}emit(t,r){const n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(t);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=u=>{const f=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){const _=n.external.registry.get(u[0])?.id,g=n.external.uri??(v=>v);if(_)return{ref:g(_)};const w=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=w,{defId:w,ref:`${g("__shared")}#/${f}/${w}`}}if(u[1]===o)return{ref:"#"};const h=`#/${f}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:h+m}},a=u=>{if(u[1].schema.$ref)return;const f=u[1],{ref:p,defId:h}=s(u);f.def={...f.schema},h&&(f.defId=h);const m=f.schema;for(const _ in m)delete m[_];m.$ref=p};if(n.cycles==="throw")for(const u of this.seen.entries()){const f=u[1];if(f.cycle)throw new Error(`Cycle detected: #/${f.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 f=u[1];if(t===u[0]){a(u);continue}if(n.external){const h=n.external.registry.get(u[0])?.id;if(t!==u[0]&&h){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(f.cycle){a(u);continue}if(f.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,f)=>{const p=this.seen.get(u),h=p.def??p.schema,m={...h};if(p.ref===null)return;const _=p.ref;if(p.ref=null,_){i(_,f);const y=this.seen.get(_).schema;y.$ref&&f.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(y)):(Object.assign(h,y),Object.assign(h,m))}p.isParent||this.override({zodSchema:u,jsonSchema:h,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const f=u[1];f.def&&f.defId&&(c[f.defId]=f.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 Sm(e,t){if(e instanceof hm){const n=new km(t),o={};for(const i of e._idmap.entries()){const[l,c]=i;n.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const i of e._idmap.entries()){const[l,c]=i;s[l]=n.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const r=new km(t);return r.process(e),r.emit(e,t)}function Ct(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ct(o.element,r);case"object":{for(const s in o.shape)if(Ct(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(Ct(s,r))return!0;return!1}case"intersection":return Ct(o.left,r)||Ct(o.right,r);case"tuple":{for(const s of o.items)if(Ct(s,r))return!0;return!!(o.rest&&Ct(o.rest,r))}case"record":return Ct(o.keyType,r)||Ct(o.valueType,r);case"map":return Ct(o.keyType,r)||Ct(o.valueType,r);case"set":return Ct(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ct(o.innerType,r);case"lazy":return Ct(o.getter(),r);case"default":return Ct(o.innerType,r);case"prefault":return Ct(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Ct(o.in,r)||Ct(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const Ak=J("ZodISODateTime",(e,t)=>{a9.init(e,t),pt.init(e,t)});function Cm(e){return uk(Ak,e)}const qk=J("ZodISODate",(e,t)=>{i9.init(e,t),pt.init(e,t)});function Lk(e){return dk(qk,e)}const jk=J("ZodISOTime",(e,t)=>{l9.init(e,t),pt.init(e,t)});function Dk(e){return pk(jk,e)}const Uk=J("ZodISODuration",(e,t)=>{c9.init(e,t),pt.init(e,t)});function zk(e){return fk(Uk,e)}const Bi=J("ZodError",(e,t)=>{Fh.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>oT(e,r)},flatten:{value:r=>nT(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Zk=Vh(Bi),Fk=Hh(Bi),Vk=Bh(Bi),Im=Wh(Bi),at=J("ZodType",(e,t)=>(tt.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>xn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>Zk(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Vk(e,r,n),e.parseAsync=async(r,n)=>Fk(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Im(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(O4(r,n)),e.superRefine=r=>e.check(A4(r)),e.overwrite=r=>e.check(qs(r)),e.optional=()=>he(e),e.nullable=()=>Lm(e),e.nullish=()=>he(Lm(e)),e.nonoptional=r=>I4(e,r),e.array=()=>q(e),e.or=r=>ae([e,r]),e.and=r=>zc(e,r),e.transform=r=>Fc(e,Am(r)),e.default=r=>k4(e,r),e.prefault=r=>C4(e,r),e.catch=r=>E4(e,r),e.pipe=r=>Fc(e,r),e.readonly=()=>P4(e),e.describe=r=>{const n=e.clone();return As.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return As.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return As.get(e);const n=e.clone();return As.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),xm=J("_ZodString",(e,t)=>{qc.init(e,t),at.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(Tk(...n)),e.includes=(...n)=>e.check(Ck(...n)),e.startsWith=(...n)=>e.check(Ik(...n)),e.endsWith=(...n)=>e.check(xk(...n)),e.min=(...n)=>e.check(Hi(...n)),e.max=(...n)=>e.check(bm(...n)),e.length=(...n)=>e.check(Tm(...n)),e.nonempty=(...n)=>e.check(Hi(1,...n)),e.lowercase=n=>e.check(kk(n)),e.uppercase=n=>e.check(Sk(n)),e.trim=()=>e.check($k()),e.normalize=(...n)=>e.check(Ek(...n)),e.toLowerCase=()=>e.check(Rk()),e.toUpperCase=()=>e.check(Pk())}),Hk=J("ZodString",(e,t)=>{qc.init(e,t),xm.init(e,t),e.email=r=>e.check(H9(Bk,r)),e.url=r=>e.check(gm($m,r)),e.jwt=r=>e.check(ck(i4,r)),e.emoji=r=>e.check(K9(Gk,r)),e.guid=r=>e.check(mm(Em,r)),e.uuid=r=>e.check(B9(Wi,r)),e.uuidv4=r=>e.check(W9(Wi,r)),e.uuidv6=r=>e.check(G9(Wi,r)),e.uuidv7=r=>e.check(J9(Wi,r)),e.nanoid=r=>e.check(Y9(Jk,r)),e.guid=r=>e.check(mm(Em,r)),e.cuid=r=>e.check(Q9(Kk,r)),e.cuid2=r=>e.check(X9(Yk,r)),e.ulid=r=>e.check(ek(Qk,r)),e.base64=r=>e.check(ym(Rm,r)),e.base64url=r=>e.check(ik(s4,r)),e.xid=r=>e.check(tk(Xk,r)),e.ksuid=r=>e.check(rk(e4,r)),e.ipv4=r=>e.check(nk(t4,r)),e.ipv6=r=>e.check(ok(r4,r)),e.cidrv4=r=>e.check(sk(n4,r)),e.cidrv6=r=>e.check(ak(o4,r)),e.e164=r=>e.check(lk(a4,r)),e.datetime=r=>e.check(Cm(r)),e.date=r=>e.check(Lk(r)),e.time=r=>e.check(Dk(r)),e.duration=r=>e.check(zk(r))});function d(e){return V9(Hk,e)}const pt=J("ZodStringFormat",(e,t)=>{ct.init(e,t),xm.init(e,t)}),Bk=J("ZodEmail",(e,t)=>{YT.init(e,t),pt.init(e,t)}),Em=J("ZodGUID",(e,t)=>{JT.init(e,t),pt.init(e,t)}),Wi=J("ZodUUID",(e,t)=>{KT.init(e,t),pt.init(e,t)}),$m=J("ZodURL",(e,t)=>{QT.init(e,t),pt.init(e,t)});function Wk(e){return gm($m,e)}const Gk=J("ZodEmoji",(e,t)=>{XT.init(e,t),pt.init(e,t)}),Jk=J("ZodNanoID",(e,t)=>{e9.init(e,t),pt.init(e,t)}),Kk=J("ZodCUID",(e,t)=>{t9.init(e,t),pt.init(e,t)}),Yk=J("ZodCUID2",(e,t)=>{r9.init(e,t),pt.init(e,t)}),Qk=J("ZodULID",(e,t)=>{n9.init(e,t),pt.init(e,t)}),Xk=J("ZodXID",(e,t)=>{o9.init(e,t),pt.init(e,t)}),e4=J("ZodKSUID",(e,t)=>{s9.init(e,t),pt.init(e,t)}),t4=J("ZodIPv4",(e,t)=>{u9.init(e,t),pt.init(e,t)}),r4=J("ZodIPv6",(e,t)=>{d9.init(e,t),pt.init(e,t)}),n4=J("ZodCIDRv4",(e,t)=>{p9.init(e,t),pt.init(e,t)}),o4=J("ZodCIDRv6",(e,t)=>{f9.init(e,t),pt.init(e,t)}),Rm=J("ZodBase64",(e,t)=>{h9.init(e,t),pt.init(e,t)});function Pm(e){return ym(Rm,e)}const s4=J("ZodBase64URL",(e,t)=>{g9.init(e,t),pt.init(e,t)}),a4=J("ZodE164",(e,t)=>{y9.init(e,t),pt.init(e,t)}),i4=J("ZodJWT",(e,t)=>{_9.init(e,t),pt.init(e,t)}),Uc=J("ZodNumber",(e,t)=>{rm.init(e,t),at.init(e,t),e.gt=(n,o)=>e.check(_m(n,o)),e.gte=(n,o)=>e.check(Dc(n,o)),e.min=(n,o)=>e.check(Dc(n,o)),e.lt=(n,o)=>e.check(vm(n,o)),e.lte=(n,o)=>e.check(jc(n,o)),e.max=(n,o)=>e.check(jc(n,o)),e.int=n=>e.check(Mm(n)),e.safe=n=>e.check(Mm(n)),e.positive=n=>e.check(_m(0,n)),e.nonnegative=n=>e.check(Dc(0,n)),e.negative=n=>e.check(vm(0,n)),e.nonpositive=n=>e.check(jc(0,n)),e.multipleOf=(n,o)=>e.check(wm(n,o)),e.step=(n,o)=>e.check(wm(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function O(e){return hk(Uc,e)}const l4=J("ZodNumberFormat",(e,t)=>{w9.init(e,t),Uc.init(e,t)});function Mm(e){return gk(l4,e)}const c4=J("ZodBoolean",(e,t)=>{b9.init(e,t),at.init(e,t)});function ve(e){return yk(c4,e)}const u4=J("ZodNull",(e,t)=>{T9.init(e,t),at.init(e,t)});function Ls(e){return vk(u4,e)}const d4=J("ZodAny",(e,t)=>{k9.init(e,t),at.init(e,t)});function Tt(){return _k(d4)}const p4=J("ZodUnknown",(e,t)=>{S9.init(e,t),at.init(e,t)});function xe(){return wk(p4)}const f4=J("ZodNever",(e,t)=>{C9.init(e,t),at.init(e,t)});function h4(e){return bk(f4,e)}const m4=J("ZodArray",(e,t)=>{I9.init(e,t),at.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Hi(r,n)),e.nonempty=r=>e.check(Hi(1,r)),e.max=(r,n)=>e.check(bm(r,n)),e.length=(r,n)=>e.check(Tm(r,n)),e.unwrap=()=>e.element});function q(e,t){return Mk(m4,e,t)}const Nm=J("ZodObject",(e,t)=>{sm.init(e,t),at.init(e,t),Be(e,"shape",()=>t.shape),e.keyof=()=>de(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:xe()}),e.loose=()=>e.clone({...e._zod.def,catchall:xe()}),e.strict=()=>e.clone({...e._zod.def,catchall:h4()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>X3(e,r),e.merge=r=>eT(e,r),e.pick=r=>Y3(e,r),e.omit=r=>Q3(e,r),e.partial=(...r)=>tT(qm,e,r[0]),e.required=(...r)=>rT(jm,e,r[0])});function T(e,t){const r={type:"object",get shape(){return Rs(this,"shape",{...e}),this.shape},...ge(t)};return new Nm(r)}function ft(e,t){return new Nm({type:"object",get shape(){return Rs(this,"shape",{...e}),this.shape},catchall:xe(),...ge(t)})}const Om=J("ZodUnion",(e,t)=>{im.init(e,t),at.init(e,t),e.options=t.options});function ae(e,t){return new Om({type:"union",options:e,...ge(t)})}const g4=J("ZodDiscriminatedUnion",(e,t)=>{Om.init(e,t),x9.init(e,t)});function Ve(e,t,r){return new g4({type:"union",options:t,discriminator:e,...ge(r)})}const y4=J("ZodIntersection",(e,t)=>{E9.init(e,t),at.init(e,t)});function zc(e,t){return new y4({type:"intersection",left:e,right:t})}const v4=J("ZodRecord",(e,t)=>{$9.init(e,t),at.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function _e(e,t,r){return new v4({type:"record",keyType:e,valueType:t,...ge(r)})}const Zc=J("ZodEnum",(e,t)=>{R9.init(e,t),at.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const s={};for(const a of n)if(r.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Zc({...t,checks:[],...ge(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Zc({...t,checks:[],...ge(o),entries:s})}});function de(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Zc({type:"enum",entries:r,...ge(t)})}const _4=J("ZodLiteral",(e,t)=>{P9.init(e,t),at.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function P(e,t){return new _4({type:"literal",values:Array.isArray(e)?e:[e],...ge(t)})}const w4=J("ZodTransform",(e,t)=>{M9.init(e,t),at.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Os(s,r.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(Os(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Am(e){return new w4({type:"transform",transform:e})}const qm=J("ZodOptional",(e,t)=>{N9.init(e,t),at.init(e,t),e.unwrap=()=>e._zod.def.innerType});function he(e){return new qm({type:"optional",innerType:e})}const b4=J("ZodNullable",(e,t)=>{O9.init(e,t),at.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Lm(e){return new b4({type:"nullable",innerType:e})}const T4=J("ZodDefault",(e,t)=>{A9.init(e,t),at.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function k4(e,t){return new T4({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const S4=J("ZodPrefault",(e,t)=>{q9.init(e,t),at.init(e,t),e.unwrap=()=>e._zod.def.innerType});function C4(e,t){return new S4({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const jm=J("ZodNonOptional",(e,t)=>{L9.init(e,t),at.init(e,t),e.unwrap=()=>e._zod.def.innerType});function I4(e,t){return new jm({type:"nonoptional",innerType:e,...ge(t)})}const x4=J("ZodCatch",(e,t)=>{j9.init(e,t),at.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function E4(e,t){return new x4({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const $4=J("ZodPipe",(e,t)=>{D9.init(e,t),at.init(e,t),e.in=t.in,e.out=t.out});function Fc(e,t){return new $4({type:"pipe",in:e,out:t})}const R4=J("ZodReadonly",(e,t)=>{U9.init(e,t),at.init(e,t)});function P4(e){return new R4({type:"readonly",innerType:e})}const M4=J("ZodLazy",(e,t)=>{z9.init(e,t),at.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Gi(e){return new M4({type:"lazy",getter:e})}const Vc=J("ZodCustom",(e,t)=>{Z9.init(e,t),at.init(e,t)});function N4(e){const t=new Xt({check:"custom"});return t._zod.check=e,t}function Dm(e,t){return Nk(Vc,e??(()=>!0),t)}function O4(e,t={}){return Ok(Vc,e,t)}function A4(e){const t=N4(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Os(n,r.value,t._zod.def));else{const o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Os(o))}},e(r.value,r)));return t}function Ji(e,t={error:`Input not instance of ${e.name}`}){const r=new Vc({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...ge(t)});return r._zod.bag.Class=e,r}function Um(e,t){return Fc(Am(e),t)}const zm={custom:"custom"};function Zm(e){return mk(Uc,e)}const js="2025-11-25",Fm=[js,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],eo="io.modelcontextprotocol/related-task",Ki="2.0",Nt=Dm(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Vm=ae([d(),O().int()]),Hm=d();ft({ttl:ae([O(),Ls()]).optional(),pollInterval:O().optional()});const q4=T({ttl:O().optional()}),L4=T({taskId:d()}),Hc=ft({progressToken:Vm.optional(),[eo]:L4.optional()}),ur=T({_meta:Hc.optional()}),Ds=ur.extend({task:q4.optional()}),j4=e=>Ds.safeParse(e).success,Ot=T({method:d(),params:ur.loose().optional()}),Tr=T({_meta:Hc.optional()}),kr=T({method:d(),params:Tr.loose().optional()}),At=ft({_meta:Hc.optional()}),Yi=ae([d(),O().int()]),Bm=T({jsonrpc:P(Ki),id:Yi,...Ot.shape}).strict(),Bc=e=>Bm.safeParse(e).success,Wm=T({jsonrpc:P(Ki),...kr.shape}).strict(),D4=e=>Wm.safeParse(e).success,Wc=T({jsonrpc:P(Ki),id:Yi,result:At}).strict(),Us=e=>Wc.safeParse(e).success;var fe;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(fe||(fe={}));const Gc=T({jsonrpc:P(Ki),id:Yi.optional(),error:T({code:O().int(),message:d(),data:xe().optional()})}).strict(),U4=e=>Gc.safeParse(e).success,dn=ae([Bm,Wm,Wc,Gc]);ae([Wc,Gc]);const $n=At.strict(),z4=Tr.extend({requestId:Yi.optional(),reason:d().optional()}),Jc=kr.extend({method:P("notifications/cancelled"),params:z4}),Z4=T({src:d(),mimeType:d().optional(),sizes:q(d()).optional(),theme:de(["light","dark"]).optional()}),zs=T({icons:q(Z4).optional()}),Ro=T({name:d(),title:d().optional()}),Gm=Ro.extend({...Ro.shape,...zs.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),F4=zc(T({applyDefaults:ve().optional()}),_e(d(),xe())),V4=Um(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,zc(T({form:F4.optional(),url:Nt.optional()}),_e(d(),xe()).optional())),H4=ft({list:Nt.optional(),cancel:Nt.optional(),requests:ft({sampling:ft({createMessage:Nt.optional()}).optional(),elicitation:ft({create:Nt.optional()}).optional()}).optional()}),B4=ft({list:Nt.optional(),cancel:Nt.optional(),requests:ft({tools:ft({call:Nt.optional()}).optional()}).optional()}),W4=T({experimental:_e(d(),Nt).optional(),sampling:T({context:Nt.optional(),tools:Nt.optional()}).optional(),elicitation:V4.optional(),roots:T({listChanged:ve().optional()}).optional(),tasks:H4.optional()}),G4=ur.extend({protocolVersion:d(),capabilities:W4,clientInfo:Gm}),Jm=Ot.extend({method:P("initialize"),params:G4}),J4=T({experimental:_e(d(),Nt).optional(),logging:Nt.optional(),completions:Nt.optional(),prompts:T({listChanged:ve().optional()}).optional(),resources:T({subscribe:ve().optional(),listChanged:ve().optional()}).optional(),tools:T({listChanged:ve().optional()}).optional(),tasks:B4.optional()}),Km=At.extend({protocolVersion:d(),capabilities:J4,serverInfo:Gm,instructions:d().optional()}),Kc=kr.extend({method:P("notifications/initialized"),params:Tr.optional()}),K4=e=>Kc.safeParse(e).success,Yc=Ot.extend({method:P("ping"),params:ur.optional()}),Y4=T({progress:O(),total:he(O()),message:he(d())}),Q4=T({...Tr.shape,...Y4.shape,progressToken:Vm}),Qc=kr.extend({method:P("notifications/progress"),params:Q4}),X4=ur.extend({cursor:Hm.optional()}),Zs=Ot.extend({params:X4.optional()}),Fs=At.extend({nextCursor:Hm.optional()}),eS=de(["working","input_required","completed","failed","cancelled"]),Vs=T({taskId:d(),status:eS,ttl:ae([O(),Ls()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:he(O()),statusMessage:he(d())}),Po=At.extend({task:Vs}),tS=Tr.merge(Vs),Qi=kr.extend({method:P("notifications/tasks/status"),params:tS}),Xc=Ot.extend({method:P("tasks/get"),params:ur.extend({taskId:d()})}),eu=At.merge(Vs),tu=Ot.extend({method:P("tasks/result"),params:ur.extend({taskId:d()})});At.loose();const ru=Zs.extend({method:P("tasks/list")}),nu=Fs.extend({tasks:q(Vs)}),ou=Ot.extend({method:P("tasks/cancel"),params:ur.extend({taskId:d()})}),rS=At.merge(Vs),Ym=T({uri:d(),mimeType:he(d()),_meta:_e(d(),xe()).optional()}),Qm=Ym.extend({text:d()}),su=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Xm=Ym.extend({blob:su}),Hs=de(["user","assistant"]),Mo=T({audience:q(Hs).optional(),priority:O().min(0).max(1).optional(),lastModified:Cm({offset:!0}).optional()}),e0=T({...Ro.shape,...zs.shape,uri:d(),description:he(d()),mimeType:he(d()),annotations:Mo.optional(),_meta:he(ft({}))}),nS=T({...Ro.shape,...zs.shape,uriTemplate:d(),description:he(d()),mimeType:he(d()),annotations:Mo.optional(),_meta:he(ft({}))}),Xi=Zs.extend({method:P("resources/list")}),t0=Fs.extend({resources:q(e0)}),au=Zs.extend({method:P("resources/templates/list")}),r0=Fs.extend({resourceTemplates:q(nS)}),iu=ur.extend({uri:d()}),oS=iu,lu=Ot.extend({method:P("resources/read"),params:oS}),n0=At.extend({contents:q(ae([Qm,Xm]))}),cu=kr.extend({method:P("notifications/resources/list_changed"),params:Tr.optional()}),sS=iu,o0=Ot.extend({method:P("resources/subscribe"),params:sS}),aS=iu,s0=Ot.extend({method:P("resources/unsubscribe"),params:aS}),iS=Tr.extend({uri:d()}),a0=kr.extend({method:P("notifications/resources/updated"),params:iS}),lS=T({name:d(),description:he(d()),required:he(ve())}),cS=T({...Ro.shape,...zs.shape,description:he(d()),arguments:he(q(lS)),_meta:he(ft({}))}),uu=Zs.extend({method:P("prompts/list")}),i0=Fs.extend({prompts:q(cS)}),uS=ur.extend({name:d(),arguments:_e(d(),d()).optional()}),du=Ot.extend({method:P("prompts/get"),params:uS}),pu=T({type:P("text"),text:d(),annotations:Mo.optional(),_meta:_e(d(),xe()).optional()}),fu=T({type:P("image"),data:su,mimeType:d(),annotations:Mo.optional(),_meta:_e(d(),xe()).optional()}),hu=T({type:P("audio"),data:su,mimeType:d(),annotations:Mo.optional(),_meta:_e(d(),xe()).optional()}),dS=T({type:P("tool_use"),name:d(),id:d(),input:_e(d(),xe()),_meta:_e(d(),xe()).optional()}),pS=T({type:P("resource"),resource:ae([Qm,Xm]),annotations:Mo.optional(),_meta:_e(d(),xe()).optional()}),fS=e0.extend({type:P("resource_link")}),mu=ae([pu,fu,hu,fS,pS]),hS=T({role:Hs,content:mu}),l0=At.extend({description:d().optional(),messages:q(hS)}),gu=kr.extend({method:P("notifications/prompts/list_changed"),params:Tr.optional()}),mS=T({title:d().optional(),readOnlyHint:ve().optional(),destructiveHint:ve().optional(),idempotentHint:ve().optional(),openWorldHint:ve().optional()}),gS=T({taskSupport:de(["required","optional","forbidden"]).optional()}),c0=T({...Ro.shape,...zs.shape,description:d().optional(),inputSchema:T({type:P("object"),properties:_e(d(),Nt).optional(),required:q(d()).optional()}).catchall(xe()),outputSchema:T({type:P("object"),properties:_e(d(),Nt).optional(),required:q(d()).optional()}).catchall(xe()).optional(),annotations:mS.optional(),execution:gS.optional(),_meta:_e(d(),xe()).optional()}),yu=Zs.extend({method:P("tools/list")}),u0=Fs.extend({tools:q(c0)}),No=At.extend({content:q(mu).default([]),structuredContent:_e(d(),xe()).optional(),isError:ve().optional()});No.or(At.extend({toolResult:xe()}));const yS=Ds.extend({name:d(),arguments:_e(d(),xe()).optional()}),el=Ot.extend({method:P("tools/call"),params:yS}),vu=kr.extend({method:P("notifications/tools/list_changed"),params:Tr.optional()}),vS=T({autoRefresh:ve().default(!0),debounceMs:O().int().nonnegative().default(300)}),tl=de(["debug","info","notice","warning","error","critical","alert","emergency"]),_S=ur.extend({level:tl}),rl=Ot.extend({method:P("logging/setLevel"),params:_S}),wS=Tr.extend({level:tl,logger:d().optional(),data:xe()}),d0=kr.extend({method:P("notifications/message"),params:wS}),bS=T({name:d().optional()}),TS=T({hints:q(bS).optional(),costPriority:O().min(0).max(1).optional(),speedPriority:O().min(0).max(1).optional(),intelligencePriority:O().min(0).max(1).optional()}),kS=T({mode:de(["auto","required","none"]).optional()}),SS=T({type:P("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:q(mu).default([]),structuredContent:T({}).loose().optional(),isError:ve().optional(),_meta:_e(d(),xe()).optional()}),CS=Ve("type",[pu,fu,hu]),nl=Ve("type",[pu,fu,hu,dS,SS]),IS=T({role:Hs,content:ae([nl,q(nl)]),_meta:_e(d(),xe()).optional()}),xS=Ds.extend({messages:q(IS),modelPreferences:TS.optional(),systemPrompt:d().optional(),includeContext:de(["none","thisServer","allServers"]).optional(),temperature:O().optional(),maxTokens:O().int(),stopSequences:q(d()).optional(),metadata:Nt.optional(),tools:q(c0).optional(),toolChoice:kS.optional()}),_u=Ot.extend({method:P("sampling/createMessage"),params:xS}),ol=At.extend({model:d(),stopReason:he(de(["endTurn","stopSequence","maxTokens"]).or(d())),role:Hs,content:CS}),wu=At.extend({model:d(),stopReason:he(de(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:Hs,content:ae([nl,q(nl)])}),ES=T({type:P("boolean"),title:d().optional(),description:d().optional(),default:ve().optional()}),$S=T({type:P("string"),title:d().optional(),description:d().optional(),minLength:O().optional(),maxLength:O().optional(),format:de(["email","uri","date","date-time"]).optional(),default:d().optional()}),RS=T({type:de(["number","integer"]),title:d().optional(),description:d().optional(),minimum:O().optional(),maximum:O().optional(),default:O().optional()}),PS=T({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),default:d().optional()}),MS=T({type:P("string"),title:d().optional(),description:d().optional(),oneOf:q(T({const:d(),title:d()})),default:d().optional()}),NS=T({type:P("string"),title:d().optional(),description:d().optional(),enum:q(d()),enumNames:q(d()).optional(),default:d().optional()}),OS=ae([PS,MS]),AS=T({type:P("array"),title:d().optional(),description:d().optional(),minItems:O().optional(),maxItems:O().optional(),items:T({type:P("string"),enum:q(d())}),default:q(d()).optional()}),qS=T({type:P("array"),title:d().optional(),description:d().optional(),minItems:O().optional(),maxItems:O().optional(),items:T({anyOf:q(T({const:d(),title:d()}))}),default:q(d()).optional()}),LS=ae([AS,qS]),jS=ae([NS,OS,LS]),DS=ae([jS,ES,$S,RS]),US=Ds.extend({mode:P("form").optional(),message:d(),requestedSchema:T({type:P("object"),properties:_e(d(),DS),required:q(d()).optional()})}),zS=Ds.extend({mode:P("url"),message:d(),elicitationId:d(),url:d().url()}),ZS=ae([US,zS]),bu=Ot.extend({method:P("elicitation/create"),params:ZS}),FS=Tr.extend({elicitationId:d()}),VS=kr.extend({method:P("notifications/elicitation/complete"),params:FS}),Bs=At.extend({action:de(["accept","decline","cancel"]),content:Um(e=>e===null?void 0:e,_e(d(),ae([d(),O(),ve(),q(d())])).optional())}),HS=T({type:P("ref/resource"),uri:d()}),BS=T({type:P("ref/prompt"),name:d()}),WS=ur.extend({ref:ae([BS,HS]),argument:T({name:d(),value:d()}),context:T({arguments:_e(d(),d()).optional()}).optional()}),Tu=Ot.extend({method:P("completion/complete"),params:WS});function GS(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function JS(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const p0=At.extend({completion:ft({values:q(d()).max(100),total:he(O().int()),hasMore:he(ve())})}),KS=T({uri:d().startsWith("file://"),name:d().optional(),_meta:_e(d(),xe()).optional()}),f0=Ot.extend({method:P("roots/list"),params:ur.optional()}),ku=At.extend({roots:q(KS)}),h0=kr.extend({method:P("notifications/roots/list_changed"),params:Tr.optional()});ae([Yc,Jm,Tu,rl,du,uu,Xi,au,lu,o0,s0,el,yu,Xc,tu,ru,ou]),ae([Jc,Qc,Kc,h0,Qi]),ae([$n,ol,wu,Bs,ku,eu,nu,Po]),ae([Yc,_u,bu,f0,Xc,tu,ru,ou]),ae([Jc,Qc,d0,a0,cu,vu,gu,Qi,VS]),ae([$n,Km,p0,l0,i0,t0,r0,n0,No,u0,eu,nu,Po]);class ce extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===fe.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new YS(o.elicitations,r)}return new ce(t,r,n)}}class YS extends ce{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(fe.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const QS=J("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");tt.init(e,t),e.def=t,e.parse=(r,n)=>sT(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Oc(e,r,n),e.parseAsync=async(r,n)=>aT(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Ac(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>xn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))}),XS=J("ZodMiniObject",(e,t)=>{sm.init(e,t),QS.init(e,t),Be(e,"shape",()=>t.shape)});function m0(e,t){const r={type:"object",get shape(){return Rs(this,"shape",{...e}),this.shape},...ge(t)};return new XS(r)}function Or(e){return!!e._zod}function Oo(e){const t=Object.values(e);if(t.length===0)return m0({});const r=t.every(Or),n=t.every(o=>!Or(o));if(r)return m0(e);if(n)return Qt(e);throw new Error("Mixed Zod versions detected in object shape.")}function Ar(e,t){return Or(e)?Oc(e,t):e.safeParse(t)}async function Su(e,t){return Or(e)?await Ac(e,t):await e.safeParseAsync(t)}function Ao(e){if(!e)return;let t;if(Or(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Ws(e){if(e){if(typeof e=="object"){const t=e,r=e;if(!t._def&&!r._zod){const n=Object.values(e);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Oo(e)}}if(Or(e)){const r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Cu(e){if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&typeof t=="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function eC(e){return e.description}function tC(e){if(Or(e))return e._zod?.def?.type==="optional";const t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function g0(e){if(Or(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}function to(e){return e==="completed"||e==="failed"||e==="cancelled"}const rC=Symbol("Let zodToJsonSchema decide on which parser to use"),y0={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"},nC=e=>typeof e=="string"?{...y0,name:e}:{...y0,...e},oC=e=>{const t=nC(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function v0(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function Ye(e,t,r,n,o){e[t]=r,v0(e,t,n,o)}const _0=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function er(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?_0(t,e.currentPath):t.join("/")}}function sC(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==B.ZodAny&&(r.items=We(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&Ye(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&Ye(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(Ye(r,"minItems",e.exactLength.value,e.exactLength.message,t),Ye(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function aC(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?Ye(r,"minimum",n.value,n.message,t):Ye(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ye(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ye(r,"maximum",n.value,n.message,t):Ye(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ye(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ye(r,"multipleOf",n.value,n.message,t);break}return r}function iC(){return{type:"boolean"}}function w0(e,t){return We(e.type._def,t)}const lC=(e,t)=>We(e.innerType._def,t);function b0(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>b0(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return cC(e,t)}}const cC=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":Ye(r,"minimum",n.value,n.message,t);break;case"max":Ye(r,"maximum",n.value,n.message,t);break}return r};function uC(e,t){return{...We(e.innerType._def,t),default:e.defaultValue()}}function dC(e,t){return t.effectStrategy==="input"?We(e.schema._def,t):er(t)}function pC(e){return{type:"string",enum:Array.from(e.values)}}const fC=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function hC(e,t){const r=[We(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),We(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return r.forEach(s=>{if(fC(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:i,...l}=s;a=l}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function mC(e,t){const r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}let Iu;const qr={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 T0(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":Ye(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":Ye(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Lr(r,"email",n.message,t);break;case"format:idn-email":Lr(r,"idn-email",n.message,t);break;case"pattern:zod":Bt(r,qr.email,n.message,t);break}break;case"url":Lr(r,"uri",n.message,t);break;case"uuid":Lr(r,"uuid",n.message,t);break;case"regex":Bt(r,n.regex,n.message,t);break;case"cuid":Bt(r,qr.cuid,n.message,t);break;case"cuid2":Bt(r,qr.cuid2,n.message,t);break;case"startsWith":Bt(r,RegExp(`^${xu(n.value,t)}`),n.message,t);break;case"endsWith":Bt(r,RegExp(`${xu(n.value,t)}$`),n.message,t);break;case"datetime":Lr(r,"date-time",n.message,t);break;case"date":Lr(r,"date",n.message,t);break;case"time":Lr(r,"time",n.message,t);break;case"duration":Lr(r,"duration",n.message,t);break;case"length":Ye(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),Ye(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Bt(r,RegExp(xu(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Lr(r,"ipv4",n.message,t),n.version!=="v4"&&Lr(r,"ipv6",n.message,t);break}case"base64url":Bt(r,qr.base64url,n.message,t);break;case"jwt":Bt(r,qr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Bt(r,qr.ipv4Cidr,n.message,t),n.version!=="v4"&&Bt(r,qr.ipv6Cidr,n.message,t);break}case"emoji":Bt(r,qr.emoji(),n.message,t);break;case"ulid":{Bt(r,qr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Lr(r,"binary",n.message,t);break}case"contentEncoding:base64":{Ye(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Bt(r,qr.base64,n.message,t);break}}break}case"nanoid":Bt(r,qr.nanoid,n.message,t)}return r}function xu(e,t){return t.patternStrategy==="escape"?yC(e):e}const gC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function yC(e){let t="";for(let r=0;r<e.length;r++)gC.has(e[r])||(t+="\\"),t+=e[r];return t}function Lr(e,t,r,n){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Ye(e,"format",t,r,n)}function Bt(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:k0(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Ye(e,"pattern",k0(t,n),r,n)}function k0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source;let o="",s=!1,a=!1,i=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(a){if(n[l].match(/[a-z]/)){i?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),i=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],i=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
35
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of this.seen.entries()){const f=u[1];if(t===u[0]){a(u);continue}if(n.external){const h=n.external.registry.get(u[0])?.id;if(t!==u[0]&&h){a(u);continue}}if(this.metadataRegistry.get(u[0])?.id){a(u);continue}if(f.cycle){a(u);continue}if(f.count>1&&n.reused==="ref"){a(u);continue}}const i=(u,f)=>{const p=this.seen.get(u),h=p.def??p.schema,m={...h};if(p.ref===null)return;const _=p.ref;if(p.ref=null,_){i(_,f);const g=this.seen.get(_).schema;g.$ref&&f.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,m))}p.isParent||this.override({zodSchema:u,jsonSchema:h,path:p.path??[]})};for(const u of[...this.seen.entries()].reverse())i(u[0],{target:this.target});const l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){const u=n.external.registry.get(t)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=n.external.uri(u)}Object.assign(l,o.def);const c=n.external?.defs??{};for(const u of this.seen.entries()){const f=u[1];f.def&&f.defId&&(c[f.defId]=f.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 Im(e,t){if(e instanceof ym){const n=new xm(t),o={};for(const i of e._idmap.entries()){const[l,c]=i;n.process(c)}const s={},a={registry:e,uri:t?.uri,defs:o};for(const i of e._idmap.entries()){const[l,c]=i;s[l]=n.emit(c,{...t,external:a})}if(Object.keys(o).length>0){const i=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:o}}return{schemas:s}}const r=new xm(t);return r.process(e),r.emit(e,t)}function Et(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const o=e._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Et(o.element,r);case"object":{for(const s in o.shape)if(Et(o.shape[s],r))return!0;return!1}case"union":{for(const s of o.options)if(Et(s,r))return!0;return!1}case"intersection":return Et(o.left,r)||Et(o.right,r);case"tuple":{for(const s of o.items)if(Et(s,r))return!0;return!!(o.rest&&Et(o.rest,r))}case"record":return Et(o.keyType,r)||Et(o.valueType,r);case"map":return Et(o.keyType,r)||Et(o.valueType,r);case"set":return Et(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Et(o.innerType,r);case"lazy":return Et(o.getter(),r);case"default":return Et(o.innerType,r);case"prefault":return Et(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Et(o.in,r)||Et(o.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${o.type}`)}const VT=K("ZodISODateTime",(e,t)=>{mk.init(e,t),yt.init(e,t)});function $m(e){return _T(VT,e)}const HT=K("ZodISODate",(e,t)=>{gk.init(e,t),yt.init(e,t)});function BT(e){return wT(HT,e)}const JT=K("ZodISOTime",(e,t)=>{yk.init(e,t),yt.init(e,t)});function WT(e){return bT(JT,e)}const GT=K("ZodISODuration",(e,t)=>{vk.init(e,t),yt.init(e,t)});function KT(e){return kT(GT,e)}const Yi=K("ZodError",(e,t)=>{Bh.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>f9(e,r)},flatten:{value:r=>p9(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),YT=Jh(Yi),QT=Wh(Yi),XT=Gh(Yi),Em=Kh(Yi),pt=K("ZodType",(e,t)=>(lt.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Rn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>YT(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>XT(e,r,n),e.parseAsync=async(r,n)=>QT(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Em(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(F4(r,n)),e.superRefine=r=>e.check(V4(r)),e.overwrite=r=>e.check(zs(r)),e.optional=()=>ve(e),e.nullable=()=>Um(e),e.nullish=()=>ve(Um(e)),e.nonoptional=r=>A4(e,r),e.array=()=>j(e),e.or=r=>le([e,r]),e.and=r=>Hc(e,r),e.transform=r=>Jc(e,Lm(r)),e.default=r=>M4(e,r),e.prefault=r=>N4(e,r),e.catch=r=>j4(e,r),e.pipe=r=>Jc(e,r),e.readonly=()=>U4(e),e.describe=r=>{const n=e.clone();return Us.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Us.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Us.get(e);const n=e.clone();return Us.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Rm=K("_ZodString",(e,t)=>{Uc.init(e,t),pt.init(e,t);const r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(PT(...n)),e.includes=(...n)=>e.check(NT(...n)),e.startsWith=(...n)=>e.check(AT(...n)),e.endsWith=(...n)=>e.check(qT(...n)),e.min=(...n)=>e.check(Ki(...n)),e.max=(...n)=>e.check(Sm(...n)),e.length=(...n)=>e.check(Cm(...n)),e.nonempty=(...n)=>e.check(Ki(1,...n)),e.lowercase=n=>e.check(MT(n)),e.uppercase=n=>e.check(OT(n)),e.trim=()=>e.check(LT()),e.normalize=(...n)=>e.check(jT(...n)),e.toLowerCase=()=>e.check(DT()),e.toUpperCase=()=>e.check(UT())}),e4=K("ZodString",(e,t)=>{Uc.init(e,t),Rm.init(e,t),e.email=r=>e.check(eT(t4,r)),e.url=r=>e.check(_m(Mm,r)),e.jwt=r=>e.check(vT(g4,r)),e.emoji=r=>e.check(sT(n4,r)),e.guid=r=>e.check(vm(Pm,r)),e.uuid=r=>e.check(tT(Qi,r)),e.uuidv4=r=>e.check(rT(Qi,r)),e.uuidv6=r=>e.check(nT(Qi,r)),e.uuidv7=r=>e.check(oT(Qi,r)),e.nanoid=r=>e.check(aT(o4,r)),e.guid=r=>e.check(vm(Pm,r)),e.cuid=r=>e.check(iT(s4,r)),e.cuid2=r=>e.check(lT(a4,r)),e.ulid=r=>e.check(cT(i4,r)),e.base64=r=>e.check(wm(Om,r)),e.base64url=r=>e.check(gT(h4,r)),e.xid=r=>e.check(uT(l4,r)),e.ksuid=r=>e.check(dT(c4,r)),e.ipv4=r=>e.check(pT(u4,r)),e.ipv6=r=>e.check(fT(d4,r)),e.cidrv4=r=>e.check(hT(p4,r)),e.cidrv6=r=>e.check(mT(f4,r)),e.e164=r=>e.check(yT(m4,r)),e.datetime=r=>e.check($m(r)),e.date=r=>e.check(BT(r)),e.time=r=>e.check(WT(r)),e.duration=r=>e.check(KT(r))});function d(e){return Xk(e4,e)}const yt=K("ZodStringFormat",(e,t)=>{ht.init(e,t),Rm.init(e,t)}),t4=K("ZodEmail",(e,t)=>{ak.init(e,t),yt.init(e,t)}),Pm=K("ZodGUID",(e,t)=>{ok.init(e,t),yt.init(e,t)}),Qi=K("ZodUUID",(e,t)=>{sk.init(e,t),yt.init(e,t)}),Mm=K("ZodURL",(e,t)=>{ik.init(e,t),yt.init(e,t)});function r4(e){return _m(Mm,e)}const n4=K("ZodEmoji",(e,t)=>{lk.init(e,t),yt.init(e,t)}),o4=K("ZodNanoID",(e,t)=>{ck.init(e,t),yt.init(e,t)}),s4=K("ZodCUID",(e,t)=>{uk.init(e,t),yt.init(e,t)}),a4=K("ZodCUID2",(e,t)=>{dk.init(e,t),yt.init(e,t)}),i4=K("ZodULID",(e,t)=>{pk.init(e,t),yt.init(e,t)}),l4=K("ZodXID",(e,t)=>{fk.init(e,t),yt.init(e,t)}),c4=K("ZodKSUID",(e,t)=>{hk.init(e,t),yt.init(e,t)}),u4=K("ZodIPv4",(e,t)=>{_k.init(e,t),yt.init(e,t)}),d4=K("ZodIPv6",(e,t)=>{wk.init(e,t),yt.init(e,t)}),p4=K("ZodCIDRv4",(e,t)=>{bk.init(e,t),yt.init(e,t)}),f4=K("ZodCIDRv6",(e,t)=>{kk.init(e,t),yt.init(e,t)}),Om=K("ZodBase64",(e,t)=>{Tk.init(e,t),yt.init(e,t)});function Nm(e){return wm(Om,e)}const h4=K("ZodBase64URL",(e,t)=>{Ck.init(e,t),yt.init(e,t)}),m4=K("ZodE164",(e,t)=>{xk.init(e,t),yt.init(e,t)}),g4=K("ZodJWT",(e,t)=>{$k.init(e,t),yt.init(e,t)}),Vc=K("ZodNumber",(e,t)=>{sm.init(e,t),pt.init(e,t),e.gt=(n,o)=>e.check(km(n,o)),e.gte=(n,o)=>e.check(Fc(n,o)),e.min=(n,o)=>e.check(Fc(n,o)),e.lt=(n,o)=>e.check(bm(n,o)),e.lte=(n,o)=>e.check(Zc(n,o)),e.max=(n,o)=>e.check(Zc(n,o)),e.int=n=>e.check(Am(n)),e.safe=n=>e.check(Am(n)),e.positive=n=>e.check(km(0,n)),e.nonnegative=n=>e.check(Fc(0,n)),e.negative=n=>e.check(bm(0,n)),e.nonpositive=n=>e.check(Zc(0,n)),e.multipleOf=(n,o)=>e.check(Tm(n,o)),e.step=(n,o)=>e.check(Tm(n,o)),e.finite=()=>e;const r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function N(e){return TT(Vc,e)}const y4=K("ZodNumberFormat",(e,t)=>{Ek.init(e,t),Vc.init(e,t)});function Am(e){return CT(y4,e)}const v4=K("ZodBoolean",(e,t)=>{Rk.init(e,t),pt.init(e,t)});function Te(e){return xT(v4,e)}const _4=K("ZodNull",(e,t)=>{Pk.init(e,t),pt.init(e,t)});function Zs(e){return IT(_4,e)}const w4=K("ZodAny",(e,t)=>{Mk.init(e,t),pt.init(e,t)});function xt(){return $T(w4)}const b4=K("ZodUnknown",(e,t)=>{Ok.init(e,t),pt.init(e,t)});function Ne(){return ET(b4)}const k4=K("ZodNever",(e,t)=>{Nk.init(e,t),pt.init(e,t)});function T4(e){return RT(k4,e)}const S4=K("ZodArray",(e,t)=>{Ak.init(e,t),pt.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Ki(r,n)),e.nonempty=r=>e.check(Ki(1,r)),e.max=(r,n)=>e.check(Sm(r,n)),e.length=(r,n)=>e.check(Cm(r,n)),e.unwrap=()=>e.element});function j(e,t){return zT(S4,e,t)}const qm=K("ZodObject",(e,t)=>{lm.init(e,t),pt.init(e,t),et(e,"shape",()=>t.shape),e.keyof=()=>ge(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ne()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ne()}),e.strict=()=>e.clone({...e._zod.def,catchall:T4()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>l9(e,r),e.merge=r=>c9(e,r),e.pick=r=>a9(e,r),e.omit=r=>i9(e,r),e.partial=(...r)=>u9(Dm,e,r[0]),e.required=(...r)=>d9(zm,e,r[0])});function k(e,t){const r={type:"object",get shape(){return As(this,"shape",{...e}),this.shape},...we(t)};return new qm(r)}function vt(e,t){return new qm({type:"object",get shape(){return As(this,"shape",{...e}),this.shape},catchall:Ne(),...we(t)})}const jm=K("ZodUnion",(e,t)=>{um.init(e,t),pt.init(e,t),e.options=t.options});function le(e,t){return new jm({type:"union",options:e,...we(t)})}const C4=K("ZodDiscriminatedUnion",(e,t)=>{jm.init(e,t),qk.init(e,t)});function Qe(e,t,r){return new C4({type:"union",options:t,discriminator:e,...we(r)})}const x4=K("ZodIntersection",(e,t)=>{jk.init(e,t),pt.init(e,t)});function Hc(e,t){return new x4({type:"intersection",left:e,right:t})}const I4=K("ZodRecord",(e,t)=>{Lk.init(e,t),pt.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Se(e,t,r){return new I4({type:"record",keyType:e,valueType:t,...we(r)})}const Bc=K("ZodEnum",(e,t)=>{Dk.init(e,t),pt.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{const s={};for(const a of n)if(r.has(a))s[a]=t.entries[a];else throw new Error(`Key ${a} not found in enum`);return new Bc({...t,checks:[],...we(o),entries:s})},e.exclude=(n,o)=>{const s={...t.entries};for(const a of n)if(r.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new Bc({...t,checks:[],...we(o),entries:s})}});function ge(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Bc({type:"enum",entries:r,...we(t)})}const $4=K("ZodLiteral",(e,t)=>{Uk.init(e,t),pt.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function P(e,t){return new $4({type:"literal",values:Array.isArray(e)?e:[e],...we(t)})}const E4=K("ZodTransform",(e,t)=>{zk.init(e,t),pt.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Ds(s,r.value,t));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=e),a.continue??(a.continue=!0),r.issues.push(Ds(a))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Lm(e){return new E4({type:"transform",transform:e})}const Dm=K("ZodOptional",(e,t)=>{Zk.init(e,t),pt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function ve(e){return new Dm({type:"optional",innerType:e})}const R4=K("ZodNullable",(e,t)=>{Fk.init(e,t),pt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Um(e){return new R4({type:"nullable",innerType:e})}const P4=K("ZodDefault",(e,t)=>{Vk.init(e,t),pt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function M4(e,t){return new P4({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const O4=K("ZodPrefault",(e,t)=>{Hk.init(e,t),pt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function N4(e,t){return new O4({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const zm=K("ZodNonOptional",(e,t)=>{Bk.init(e,t),pt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function A4(e,t){return new zm({type:"nonoptional",innerType:e,...we(t)})}const q4=K("ZodCatch",(e,t)=>{Jk.init(e,t),pt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function j4(e,t){return new q4({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const L4=K("ZodPipe",(e,t)=>{Wk.init(e,t),pt.init(e,t),e.in=t.in,e.out=t.out});function Jc(e,t){return new L4({type:"pipe",in:e,out:t})}const D4=K("ZodReadonly",(e,t)=>{Gk.init(e,t),pt.init(e,t)});function U4(e){return new D4({type:"readonly",innerType:e})}const z4=K("ZodLazy",(e,t)=>{Kk.init(e,t),pt.init(e,t),e.unwrap=()=>e._zod.def.getter()});function Xi(e){return new z4({type:"lazy",getter:e})}const Wc=K("ZodCustom",(e,t)=>{Yk.init(e,t),pt.init(e,t)});function Z4(e){const t=new rr({check:"custom"});return t._zod.check=e,t}function Zm(e,t){return ZT(Wc,e??(()=>!0),t)}function F4(e,t={}){return FT(Wc,e,t)}function V4(e){const t=Z4(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ds(n,r.value,t._zod.def));else{const o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Ds(o))}},e(r.value,r)));return t}function el(e,t={error:`Input not instance of ${e.name}`}){const r=new Wc({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...we(t)});return r._zod.bag.Class=e,r}function Fm(e,t){return Jc(Lm(e),t)}const Vm={custom:"custom"};function Hm(e){return ST(Vc,e)}const Fs="2025-11-25",Bm=[Fs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],oo="io.modelcontextprotocol/related-task",tl="2.0",jt=Zm(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Jm=le([d(),N().int()]),Wm=d();vt({ttl:le([N(),Zs()]).optional(),pollInterval:N().optional()});const H4=k({ttl:N().optional()}),B4=k({taskId:d()}),Gc=vt({progressToken:Jm.optional(),[oo]:B4.optional()}),pr=k({_meta:Gc.optional()}),Vs=pr.extend({task:H4.optional()}),J4=e=>Vs.safeParse(e).success,Lt=k({method:d(),params:pr.loose().optional()}),Tr=k({_meta:Gc.optional()}),Sr=k({method:d(),params:Tr.loose().optional()}),Dt=vt({_meta:Gc.optional()}),rl=le([d(),N().int()]),Gm=k({jsonrpc:P(tl),id:rl,...Lt.shape}).strict(),Kc=e=>Gm.safeParse(e).success,Km=k({jsonrpc:P(tl),...Sr.shape}).strict(),W4=e=>Km.safeParse(e).success,Yc=k({jsonrpc:P(tl),id:rl,result:Dt}).strict(),Hs=e=>Yc.safeParse(e).success;var ye;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ye||(ye={}));const Qc=k({jsonrpc:P(tl),id:rl.optional(),error:k({code:N().int(),message:d(),data:Ne().optional()})}).strict(),G4=e=>Qc.safeParse(e).success,hn=le([Gm,Km,Yc,Qc]);le([Yc,Qc]);const Mn=Dt.strict(),K4=Tr.extend({requestId:rl.optional(),reason:d().optional()}),Xc=Sr.extend({method:P("notifications/cancelled"),params:K4}),Y4=k({src:d(),mimeType:d().optional(),sizes:j(d()).optional(),theme:ge(["light","dark"]).optional()}),Bs=k({icons:j(Y4).optional()}),Lo=k({name:d(),title:d().optional()}),Ym=Lo.extend({...Lo.shape,...Bs.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),Q4=Hc(k({applyDefaults:Te().optional()}),Se(d(),Ne())),X4=Fm(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Hc(k({form:Q4.optional(),url:jt.optional()}),Se(d(),Ne()).optional())),eS=vt({list:jt.optional(),cancel:jt.optional(),requests:vt({sampling:vt({createMessage:jt.optional()}).optional(),elicitation:vt({create:jt.optional()}).optional()}).optional()}),tS=vt({list:jt.optional(),cancel:jt.optional(),requests:vt({tools:vt({call:jt.optional()}).optional()}).optional()}),rS=k({experimental:Se(d(),jt).optional(),sampling:k({context:jt.optional(),tools:jt.optional()}).optional(),elicitation:X4.optional(),roots:k({listChanged:Te().optional()}).optional(),tasks:eS.optional()}),nS=pr.extend({protocolVersion:d(),capabilities:rS,clientInfo:Ym}),Qm=Lt.extend({method:P("initialize"),params:nS}),oS=k({experimental:Se(d(),jt).optional(),logging:jt.optional(),completions:jt.optional(),prompts:k({listChanged:Te().optional()}).optional(),resources:k({subscribe:Te().optional(),listChanged:Te().optional()}).optional(),tools:k({listChanged:Te().optional()}).optional(),tasks:tS.optional()}),Xm=Dt.extend({protocolVersion:d(),capabilities:oS,serverInfo:Ym,instructions:d().optional()}),eu=Sr.extend({method:P("notifications/initialized"),params:Tr.optional()}),sS=e=>eu.safeParse(e).success,tu=Lt.extend({method:P("ping"),params:pr.optional()}),aS=k({progress:N(),total:ve(N()),message:ve(d())}),iS=k({...Tr.shape,...aS.shape,progressToken:Jm}),ru=Sr.extend({method:P("notifications/progress"),params:iS}),lS=pr.extend({cursor:Wm.optional()}),Js=Lt.extend({params:lS.optional()}),Ws=Dt.extend({nextCursor:Wm.optional()}),cS=ge(["working","input_required","completed","failed","cancelled"]),Gs=k({taskId:d(),status:cS,ttl:le([N(),Zs()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:ve(N()),statusMessage:ve(d())}),Do=Dt.extend({task:Gs}),uS=Tr.merge(Gs),nl=Sr.extend({method:P("notifications/tasks/status"),params:uS}),nu=Lt.extend({method:P("tasks/get"),params:pr.extend({taskId:d()})}),ou=Dt.merge(Gs),su=Lt.extend({method:P("tasks/result"),params:pr.extend({taskId:d()})});Dt.loose();const au=Js.extend({method:P("tasks/list")}),iu=Ws.extend({tasks:j(Gs)}),lu=Lt.extend({method:P("tasks/cancel"),params:pr.extend({taskId:d()})}),dS=Dt.merge(Gs),e0=k({uri:d(),mimeType:ve(d()),_meta:Se(d(),Ne()).optional()}),t0=e0.extend({text:d()}),cu=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),r0=e0.extend({blob:cu}),Ks=ge(["user","assistant"]),Uo=k({audience:j(Ks).optional(),priority:N().min(0).max(1).optional(),lastModified:$m({offset:!0}).optional()}),n0=k({...Lo.shape,...Bs.shape,uri:d(),description:ve(d()),mimeType:ve(d()),annotations:Uo.optional(),_meta:ve(vt({}))}),pS=k({...Lo.shape,...Bs.shape,uriTemplate:d(),description:ve(d()),mimeType:ve(d()),annotations:Uo.optional(),_meta:ve(vt({}))}),ol=Js.extend({method:P("resources/list")}),o0=Ws.extend({resources:j(n0)}),uu=Js.extend({method:P("resources/templates/list")}),s0=Ws.extend({resourceTemplates:j(pS)}),du=pr.extend({uri:d()}),fS=du,pu=Lt.extend({method:P("resources/read"),params:fS}),a0=Dt.extend({contents:j(le([t0,r0]))}),fu=Sr.extend({method:P("notifications/resources/list_changed"),params:Tr.optional()}),hS=du,i0=Lt.extend({method:P("resources/subscribe"),params:hS}),mS=du,l0=Lt.extend({method:P("resources/unsubscribe"),params:mS}),gS=Tr.extend({uri:d()}),c0=Sr.extend({method:P("notifications/resources/updated"),params:gS}),yS=k({name:d(),description:ve(d()),required:ve(Te())}),vS=k({...Lo.shape,...Bs.shape,description:ve(d()),arguments:ve(j(yS)),_meta:ve(vt({}))}),hu=Js.extend({method:P("prompts/list")}),u0=Ws.extend({prompts:j(vS)}),_S=pr.extend({name:d(),arguments:Se(d(),d()).optional()}),mu=Lt.extend({method:P("prompts/get"),params:_S}),gu=k({type:P("text"),text:d(),annotations:Uo.optional(),_meta:Se(d(),Ne()).optional()}),yu=k({type:P("image"),data:cu,mimeType:d(),annotations:Uo.optional(),_meta:Se(d(),Ne()).optional()}),vu=k({type:P("audio"),data:cu,mimeType:d(),annotations:Uo.optional(),_meta:Se(d(),Ne()).optional()}),wS=k({type:P("tool_use"),name:d(),id:d(),input:Se(d(),Ne()),_meta:Se(d(),Ne()).optional()}),bS=k({type:P("resource"),resource:le([t0,r0]),annotations:Uo.optional(),_meta:Se(d(),Ne()).optional()}),kS=n0.extend({type:P("resource_link")}),_u=le([gu,yu,vu,kS,bS]),TS=k({role:Ks,content:_u}),d0=Dt.extend({description:d().optional(),messages:j(TS)}),wu=Sr.extend({method:P("notifications/prompts/list_changed"),params:Tr.optional()}),SS=k({title:d().optional(),readOnlyHint:Te().optional(),destructiveHint:Te().optional(),idempotentHint:Te().optional(),openWorldHint:Te().optional()}),CS=k({taskSupport:ge(["required","optional","forbidden"]).optional()}),p0=k({...Lo.shape,...Bs.shape,description:d().optional(),inputSchema:k({type:P("object"),properties:Se(d(),jt).optional(),required:j(d()).optional()}).catchall(Ne()),outputSchema:k({type:P("object"),properties:Se(d(),jt).optional(),required:j(d()).optional()}).catchall(Ne()).optional(),annotations:SS.optional(),execution:CS.optional(),_meta:Se(d(),Ne()).optional()}),bu=Js.extend({method:P("tools/list")}),f0=Ws.extend({tools:j(p0)}),zo=Dt.extend({content:j(_u).default([]),structuredContent:Se(d(),Ne()).optional(),isError:Te().optional()});zo.or(Dt.extend({toolResult:Ne()}));const xS=Vs.extend({name:d(),arguments:Se(d(),Ne()).optional()}),sl=Lt.extend({method:P("tools/call"),params:xS}),ku=Sr.extend({method:P("notifications/tools/list_changed"),params:Tr.optional()}),IS=k({autoRefresh:Te().default(!0),debounceMs:N().int().nonnegative().default(300)}),al=ge(["debug","info","notice","warning","error","critical","alert","emergency"]),$S=pr.extend({level:al}),il=Lt.extend({method:P("logging/setLevel"),params:$S}),ES=Tr.extend({level:al,logger:d().optional(),data:Ne()}),h0=Sr.extend({method:P("notifications/message"),params:ES}),RS=k({name:d().optional()}),PS=k({hints:j(RS).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),MS=k({mode:ge(["auto","required","none"]).optional()}),OS=k({type:P("tool_result"),toolUseId:d().describe("The unique identifier for the corresponding tool call."),content:j(_u).default([]),structuredContent:k({}).loose().optional(),isError:Te().optional(),_meta:Se(d(),Ne()).optional()}),NS=Qe("type",[gu,yu,vu]),ll=Qe("type",[gu,yu,vu,wS,OS]),AS=k({role:Ks,content:le([ll,j(ll)]),_meta:Se(d(),Ne()).optional()}),qS=Vs.extend({messages:j(AS),modelPreferences:PS.optional(),systemPrompt:d().optional(),includeContext:ge(["none","thisServer","allServers"]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:j(d()).optional(),metadata:jt.optional(),tools:j(p0).optional(),toolChoice:MS.optional()}),Tu=Lt.extend({method:P("sampling/createMessage"),params:qS}),cl=Dt.extend({model:d(),stopReason:ve(ge(["endTurn","stopSequence","maxTokens"]).or(d())),role:Ks,content:NS}),Su=Dt.extend({model:d(),stopReason:ve(ge(["endTurn","stopSequence","maxTokens","toolUse"]).or(d())),role:Ks,content:le([ll,j(ll)])}),jS=k({type:P("boolean"),title:d().optional(),description:d().optional(),default:Te().optional()}),LS=k({type:P("string"),title:d().optional(),description:d().optional(),minLength:N().optional(),maxLength:N().optional(),format:ge(["email","uri","date","date-time"]).optional(),default:d().optional()}),DS=k({type:ge(["number","integer"]),title:d().optional(),description:d().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),US=k({type:P("string"),title:d().optional(),description:d().optional(),enum:j(d()),default:d().optional()}),zS=k({type:P("string"),title:d().optional(),description:d().optional(),oneOf:j(k({const:d(),title:d()})),default:d().optional()}),ZS=k({type:P("string"),title:d().optional(),description:d().optional(),enum:j(d()),enumNames:j(d()).optional(),default:d().optional()}),FS=le([US,zS]),VS=k({type:P("array"),title:d().optional(),description:d().optional(),minItems:N().optional(),maxItems:N().optional(),items:k({type:P("string"),enum:j(d())}),default:j(d()).optional()}),HS=k({type:P("array"),title:d().optional(),description:d().optional(),minItems:N().optional(),maxItems:N().optional(),items:k({anyOf:j(k({const:d(),title:d()}))}),default:j(d()).optional()}),BS=le([VS,HS]),JS=le([ZS,FS,BS]),WS=le([JS,jS,LS,DS]),GS=Vs.extend({mode:P("form").optional(),message:d(),requestedSchema:k({type:P("object"),properties:Se(d(),WS),required:j(d()).optional()})}),KS=Vs.extend({mode:P("url"),message:d(),elicitationId:d(),url:d().url()}),YS=le([GS,KS]),Cu=Lt.extend({method:P("elicitation/create"),params:YS}),QS=Tr.extend({elicitationId:d()}),XS=Sr.extend({method:P("notifications/elicitation/complete"),params:QS}),Ys=Dt.extend({action:ge(["accept","decline","cancel"]),content:Fm(e=>e===null?void 0:e,Se(d(),le([d(),N(),Te(),j(d())])).optional())}),eC=k({type:P("ref/resource"),uri:d()}),tC=k({type:P("ref/prompt"),name:d()}),rC=pr.extend({ref:le([tC,eC]),argument:k({name:d(),value:d()}),context:k({arguments:Se(d(),d()).optional()}).optional()}),xu=Lt.extend({method:P("completion/complete"),params:rC});function nC(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function oC(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const m0=Dt.extend({completion:vt({values:j(d()).max(100),total:ve(N().int()),hasMore:ve(Te())})}),sC=k({uri:d().startsWith("file://"),name:d().optional(),_meta:Se(d(),Ne()).optional()}),g0=Lt.extend({method:P("roots/list"),params:pr.optional()}),Iu=Dt.extend({roots:j(sC)}),y0=Sr.extend({method:P("notifications/roots/list_changed"),params:Tr.optional()});le([tu,Qm,xu,il,mu,hu,ol,uu,pu,i0,l0,sl,bu,nu,su,au,lu]),le([Xc,ru,eu,y0,nl]),le([Mn,cl,Su,Ys,Iu,ou,iu,Do]),le([tu,Tu,Cu,g0,nu,su,au,lu]),le([Xc,ru,h0,c0,fu,ku,wu,nl,XS]),le([Mn,Xm,m0,d0,u0,o0,s0,a0,zo,f0,ou,iu,Do]);class fe extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===ye.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new aC(o.elicitations,r)}return new fe(t,r,n)}}class aC extends fe{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(ye.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}const iC=K("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");lt.init(e,t),e.def=t,e.parse=(r,n)=>h9(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Lc(e,r,n),e.parseAsync=async(r,n)=>m9(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>Dc(e,r,n),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>Rn(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e))}),lC=K("ZodMiniObject",(e,t)=>{lm.init(e,t),iC.init(e,t),et(e,"shape",()=>t.shape)});function v0(e,t){const r={type:"object",get shape(){return As(this,"shape",{...e}),this.shape},...we(t)};return new lC(r)}function Nr(e){return!!e._zod}function Zo(e){const t=Object.values(e);if(t.length===0)return v0({});const r=t.every(Nr),n=t.every(o=>!Nr(o));if(r)return v0(e);if(n)return tr(e);throw new Error("Mixed Zod versions detected in object shape.")}function Ar(e,t){return Nr(e)?Lc(e,t):e.safeParse(t)}async function $u(e,t){return Nr(e)?await Dc(e,t):await e.safeParseAsync(t)}function Fo(e){if(!e)return;let t;if(Nr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Qs(e){if(e){if(typeof e=="object"){const t=e,r=e;if(!t._def&&!r._zod){const n=Object.values(e);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Zo(e)}}if(Nr(e)){const r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Eu(e){if(e&&typeof e=="object"){if("message"in e&&typeof e.message=="string")return e.message;if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0){const t=e.issues[0];if(t&&typeof t=="object"&&"message"in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function cC(e){return e.description}function uC(e){if(Nr(e))return e._zod?.def?.type==="optional";const t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function _0(e){if(Nr(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}function so(e){return e==="completed"||e==="failed"||e==="cancelled"}const dC=Symbol("Let zodToJsonSchema decide on which parser to use"),w0={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"},pC=e=>typeof e=="string"?{...w0,name:e}:{...w0,...e},fC=e=>{const t=pC(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}};function b0(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function st(e,t,r,n,o){e[t]=r,b0(e,t,n,o)}const k0=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function nr(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?k0(t,e.currentPath):t.join("/")}}function hC(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==G.ZodAny&&(r.items=tt(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&st(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&st(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(st(r,"minItems",e.exactLength.value,e.exactLength.message,t),st(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}function mC(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?st(r,"minimum",n.value,n.message,t):st(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),st(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?st(r,"maximum",n.value,n.message,t):st(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),st(r,"maximum",n.value,n.message,t));break;case"multipleOf":st(r,"multipleOf",n.value,n.message,t);break}return r}function gC(){return{type:"boolean"}}function T0(e,t){return tt(e.type._def,t)}const yC=(e,t)=>tt(e.innerType._def,t);function S0(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>S0(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return vC(e,t)}}const vC=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":st(r,"minimum",n.value,n.message,t);break;case"max":st(r,"maximum",n.value,n.message,t);break}return r};function _C(e,t){return{...tt(e.innerType._def,t),default:e.defaultValue()}}function wC(e,t){return t.effectStrategy==="input"?tt(e.schema._def,t):nr(t)}function bC(e){return{type:"string",enum:Array.from(e.values)}}const kC=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function TC(e,t){const r=[tt(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),tt(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return r.forEach(s=>{if(kC(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:i,...l}=s;a=l}else n=void 0;o.push(a)}}),o.length?{allOf:o,...n}:void 0}function SC(e,t){const r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}let Ru;const qr={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:()=>(Ru===void 0&&(Ru=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ru),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 C0(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":st(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":st(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":jr(r,"email",n.message,t);break;case"format:idn-email":jr(r,"idn-email",n.message,t);break;case"pattern:zod":Kt(r,qr.email,n.message,t);break}break;case"url":jr(r,"uri",n.message,t);break;case"uuid":jr(r,"uuid",n.message,t);break;case"regex":Kt(r,n.regex,n.message,t);break;case"cuid":Kt(r,qr.cuid,n.message,t);break;case"cuid2":Kt(r,qr.cuid2,n.message,t);break;case"startsWith":Kt(r,RegExp(`^${Pu(n.value,t)}`),n.message,t);break;case"endsWith":Kt(r,RegExp(`${Pu(n.value,t)}$`),n.message,t);break;case"datetime":jr(r,"date-time",n.message,t);break;case"date":jr(r,"date",n.message,t);break;case"time":jr(r,"time",n.message,t);break;case"duration":jr(r,"duration",n.message,t);break;case"length":st(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),st(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Kt(r,RegExp(Pu(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&jr(r,"ipv4",n.message,t),n.version!=="v4"&&jr(r,"ipv6",n.message,t);break}case"base64url":Kt(r,qr.base64url,n.message,t);break;case"jwt":Kt(r,qr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Kt(r,qr.ipv4Cidr,n.message,t),n.version!=="v4"&&Kt(r,qr.ipv6Cidr,n.message,t);break}case"emoji":Kt(r,qr.emoji(),n.message,t);break;case"ulid":{Kt(r,qr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{jr(r,"binary",n.message,t);break}case"contentEncoding:base64":{st(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Kt(r,qr.base64,n.message,t);break}}break}case"nanoid":Kt(r,qr.nanoid,n.message,t)}return r}function Pu(e,t){return t.patternStrategy==="escape"?xC(e):e}const CC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function xC(e){let t="";for(let r=0;r<e.length;r++)CC.has(e[r])||(t+="\\"),t+=e[r];return t}function jr(e,t,r,n){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):st(e,"format",t,r,n)}function Kt(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:x0(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):st(e,"pattern",x0(t,n),r,n)}function x0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source;let o="",s=!1,a=!1,i=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(a){if(n[l].match(/[a-z]/)){i?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),i=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],i=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
36
36
  ]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
37
37
  ]))`;continue}}if(r.s&&n[l]==="."){o+=a?`${n[l]}\r
38
38
  `:`[${n[l]}\r
39
- ]`;continue}o+=n[l],n[l]==="\\"?s=!0:a&&n[l]==="]"?a=!1:!a&&n[l]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function S0(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===B.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:We(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??er(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:We(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===B.ZodString&&e.keyType._def.checks?.length){const{type:n,...o}=T0(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===B.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===B.ZodBranded&&e.keyType._def.type._def.typeName===B.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...o}=w0(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function vC(e,t){if(t.mapStrategy==="record")return S0(e,t);const r=We(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||er(t),n=We(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||er(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function _C(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function wC(e){return e.target==="openAi"?void 0:{not:er({...e,currentPath:[...e.currentPath,"not"]})}}function bC(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const sl={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function TC(e,t){if(t.target==="openApi3")return C0(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in sl&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=sl[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return C0(e,t)}const C0=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>We(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function kC(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:sl[e.innerType._def.typeName],nullable:!0}:{type:[sl[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const n=We(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=We(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function SC(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",v0(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?Ye(r,"minimum",n.value,n.message,t):Ye(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),Ye(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?Ye(r,"maximum",n.value,n.message,t):Ye(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),Ye(r,"maximum",n.value,n.message,t));break;case"multipleOf":Ye(r,"multipleOf",n.value,n.message,t);break}return r}function CC(e,t){const r=t.target==="openAi",n={type:"object",properties:{}},o=[],s=e.shape();for(const i in s){let l=s[i];if(l===void 0||l._def===void 0)continue;let c=xC(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=We(l._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});u!==void 0&&(n.properties[i]=u,c||o.push(i))}o.length&&(n.required=o);const a=IC(e,t);return a!==void 0&&(n.additionalProperties=a),n}function IC(e,t){if(e.catchall._def.typeName!=="ZodNever")return We(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function xC(e){try{return e.isOptional()}catch{return!0}}const EC=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return We(e.innerType._def,t);const r=We(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:er(t)},r]}:er(t)},$C=(e,t)=>{if(t.pipeStrategy==="input")return We(e.in._def,t);if(t.pipeStrategy==="output")return We(e.out._def,t);const r=We(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=We(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function RC(e,t){return We(e.type._def,t)}function PC(e,t){const n={type:"array",uniqueItems:!0,items:We(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&Ye(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&Ye(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function MC(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>We(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:We(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>We(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function NC(e){return{not:er(e)}}function OC(e){return er(e)}const AC=(e,t)=>We(e.innerType._def,t),qC=(e,t,r)=>{switch(t){case B.ZodString:return T0(e,r);case B.ZodNumber:return SC(e,r);case B.ZodObject:return CC(e,r);case B.ZodBigInt:return aC(e,r);case B.ZodBoolean:return iC();case B.ZodDate:return b0(e,r);case B.ZodUndefined:return NC(r);case B.ZodNull:return bC(r);case B.ZodArray:return sC(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return TC(e,r);case B.ZodIntersection:return hC(e,r);case B.ZodTuple:return MC(e,r);case B.ZodRecord:return S0(e,r);case B.ZodLiteral:return mC(e,r);case B.ZodEnum:return pC(e);case B.ZodNativeEnum:return _C(e);case B.ZodNullable:return kC(e,r);case B.ZodOptional:return EC(e,r);case B.ZodMap:return vC(e,r);case B.ZodSet:return PC(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return RC(e,r);case B.ZodNaN:case B.ZodNever:return wC(r);case B.ZodEffects:return dC(e,r);case B.ZodAny:return er(r);case B.ZodUnknown:return OC(r);case B.ZodDefault:return uC(e,r);case B.ZodBranded:return w0(e,r);case B.ZodReadonly:return AC(e,r);case B.ZodCatch:return lC(e,r);case B.ZodPipeline:return $C(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}};function We(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==rC)return i}if(n&&!r){const i=LC(n,t);if(i!==void 0)return i}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=qC(e,e.typeName,t),a=typeof s=="function"?We(s(),t):s;if(a&&jC(e,t,a),t.postProcess){const i=t.postProcess(a,e,t);return o.jsonSchema=a,i}return o.jsonSchema=a,a}const LC=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:_0(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),er(t)):t.$refStrategy==="seen"?er(t):void 0}},jC=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),DC=(e,t)=>{const r=oC(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,u])=>({...l,[c]:We(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??er(r)}),{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=We(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??er(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.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=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};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 UC(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function I0(e,t){return Or(e)?Sm(e,{target:UC(t?.target),io:t?.pipeStrategy??"input"}):DC(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function x0(e){const r=Ao(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=g0(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function E0(e,t){const r=Ar(e,t);if(!r.success)throw r.error;return r.data}const zC=6e4;class $0{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Jc,r=>{this._oncancel(r)}),this.setNotificationHandler(Qc,r=>{this._onprogress(r)}),this.setRequestHandler(Yc,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Xc,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ce(fe.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(tu,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(i.type==="response"||i.type==="error"){const l=i.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(l);else{const f=l,p=new ce(f.error.code,f.error.message,f.error.data);u(p)}else{const f=i.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new ce(fe.InvalidParams,`Task not found: ${s}`);if(!to(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(to(a.status)){const i=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...i,_meta:{...i._meta,[eo]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ru,async(r,n)=>{try{const{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new ce(fe.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ou,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new ce(fe.InvalidParams,`Task not found: ${r.params.taskId}`);if(to(o.status))throw new ce(fe.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new ce(fe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof ce?o:new ce(fe.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),ce.fromError(fe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),Us(s)||U4(s)?this._onresponse(s):Bc(s)?this._onrequest(s,a):D4(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=ce.fromError(fe.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[eo]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:fe.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):o?.send(u).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=j4(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:a.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const f={relatedRequestId:t.id};s&&(f.relatedTask={taskId:s}),await this.notification(u,f)},sendRequest:async(u,f,p)=>{const h={...p,relatedRequestId:t.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});const m=h.relatedTask?.taskId??s;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(u,f,h)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(a.signal.aborted)return;const f={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)},async u=>{if(a.signal.aborted)return;const f={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:fe.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Us(t))n(t);else{const a=new ce(t.error.code,t.error.message,t.error.data);n(a)}return}const o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Us(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(s=!0,this._taskProgressTokens.set(i.taskId,r))}}if(s||this._progressHandlers.delete(r),Us(t))o(t);else{const a=ce.fromError(t.error.code,t.error.message,t.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){const{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(a){yield{type:"error",error:a instanceof ce?a:new ce(fe.InternalError,String(a))}}return}let s;try{const a=await this.request(t,Po,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new ce(fe.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},to(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new ce(fe.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new ce(fe.InternalError,`Task ${s} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof ce?a:new ce(fe.InternalError,String(a))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{const f=v=>{u(v)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(v){f(v);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),h.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),i&&(h.params={...h.params,task:i}),l&&(h.params={...h.params,_meta:{...h.params?._meta||{},[eo]:l}});const m=v=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));const g=v instanceof ce?v:new ce(fe.RequestTimeout,String(v));u(g)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{const g=Ar(r,v.result);g.success?c(g.data):u(g.error)}catch(g){u(g)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});const _=n?.timeout??zC,y=()=>m(ce.fromError(fe.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const v=g=>{const S=this._responseHandlers.get(p);S?S(g):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(w,{type:"request",message:h,timestamp:Date.now()}).catch(g=>{this._cleanupTimeout(p),u(g)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(p),u(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},eu,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},nu,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},rS,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=r?.relatedTask?.taskId;if(n){const i={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[eo]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[eo]:r.relatedTask}}}),this._transport?.send(i,r).catch(l=>this._onerror(l))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[eo]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const n=x0(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=E0(t,o);return Promise.resolve(r(a,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const n=x0(t);this._notificationHandlers.set(n,o=>{const s=E0(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,r);for(const o of n)if(o.type==="request"&&Bc(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new ce(fe.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new ce(fe.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new ce(fe.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new ce(fe.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,a)=>{await n.storeTaskResult(o,s,a,r);const i=await n.getTask(o,r);if(i){const l=Qi.parse({method:"notifications/tasks/status",params:i});await this.notification(l),to(i.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,a)=>{const i=await n.getTask(o,r);if(!i)throw new ce(fe.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(to(i.status))throw new ce(fe.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,a,r);const l=await n.getTask(o,r);if(l){const c=Qi.parse({method:"notifications/tasks/status",params:l});await this.notification(c),to(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function R0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function P0(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const a=r[o];R0(a)&&R0(s)?r[o]={...a,...s}:r[o]=s}return r}var al={exports:{}},Eu={},M0;function ZC(){return M0||(M0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(N,L){return{validate:N,compare:L}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(p(!0),h),"iso-time":t(l(),u),"iso-date-time":t(p(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:j,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:g,int32:{type:"number",validate:k},int64:{type:"number",validate:C},float:{type:"number",validate:R},double:{type:"number",validate:R},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(N){return N%4===0&&(N%100!==0||N%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(N){const L=n.exec(N);if(!L)return!1;const z=+L[1],H=+L[2],ee=+L[3];return H>=1&&H<=12&&ee>=1&&ee<=(H===2&&r(z)?29:o[H])}function a(N,L){if(N&&L)return N>L?1:N<L?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(N){return function(z){const H=i.exec(z);if(!H)return!1;const ee=+H[1],te=+H[2],X=+H[3],V=H[4],se=H[5]==="-"?-1:1,D=+(H[6]||0),E=+(H[7]||0);if(D>23||E>59||N&&!V)return!1;if(ee<=23&&te<=59&&X<60)return!0;const U=te-E*se,Z=ee-D*se-(U<0?1:0);return(Z===23||Z===-1)&&(U===59||U===-1)&&X<61}}function c(N,L){if(!(N&&L))return;const z=new Date("2020-01-01T"+N).valueOf(),H=new Date("2020-01-01T"+L).valueOf();if(z&&H)return z-H}function u(N,L){if(!(N&&L))return;const z=i.exec(N),H=i.exec(L);if(z&&H)return N=z[1]+z[2]+z[3],L=H[1]+H[2]+H[3],N>L?1:N<L?-1:0}const f=/t|\s/i;function p(N){const L=l(N);return function(H){const ee=H.split(f);return ee.length===2&&s(ee[0])&&L(ee[1])}}function h(N,L){if(!(N&&L))return;const z=new Date(N).valueOf(),H=new Date(L).valueOf();if(z&&H)return z-H}function m(N,L){if(!(N&&L))return;const[z,H]=N.split(f),[ee,te]=L.split(f),X=a(z,ee);if(X!==void 0)return X||c(H,te)}const _=/\/|:/,y=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function w(N){return _.test(N)&&y.test(N)}const v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g(N){return v.lastIndex=0,v.test(N)}const S=-2147483648,b=2**31-1;function k(N){return Number.isInteger(N)&&N<=b&&N>=S}function C(N){return Number.isInteger(N)}function R(){return!0}const I=/[^\\]\\Z/;function j(N){if(I.test(N))return!1;try{return new RegExp(N),!0}catch{return!1}}})(Eu)),Eu}var $u={},N0;function FC(){return N0||(N0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Sh(),r=Ne(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:i,schemaCode:l})=>(0,r.str)`should be ${o[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${o[i].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(i){const{gen:l,data:c,schemaCode:u,keyword:f,it:p}=i,{opts:h,self:m}=p;if(!h.validateFormats)return;const _=new t.KeywordCxt(p,m.RULES.all.format.definition,"format");_.$data?y():w();function y(){const g=l.scopeValue("formats",{ref:m.formats,code:h.code.formats}),S=l.const("fmt",(0,r._)`${g}[${_.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${S} != "object"`,(0,r._)`${S} instanceof RegExp`,(0,r._)`typeof ${S}.compare != "function"`,v(S)))}function w(){const g=_.schema,S=m.formats[g];if(!S||S===!0)return;if(typeof S!="object"||S instanceof RegExp||typeof S.compare!="function")throw new Error(`"${f}": format "${g}" does not define "compare" function`);const b=l.scopeValue("formats",{key:g,ref:S,code:h.code.formats?(0,r._)`${h.code.formats}${(0,r.getProperty)(g)}`:void 0});i.fail$data(v(b))}function v(g){return(0,r._)`${g}.compare(${c}, ${u}) ${o[f].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})($u)),$u}var O0;function VC(){return O0||(O0=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=ZC(),n=FC(),o=Ne(),s=new o.Name("fullFormats"),a=new o.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[f,p]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,s],h=u.formats||r.formatNames;return l(c,h,f,p),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const p=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!p)throw new Error(`Unknown format "${c}"`);return p};function l(c,u,f,p){var h,m;(h=(m=c.opts.code).formats)!==null&&h!==void 0||(m.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const _ of u)c.addFormat(_,f[_])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(al,al.exports)),al.exports}var HC=VC();const BC=Vn(HC);function WC(){const e=new Ch({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return BC(e),e}class A0{constructor(t){this._ajv=t??WC()}getValidator(t){const r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class GC{constructor(t){this._client=t}async*callToolStream(t,r=No,n){const o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},a=o.requestStream({method:"tools/call",params:t},r,s),i=o.getToolOutputValidator(t.name);for await(const l of a){if(l.type==="result"&&i){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new ce(fe.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=i(c.structuredContent);if(!u.valid){yield{type:"error",error:new ce(fe.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof ce){yield{type:"error",error:u};return}yield{type:"error",error:new ce(fe.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function q0(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break}}function L0(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break}}function il(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&il(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&il(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&il(r,t)}}function JC(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}class Gs extends $0{constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new A0,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",vu,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",gu,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",cu,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new GC(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=P0(this._capabilities,t)}setRequestHandler(t,r){const o=Ao(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Or(o)){const i=o;s=i._zod?.def?.value??i.value}else{const i=o;s=i._def?.value??i.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const a=s;if(a==="elicitation/create"){const i=async(l,c)=>{const u=Ar(bu,l);if(!u.success){const v=u.error instanceof Error?u.error.message:String(u.error);throw new ce(fe.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:f}=u.data;f.mode=f.mode??"form";const{supportsFormMode:p,supportsUrlMode:h}=JC(this._capabilities.elicitation);if(f.mode==="form"&&!p)throw new ce(fe.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!h)throw new ce(fe.InvalidParams,"Client does not support URL-mode elicitation requests");const m=await Promise.resolve(r(l,c));if(f.task){const v=Ar(Po,m);if(!v.success){const g=v.error instanceof Error?v.error.message:String(v.error);throw new ce(fe.InvalidParams,`Invalid task creation result: ${g}`)}return v.data}const _=Ar(Bs,m);if(!_.success){const v=_.error instanceof Error?_.error.message:String(_.error);throw new ce(fe.InvalidParams,`Invalid elicitation result: ${v}`)}const y=_.data,w=f.mode==="form"?f.requestedSchema:void 0;if(f.mode==="form"&&y.action==="accept"&&y.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{il(w,y.content)}catch{}return y};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=Ar(_u,l);if(!u.success){const y=u.error instanceof Error?u.error.message:String(u.error);throw new ce(fe.InvalidParams,`Invalid sampling request: ${y}`)}const{params:f}=u.data,p=await Promise.resolve(r(l,c));if(f.task){const y=Ar(Po,p);if(!y.success){const w=y.error instanceof Error?y.error.message:String(y.error);throw new ce(fe.InvalidParams,`Invalid task creation result: ${w}`)}return y.data}const m=f.tools||f.toolChoice?wu:ol,_=Ar(m,p);if(!_.success){const y=_.error instanceof Error?_.error.message:String(_.error);throw new ce(fe.InvalidParams,`Invalid sampling result: ${y}`)}return _.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:js,capabilities:this._capabilities,clientInfo:this._clientInfo}},Km,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Fm.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){q0(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&L0(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},$n,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},p0,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},$n,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},l0,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},i0,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},t0,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},r0,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},n0,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},$n,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},$n,r)}async callTool(t,r=No,n){if(this.isToolTaskRequired(t.name))throw new ce(fe.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new ce(fe.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new ce(fe.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof ce?a:new ce(fe.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},u0,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=vS.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=s.data,{onChanged:l}=n,c=async()=>{if(!a){l(null,null);return}try{const f=await o();l(null,f)}catch(f){const p=f instanceof Error?f:new Error(String(f));l(p,null)}},u=()=>{if(i){const f=this._listChangedDebounceTimers.get(t);f&&clearTimeout(f);const p=setTimeout(c,i);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class j0 extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Ru(e){}function D0(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Ru,onError:r=Ru,onRetry:n=Ru,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(_){const y=a?_.replace(/^\xEF\xBB\xBF/,""):_,[w,v]=KC(`${s}${y}`);for(const g of w)f(g);s=v,a=!1}function f(_){if(_===""){h();return}if(_.startsWith(":")){o&&o(_.slice(_.startsWith(": ")?2:1));return}const y=_.indexOf(":");if(y!==-1){const w=_.slice(0,y),v=_[y+1]===" "?2:1,g=_.slice(y+v);p(w,g,_);return}p(_,"",_)}function p(_,y,w){switch(_){case"event":c=y;break;case"data":l=`${l}${y}
40
- `;break;case"id":i=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?n(parseInt(y,10)):r(new j0(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:w}));break;default:r(new j0(`Unknown field "${_.length>20?`${_.slice(0,20)}…`:_}"`,{type:"unknown-field",field:_,value:y,line:w}));break}}function h(){l.length>0&&t({id:i,event:c||void 0,data:l.endsWith(`
41
- `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function m(_={}){s&&_.consume&&f(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:m}}function KC(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
39
+ ]`;continue}o+=n[l],n[l]==="\\"?s=!0:a&&n[l]==="]"?a=!1:!a&&n[l]==="["&&(a=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}function I0(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===G.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:tt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??nr(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const r={type:"object",additionalProperties:tt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===G.ZodString&&e.keyType._def.checks?.length){const{type:n,...o}=C0(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===G.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===G.ZodBranded&&e.keyType._def.type._def.typeName===G.ZodString&&e.keyType._def.type._def.checks?.length){const{type:n,...o}=T0(e.keyType._def,t);return{...r,propertyNames:o}}}return r}function IC(e,t){if(t.mapStrategy==="record")return I0(e,t);const r=tt(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||nr(t),n=tt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||nr(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function $C(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function EC(e){return e.target==="openAi"?void 0:{not:nr({...e,currentPath:[...e.currentPath,"not"]})}}function RC(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ul={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function PC(e,t){if(t.target==="openApi3")return $0(e,t);const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in ul&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=ul[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return $0(e,t)}const $0=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>tt(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function MC(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:ul[e.innerType._def.typeName],nullable:!0}:{type:[ul[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const n=tt(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=tt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function OC(e,t){const r={type:"number"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"int":r.type="integer",b0(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?st(r,"minimum",n.value,n.message,t):st(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),st(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?st(r,"maximum",n.value,n.message,t):st(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),st(r,"maximum",n.value,n.message,t));break;case"multipleOf":st(r,"multipleOf",n.value,n.message,t);break}return r}function NC(e,t){const r=t.target==="openAi",n={type:"object",properties:{}},o=[],s=e.shape();for(const i in s){let l=s[i];if(l===void 0||l._def===void 0)continue;let c=qC(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=tt(l._def,{...t,currentPath:[...t.currentPath,"properties",i],propertyPath:[...t.currentPath,"properties",i]});u!==void 0&&(n.properties[i]=u,c||o.push(i))}o.length&&(n.required=o);const a=AC(e,t);return a!==void 0&&(n.additionalProperties=a),n}function AC(e,t){if(e.catchall._def.typeName!=="ZodNever")return tt(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function qC(e){try{return e.isOptional()}catch{return!0}}const jC=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return tt(e.innerType._def,t);const r=tt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:nr(t)},r]}:nr(t)},LC=(e,t)=>{if(t.pipeStrategy==="input")return tt(e.in._def,t);if(t.pipeStrategy==="output")return tt(e.out._def,t);const r=tt(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=tt(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function DC(e,t){return tt(e.type._def,t)}function UC(e,t){const n={type:"array",uniqueItems:!0,items:tt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&st(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&st(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}function zC(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>tt(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:tt(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>tt(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function ZC(e){return{not:nr(e)}}function FC(e){return nr(e)}const VC=(e,t)=>tt(e.innerType._def,t),HC=(e,t,r)=>{switch(t){case G.ZodString:return C0(e,r);case G.ZodNumber:return OC(e,r);case G.ZodObject:return NC(e,r);case G.ZodBigInt:return mC(e,r);case G.ZodBoolean:return gC();case G.ZodDate:return S0(e,r);case G.ZodUndefined:return ZC(r);case G.ZodNull:return RC(r);case G.ZodArray:return hC(e,r);case G.ZodUnion:case G.ZodDiscriminatedUnion:return PC(e,r);case G.ZodIntersection:return TC(e,r);case G.ZodTuple:return zC(e,r);case G.ZodRecord:return I0(e,r);case G.ZodLiteral:return SC(e,r);case G.ZodEnum:return bC(e);case G.ZodNativeEnum:return $C(e);case G.ZodNullable:return MC(e,r);case G.ZodOptional:return jC(e,r);case G.ZodMap:return IC(e,r);case G.ZodSet:return UC(e,r);case G.ZodLazy:return()=>e.getter()._def;case G.ZodPromise:return DC(e,r);case G.ZodNaN:case G.ZodNever:return EC(r);case G.ZodEffects:return wC(e,r);case G.ZodAny:return nr(r);case G.ZodUnknown:return FC(r);case G.ZodDefault:return _C(e,r);case G.ZodBranded:return T0(e,r);case G.ZodReadonly:return VC(e,r);case G.ZodCatch:return yC(e,r);case G.ZodPipeline:return LC(e,r);case G.ZodFunction:case G.ZodVoid:case G.ZodSymbol:return;default:return(n=>{})()}};function tt(e,t,r=!1){const n=t.seen.get(e);if(t.override){const i=t.override?.(e,t,n,r);if(i!==dC)return i}if(n&&!r){const i=BC(n,t);if(i!==void 0)return i}const o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);const s=HC(e,e.typeName,t),a=typeof s=="function"?tt(s(),t):s;if(a&&JC(e,t,a),t.postProcess){const i=t.postProcess(a,e,t);return o.jsonSchema=a,i}return o.jsonSchema=a,a}const BC=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:k0(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),nr(t)):t.$refStrategy==="seen"?nr(t):void 0}},JC=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r),WC=(e,t)=>{const r=fC(t);let n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[c,u])=>({...l,[c]:tt(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??nr(r)}),{}):void 0;const o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=tt(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??nr(r),a=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;a!==void 0&&(s.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=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};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 GC(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function E0(e,t){return Nr(e)?Im(e,{target:GC(t?.target),io:t?.pipeStrategy??"input"}):WC(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function R0(e){const r=Fo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=_0(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function P0(e,t){const r=Ar(e,t);if(!r.success)throw r.error;return r.data}const KC=6e4;class M0{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Xc,r=>{this._oncancel(r)}),this.setNotificationHandler(ru,r=>{this._onprogress(r)}),this.setRequestHandler(tu,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(nu,async(r,n)=>{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new fe(ye.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(su,async(r,n)=>{const o=async()=>{const s=r.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(i.type==="response"||i.type==="error"){const l=i.message,c=l.id,u=this._requestResolvers.get(c);if(u)if(this._requestResolvers.delete(c),i.type==="response")u(l);else{const f=l,p=new fe(f.error.code,f.error.message,f.error.data);u(p)}else{const f=i.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:n.requestId})}}const a=await this._taskStore.getTask(s,n.sessionId);if(!a)throw new fe(ye.InvalidParams,`Task not found: ${s}`);if(!so(a.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(so(a.status)){const i=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...i,_meta:{...i._meta,[oo]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(au,async(r,n)=>{try{const{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new fe(ye.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(lu,async(r,n)=>{try{const o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new fe(ye.InvalidParams,`Task not found: ${r.params.taskId}`);if(so(o.status))throw new fe(ye.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);const s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new fe(ye.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof fe?o:new fe(ye.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){const r=this._timeoutInfo.get(t);if(!r)return!1;const n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),fe.fromError(ye.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){const r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;const r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};const n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};const o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),Hs(s)||G4(s)?this._onresponse(s):Kc(s)?this._onrequest(s,a):W4(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();const r=fe.fromError(ye.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){const r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){const n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[oo]?.taskId;if(n===void 0){const u={jsonrpc:"2.0",id:t.id,error:{code:ye.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):o?.send(u).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}const a=new AbortController;this._requestHandlerAbortControllers.set(t.id,a);const i=J4(t.params)?t.params.task:void 0,l=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,c={signal:a.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async u=>{const f={relatedRequestId:t.id};s&&(f.relatedTask={taskId:s}),await this.notification(u,f)},sendRequest:async(u,f,p)=>{const h={...p,relatedRequestId:t.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});const m=h.relatedTask?.taskId??s;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(u,f,h)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,c)).then(async u=>{if(a.signal.aborted)return;const f={result:u,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)},async u=>{if(a.signal.aborted)return;const f={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(u.code)?u.code:ye.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){const{progressToken:r,...n}=t.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}const a=this._responseHandlers.get(o),i=this._timeoutInfo.get(o);if(i&&a&&i.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(l);return}s(n)}_onresponse(t){const r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Hs(t))n(t);else{const a=new fe(t.error.code,t.error.message,t.error.data);n(a)}return}const o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Hs(t)&&t.result&&typeof t.result=="object"){const a=t.result;if(a.task&&typeof a.task=="object"){const i=a.task;typeof i.taskId=="string"&&(s=!0,this._taskProgressTokens.set(i.taskId,r))}}if(s||this._progressHandlers.delete(r),Hs(t))o(t);else{const a=fe.fromError(t.error.code,t.error.message,t.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){const{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(a){yield{type:"error",error:a instanceof fe?a:new fe(ye.InternalError,String(a))}}return}let s;try{const a=await this.request(t,Do,n);if(a.task)s=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new fe(ye.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:i},so(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:i.status==="failed"?yield{type:"error",error:new fe(ye.InternalError,`Task ${s} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new fe(ye.InternalError,`Task ${s} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}const l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(c=>setTimeout(c,l)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof fe?a:new fe(ye.InternalError,String(a))}}}request(t,r,n){const{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a,task:i,relatedTask:l}=n??{};return new Promise((c,u)=>{const f=v=>{u(v)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),i&&this.assertTaskCapability(t.method)}catch(v){f(v);return}n?.signal?.throwIfAborted();const p=this._requestMessageId++,h={...t,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),h.params={...t.params,_meta:{...t.params?._meta||{},progressToken:p}}),i&&(h.params={...h.params,task:i}),l&&(h.params={...h.params,_meta:{...h.params?._meta||{},[oo]:l}});const m=v=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));const y=v instanceof fe?v:new fe(ye.RequestTimeout,String(v));u(y)};this._responseHandlers.set(p,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return u(v);try{const y=Ar(r,v.result);y.success?c(y.data):u(y.error)}catch(y){u(y)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});const _=n?.timeout??KC,g=()=>m(fe.fromError(ye.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(p,_,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);const w=l?.taskId;if(w){const v=y=>{const S=this._responseHandlers.get(p);S?S(y):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,v),this._enqueueTaskMessage(w,{type:"request",message:h,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(p),u(y)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:a}).catch(v=>{this._cleanupTimeout(p),u(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},ou,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},iu,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},dS,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);const n=r?.relatedTask?.taskId;if(n){const i={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[oo]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[oo]:r.relatedTask}}}),this._transport?.send(i,r).catch(l=>this._onerror(l))});return}let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[oo]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(t,r){const n=R0(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{const a=P0(t,o);return Promise.resolve(r(a,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){const n=R0(t);this._notificationHandlers.set(n,o=>{const s=P0(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){const r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){const n=await this._taskMessageQueue.dequeueAll(t,r);for(const o of n)if(o.type==="request"&&Kc(o.message)){const s=o.message.id,a=this._requestResolvers.get(s);a?(a(new fe(ye.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new fe(ye.InvalidRequest,"Request cancelled"));return}const a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),s(new fe(ye.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){const n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{const s=await n.getTask(o,r);if(!s)throw new fe(ye.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,a)=>{await n.storeTaskResult(o,s,a,r);const i=await n.getTask(o,r);if(i){const l=nl.parse({method:"notifications/tasks/status",params:i});await this.notification(l),so(i.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,a)=>{const i=await n.getTask(o,r);if(!i)throw new fe(ye.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(so(i.status))throw new fe(ye.InvalidParams,`Cannot update task "${o}" from terminal status "${i.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,a,r);const l=await n.getTask(o,r);if(l){const c=nl.parse({method:"notifications/tasks/status",params:l});await this.notification(c),so(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}function O0(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function N0(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const a=r[o];O0(a)&&O0(s)?r[o]={...a,...s}:r[o]=s}return r}var dl={exports:{}},Mu={},A0;function YC(){return A0||(A0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(O,q){return{validate:O,compare:q}}e.fullFormats={date:t(s,a),time:t(l(!0),c),"date-time":t(p(!0),h),"iso-time":t(l(),u),"iso-date-time":t(p(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:L,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:"number",validate:T},int64:{type:"number",validate:x},float:{type:"number",validate:R},double:{type:"number",validate:R},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,a),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,h),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function r(O){return O%4===0&&(O%100!==0||O%400===0)}const n=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31];function s(O){const q=n.exec(O);if(!q)return!1;const z=+q[1],H=+q[2],ee=+q[3];return H>=1&&H<=12&&ee>=1&&ee<=(H===2&&r(z)?29:o[H])}function a(O,q){if(O&&q)return O>q?1:O<q?-1:0}const i=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function l(O){return function(z){const H=i.exec(z);if(!H)return!1;const ee=+H[1],re=+H[2],X=+H[3],V=H[4],ie=H[5]==="-"?-1:1,D=+(H[6]||0),E=+(H[7]||0);if(D>23||E>59||O&&!V)return!1;if(ee<=23&&re<=59&&X<60)return!0;const U=re-E*ie,Z=ee-D*ie-(U<0?1:0);return(Z===23||Z===-1)&&(U===59||U===-1)&&X<61}}function c(O,q){if(!(O&&q))return;const z=new Date("2020-01-01T"+O).valueOf(),H=new Date("2020-01-01T"+q).valueOf();if(z&&H)return z-H}function u(O,q){if(!(O&&q))return;const z=i.exec(O),H=i.exec(q);if(z&&H)return O=z[1]+z[2]+z[3],q=H[1]+H[2]+H[3],O>q?1:O<q?-1:0}const f=/t|\s/i;function p(O){const q=l(O);return function(H){const ee=H.split(f);return ee.length===2&&s(ee[0])&&q(ee[1])}}function h(O,q){if(!(O&&q))return;const z=new Date(O).valueOf(),H=new Date(q).valueOf();if(z&&H)return z-H}function m(O,q){if(!(O&&q))return;const[z,H]=O.split(f),[ee,re]=q.split(f),X=a(z,ee);if(X!==void 0)return X||c(H,re)}const _=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function w(O){return _.test(O)&&g.test(O)}const v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(O){return v.lastIndex=0,v.test(O)}const S=-2147483648,b=2**31-1;function T(O){return Number.isInteger(O)&&O<=b&&O>=S}function x(O){return Number.isInteger(O)}function R(){return!0}const C=/[^\\]\\Z/;function L(O){if(C.test(O))return!1;try{return new RegExp(O),!0}catch{return!1}}})(Mu)),Mu}var Ou={},q0;function QC(){return q0||(q0=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;const t=Ih(),r=Ue(),n=r.operators,o={formatMaximum:{okStr:"<=",ok:n.LTE,fail:n.GT},formatMinimum:{okStr:">=",ok:n.GTE,fail:n.LT},formatExclusiveMaximum:{okStr:"<",ok:n.LT,fail:n.GTE},formatExclusiveMinimum:{okStr:">",ok:n.GT,fail:n.LTE}},s={message:({keyword:i,schemaCode:l})=>(0,r.str)`should be ${o[i].okStr} ${l}`,params:({keyword:i,schemaCode:l})=>(0,r._)`{comparison: ${o[i].okStr}, limit: ${l}}`};e.formatLimitDefinition={keyword:Object.keys(o),type:"string",schemaType:"string",$data:!0,error:s,code(i){const{gen:l,data:c,schemaCode:u,keyword:f,it:p}=i,{opts:h,self:m}=p;if(!h.validateFormats)return;const _=new t.KeywordCxt(p,m.RULES.all.format.definition,"format");_.$data?g():w();function g(){const y=l.scopeValue("formats",{ref:m.formats,code:h.code.formats}),S=l.const("fmt",(0,r._)`${y}[${_.schemaCode}]`);i.fail$data((0,r.or)((0,r._)`typeof ${S} != "object"`,(0,r._)`${S} instanceof RegExp`,(0,r._)`typeof ${S}.compare != "function"`,v(S)))}function w(){const y=_.schema,S=m.formats[y];if(!S||S===!0)return;if(typeof S!="object"||S instanceof RegExp||typeof S.compare!="function")throw new Error(`"${f}": format "${y}" does not define "compare" function`);const b=l.scopeValue("formats",{key:y,ref:S,code:h.code.formats?(0,r._)`${h.code.formats}${(0,r.getProperty)(y)}`:void 0});i.fail$data(v(b))}function v(y){return(0,r._)`${y}.compare(${c}, ${u}) ${o[f].fail} 0`}},dependencies:["format"]};const a=i=>(i.addKeyword(e.formatLimitDefinition),i);e.default=a})(Ou)),Ou}var j0;function XC(){return j0||(j0=1,(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});const r=YC(),n=QC(),o=Ue(),s=new o.Name("fullFormats"),a=new o.Name("fastFormats"),i=(c,u={keywords:!0})=>{if(Array.isArray(u))return l(c,u,r.fullFormats,s),c;const[f,p]=u.mode==="fast"?[r.fastFormats,a]:[r.fullFormats,s],h=u.formats||r.formatNames;return l(c,h,f,p),u.keywords&&(0,n.default)(c),c};i.get=(c,u="full")=>{const p=(u==="fast"?r.fastFormats:r.fullFormats)[c];if(!p)throw new Error(`Unknown format "${c}"`);return p};function l(c,u,f,p){var h,m;(h=(m=c.opts.code).formats)!==null&&h!==void 0||(m.formats=(0,o._)`require("ajv-formats/dist/formats").${p}`);for(const _ of u)c.addFormat(_,f[_])}e.exports=t=i,Object.defineProperty(t,"__esModule",{value:!0}),t.default=i})(dl,dl.exports)),dl.exports}var ex=XC();const tx=Wn(ex);function rx(){const e=new $h({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return tx(e),e}class L0{constructor(t){this._ajv=t??rx()}getValidator(t){const r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}class nx{constructor(t){this._client=t}async*callToolStream(t,r=zo,n){const o=this._client,s={...n,task:n?.task??(o.isToolTask(t.name)?{}:void 0)},a=o.requestStream({method:"tools/call",params:t},r,s),i=o.getToolOutputValidator(t.name);for await(const l of a){if(l.type==="result"&&i){const c=l.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new fe(ye.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const u=i(c.structuredContent);if(!u.valid){yield{type:"error",error:new fe(ye.InvalidParams,`Structured content does not match the tool's output schema: ${u.errorMessage}`)};return}}catch(u){if(u instanceof fe){yield{type:"error",error:u};return}yield{type:"error",error:new fe(ye.InvalidParams,`Failed to validate structured content: ${u instanceof Error?u.message:String(u)}`)};return}}yield l}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}}function D0(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break}}function U0(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break}}function pl(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&pl(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&pl(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&pl(r,t)}}function ox(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}class Xs extends M0{constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new L0,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ku,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",wu,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",fu,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new nx(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=N0(this._capabilities,t)}setRequestHandler(t,r){const o=Fo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Nr(o)){const i=o;s=i._zod?.def?.value??i.value}else{const i=o;s=i._def?.value??i.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");const a=s;if(a==="elicitation/create"){const i=async(l,c)=>{const u=Ar(Cu,l);if(!u.success){const v=u.error instanceof Error?u.error.message:String(u.error);throw new fe(ye.InvalidParams,`Invalid elicitation request: ${v}`)}const{params:f}=u.data;f.mode=f.mode??"form";const{supportsFormMode:p,supportsUrlMode:h}=ox(this._capabilities.elicitation);if(f.mode==="form"&&!p)throw new fe(ye.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!h)throw new fe(ye.InvalidParams,"Client does not support URL-mode elicitation requests");const m=await Promise.resolve(r(l,c));if(f.task){const v=Ar(Do,m);if(!v.success){const y=v.error instanceof Error?v.error.message:String(v.error);throw new fe(ye.InvalidParams,`Invalid task creation result: ${y}`)}return v.data}const _=Ar(Ys,m);if(!_.success){const v=_.error instanceof Error?_.error.message:String(_.error);throw new fe(ye.InvalidParams,`Invalid elicitation result: ${v}`)}const g=_.data,w=f.mode==="form"?f.requestedSchema:void 0;if(f.mode==="form"&&g.action==="accept"&&g.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{pl(w,g.content)}catch{}return g};return super.setRequestHandler(t,i)}if(a==="sampling/createMessage"){const i=async(l,c)=>{const u=Ar(Tu,l);if(!u.success){const g=u.error instanceof Error?u.error.message:String(u.error);throw new fe(ye.InvalidParams,`Invalid sampling request: ${g}`)}const{params:f}=u.data,p=await Promise.resolve(r(l,c));if(f.task){const g=Ar(Do,p);if(!g.success){const w=g.error instanceof Error?g.error.message:String(g.error);throw new fe(ye.InvalidParams,`Invalid task creation result: ${w}`)}return g.data}const m=f.tools||f.toolChoice?Su:cl,_=Ar(m,p);if(!_.success){const g=_.error instanceof Error?_.error.message:String(_.error);throw new fe(ye.InvalidParams,`Invalid sampling result: ${g}`)}return _.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{const n=await this.request({method:"initialize",params:{protocolVersion:Fs,capabilities:this._capabilities,clientInfo:this._clientInfo}},Xm,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Bm.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break}}assertTaskCapability(t){D0(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&U0(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Mn,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},m0,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Mn,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},d0,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},u0,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},o0,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},s0,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},a0,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Mn,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Mn,r)}async callTool(t,r=zo,n){if(this.isToolTaskRequired(t.name))throw new fe(ye.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const o=await this.request({method:"tools/call",params:t},r,n),s=this.getToolOutputValidator(t.name);if(s){if(!o.structuredContent&&!o.isError)throw new fe(ye.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(o.structuredContent)try{const a=s(o.structuredContent);if(!a.valid)throw new fe(ye.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof fe?a:new fe(ye.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const r of t){if(r.outputSchema){const o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}const n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){const n=await this.request({method:"tools/list",params:t},f0,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,o){const s=IS.safeParse(n);if(!s.success)throw new Error(`Invalid ${t} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);const{autoRefresh:a,debounceMs:i}=s.data,{onChanged:l}=n,c=async()=>{if(!a){l(null,null);return}try{const f=await o();l(null,f)}catch(f){const p=f instanceof Error?f:new Error(String(f));l(p,null)}},u=()=>{if(i){const f=this._listChangedDebounceTimers.get(t);f&&clearTimeout(f);const p=setTimeout(c,i);this._listChangedDebounceTimers.set(t,p)}else c()};this.setNotificationHandler(r,u)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class z0 extends Error{constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Nu(e){}function Z0(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=Nu,onError:r=Nu,onRetry:n=Nu,onComment:o}=e;let s="",a=!0,i,l="",c="";function u(_){const g=a?_.replace(/^\xEF\xBB\xBF/,""):_,[w,v]=sx(`${s}${g}`);for(const y of w)f(y);s=v,a=!1}function f(_){if(_===""){h();return}if(_.startsWith(":")){o&&o(_.slice(_.startsWith(": ")?2:1));return}const g=_.indexOf(":");if(g!==-1){const w=_.slice(0,g),v=_[g+1]===" "?2:1,y=_.slice(g+v);p(w,y,_);return}p(_,"",_)}function p(_,g,w){switch(_){case"event":c=g;break;case"data":l=`${l}${g}
40
+ `;break;case"id":i=g.includes("\0")?void 0:g;break;case"retry":/^\d+$/.test(g)?n(parseInt(g,10)):r(new z0(`Invalid \`retry\` value: "${g}"`,{type:"invalid-retry",value:g,line:w}));break;default:r(new z0(`Unknown field "${_.length>20?`${_.slice(0,20)}…`:_}"`,{type:"unknown-field",field:_,value:g,line:w}));break}}function h(){l.length>0&&t({id:i,event:c||void 0,data:l.endsWith(`
41
+ `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function m(_={}){s&&_.consume&&f(s),a=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:m}}function sx(e){const t=[];let r="",n=0;for(;n<e.length;){const o=e.indexOf("\r",n),s=e.indexOf(`
42
42
  `,n);let a=-1;if(o!==-1&&s!==-1?a=Math.min(o,s):o!==-1?o===e.length-1?a=-1:a=o:s!==-1&&(a=s),a===-1){r=e.slice(n);break}else{const i=e.slice(n,a);t.push(i),n=a+1,e[n-1]==="\r"&&e[n]===`
43
- `&&n++}}return[t,r]}class U0 extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(z0(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(z0(this),r)}}function YC(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Pu(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Pu).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Pu(e.cause)}`:e.message:`${e}`}function z0(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var Z0=e=>{throw TypeError(e)},Mu=(e,t,r)=>t.has(e)||Z0("Cannot "+r),Le=(e,t,r)=>(Mu(e,t,"read from private field"),r?r.call(e):t.get(e)),It=(e,t,r)=>t.has(e)?Z0("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),ut=(e,t,r,n)=>(Mu(e,t,"write to private field"),t.set(e,r),r),pn=(e,t,r)=>(Mu(e,t,"access private method"),r),tr,ro,qo,ll,cl,Js,Lo,Ks,Rn,jo,Do,Uo,Ys,jr,Nu,Ou,Au,F0,qu,Lu,Qs,ju,Du;class ul extends EventTarget{constructor(t,r){var n,o;super(),It(this,jr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,It(this,tr),It(this,ro),It(this,qo),It(this,ll),It(this,cl),It(this,Js),It(this,Lo),It(this,Ks,null),It(this,Rn),It(this,jo),It(this,Do,null),It(this,Uo,null),It(this,Ys,null),It(this,Ou,async s=>{var a;Le(this,jo).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){pn(this,jr,Qs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?ut(this,qo,new URL(s.url)):ut(this,qo,void 0),c!==200){pn(this,jr,Qs).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){pn(this,jr,Qs).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Le(this,tr)===this.CLOSED)return;ut(this,tr,this.OPEN);const f=new Event("open");if((a=Le(this,Ys))==null||a.call(this,f),this.dispatchEvent(f),typeof i!="object"||!i||!("getReader"in i)){pn(this,jr,Qs).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,h=i.getReader();let m=!0;do{const{done:_,value:y}=await h.read();y&&Le(this,jo).feed(p.decode(y,{stream:!_})),_&&(m=!1,Le(this,jo).reset(),pn(this,jr,ju).call(this))}while(m)}),It(this,Au,s=>{ut(this,Rn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&pn(this,jr,ju).call(this,Pu(s))}),It(this,qu,s=>{typeof s.id=="string"&&ut(this,Ks,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:Le(this,qo)?Le(this,qo).origin:Le(this,ro).origin,lastEventId:s.id||""});Le(this,Uo)&&(!s.event||s.event==="message")&&Le(this,Uo).call(this,a),this.dispatchEvent(a)}),It(this,Lu,s=>{ut(this,Js,s)}),It(this,Du,()=>{ut(this,Lo,void 0),Le(this,tr)===this.CONNECTING&&pn(this,jr,Nu).call(this)});try{if(t instanceof URL)ut(this,ro,t);else if(typeof t=="string")ut(this,ro,new URL(t,QC()));else throw new Error("Invalid URL")}catch{throw YC("An invalid or illegal string was specified")}ut(this,jo,D0({onEvent:Le(this,qu),onRetry:Le(this,Lu)})),ut(this,tr,this.CONNECTING),ut(this,Js,3e3),ut(this,cl,(n=r?.fetch)!=null?n:globalThis.fetch),ut(this,ll,(o=r?.withCredentials)!=null?o:!1),pn(this,jr,Nu).call(this)}get readyState(){return Le(this,tr)}get url(){return Le(this,ro).href}get withCredentials(){return Le(this,ll)}get onerror(){return Le(this,Do)}set onerror(t){ut(this,Do,t)}get onmessage(){return Le(this,Uo)}set onmessage(t){ut(this,Uo,t)}get onopen(){return Le(this,Ys)}set onopen(t){ut(this,Ys,t)}addEventListener(t,r,n){const o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){const o=r;super.removeEventListener(t,o,n)}close(){Le(this,Lo)&&clearTimeout(Le(this,Lo)),Le(this,tr)!==this.CLOSED&&(Le(this,Rn)&&Le(this,Rn).abort(),ut(this,tr,this.CLOSED),ut(this,Rn,void 0))}}tr=new WeakMap,ro=new WeakMap,qo=new WeakMap,ll=new WeakMap,cl=new WeakMap,Js=new WeakMap,Lo=new WeakMap,Ks=new WeakMap,Rn=new WeakMap,jo=new WeakMap,Do=new WeakMap,Uo=new WeakMap,Ys=new WeakMap,jr=new WeakSet,Nu=function(){ut(this,tr,this.CONNECTING),ut(this,Rn,new AbortController),Le(this,cl)(Le(this,ro),pn(this,jr,F0).call(this)).then(Le(this,Ou)).catch(Le(this,Au))},Ou=new WeakMap,Au=new WeakMap,F0=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Le(this,Ks)?{"Last-Event-ID":Le(this,Ks)}:void 0},cache:"no-store",signal:(e=Le(this,Rn))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},qu=new WeakMap,Lu=new WeakMap,Qs=function(e,t){var r;Le(this,tr)!==this.CLOSED&&ut(this,tr,this.CLOSED);const n=new U0("error",{code:t,message:e});(r=Le(this,Do))==null||r.call(this,n),this.dispatchEvent(n)},ju=function(e,t){var r;if(Le(this,tr)===this.CLOSED)return;ut(this,tr,this.CONNECTING);const n=new U0("error",{code:t,message:e});(r=Le(this,Do))==null||r.call(this,n),this.dispatchEvent(n),ut(this,Lo,setTimeout(Le(this,Du),Le(this,Js)))},Du=new WeakMap,ul.CONNECTING=0,ul.OPEN=1,ul.CLOSED=2;function QC(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}function dl(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function V0(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...dl(t.headers),...dl(n.headers)}:t.headers};return e(r,o)}:e}let Uu;Uu=globalThis.crypto;async function XC(e){return(await Uu).getRandomValues(new Uint8Array(e))}async function e6(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await XC(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function t6(e){return await e6(e)}async function r6(e){const t=await(await Uu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function H0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await t6(e),r=await r6(t);return{code_verifier:t,code_challenge:r}}const qt=Wk().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:zm.custom,message:"URL must be parseable",fatal:!0}),jh}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),n6=ft({resource:d().url(),authorization_servers:q(qt).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:ve().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:ve().optional()}),B0=ft({issuer:d(),authorization_endpoint:qt,token_endpoint:qt,registration_endpoint:qt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),service_documentation:qt.optional(),revocation_endpoint:qt.optional(),revocation_endpoint_auth_methods_supported:q(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:q(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:q(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:q(d()).optional(),code_challenge_methods_supported:q(d()).optional(),client_id_metadata_document_supported:ve().optional()}),o6=ft({issuer:d(),authorization_endpoint:qt,token_endpoint:qt,userinfo_endpoint:qt.optional(),jwks_uri:qt,registration_endpoint:qt.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),response_modes_supported:q(d()).optional(),grant_types_supported:q(d()).optional(),acr_values_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),id_token_encryption_alg_values_supported:q(d()).optional(),id_token_encryption_enc_values_supported:q(d()).optional(),userinfo_signing_alg_values_supported:q(d()).optional(),userinfo_encryption_alg_values_supported:q(d()).optional(),userinfo_encryption_enc_values_supported:q(d()).optional(),request_object_signing_alg_values_supported:q(d()).optional(),request_object_encryption_alg_values_supported:q(d()).optional(),request_object_encryption_enc_values_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional(),display_values_supported:q(d()).optional(),claim_types_supported:q(d()).optional(),claims_supported:q(d()).optional(),service_documentation:d().optional(),claims_locales_supported:q(d()).optional(),ui_locales_supported:q(d()).optional(),claims_parameter_supported:ve().optional(),request_parameter_supported:ve().optional(),request_uri_parameter_supported:ve().optional(),require_request_uri_registration:ve().optional(),op_policy_uri:qt.optional(),op_tos_uri:qt.optional(),client_id_metadata_document_supported:ve().optional()}),s6=T({...o6.shape,...B0.pick({code_challenge_methods_supported:!0}).shape}),a6=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Zm().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),i6=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),W0=qt.optional().or(P("").transform(()=>{})),l6=T({redirect_uris:q(qt),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:qt.optional(),logo_uri:W0,scope:d().optional(),contacts:q(d()).optional(),tos_uri:W0,policy_uri:d().optional(),jwks_uri:qt.optional(),jwks:Tt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),c6=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:O().optional(),client_secret_expires_at:O().optional()}).strip(),u6=l6.merge(c6);T({error:d(),error_description:d().optional()}).strip(),T({token:d(),token_type_hint:d().optional()}).strip();function d6(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function p6({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}class $t extends Error{constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class zu extends $t{}zu.errorCode="invalid_request";let pl=class extends $t{};pl.errorCode="invalid_client";let fl=class extends $t{};fl.errorCode="invalid_grant";let hl=class extends $t{};hl.errorCode="unauthorized_client";class Zu extends $t{}Zu.errorCode="unsupported_grant_type";class Fu extends $t{}Fu.errorCode="invalid_scope";class Vu extends $t{}Vu.errorCode="access_denied";let zo=class extends $t{};zo.errorCode="server_error";class Hu extends $t{}Hu.errorCode="temporarily_unavailable";class Bu extends $t{}Bu.errorCode="unsupported_response_type";class Wu extends $t{}Wu.errorCode="unsupported_token_type";class Gu extends $t{}Gu.errorCode="invalid_token";class Ju extends $t{}Ju.errorCode="method_not_allowed";class Ku extends $t{}Ku.errorCode="too_many_requests";class ml extends $t{}ml.errorCode="invalid_client_metadata";class Yu extends $t{}Yu.errorCode="insufficient_scope";class Qu extends $t{}Qu.errorCode="invalid_target";const f6={[zu.errorCode]:zu,[pl.errorCode]:pl,[fl.errorCode]:fl,[hl.errorCode]:hl,[Zu.errorCode]:Zu,[Fu.errorCode]:Fu,[Vu.errorCode]:Vu,[zo.errorCode]:zo,[Hu.errorCode]:Hu,[Bu.errorCode]:Bu,[Wu.errorCode]:Wu,[Gu.errorCode]:Gu,[Ju.errorCode]:Ju,[Ku.errorCode]:Ku,[ml.errorCode]:ml,[Yu.errorCode]:Yu,[Qu.errorCode]:Qu};let Sr=class extends Error{constructor(t){super(t??"Unauthorized")}};function h6(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const Xu="code",ed="S256";function m6(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&h6(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function g6(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":y6(o,s,r);return;case"client_secret_post":v6(o,s,n);return;case"none":_6(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function y6(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function v6(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function _6(e,t){t.set("client_id",e)}async function G0(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=i6.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=f6[o]||zo;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new zo(o)}}async function no(e,t){try{return await td(e,t)}catch(r){if(r instanceof pl||r instanceof hl)return await e.invalidateCredentials?.("all"),await td(e,t);if(r instanceof fl)return await e.invalidateCredentials?.("tokens"),await td(e,t);throw r}}async function td(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await T6(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const l=await b6(t,e,a),c=await x6(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const y=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!w6(w))throw new ml(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(y&&w)u={client_id:w},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const g=await M6(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(g),u=g}}const f=!e.redirectUrl;if(r!==void 0||f){const y=await P6(e,i,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const y=await R6(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof $t)||y instanceof zo))throw y}const h=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:_}=await E6(i,{metadata:c,clientInformation:u,state:h,redirectUrl:e.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(_),await e.redirectToAuthorization(m),"REDIRECT"}function w6(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function b6(e,t,r){const n=d6(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!p6({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 gl(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=rd(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=rd(e,"scope")||void 0,i=rd(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function rd(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function T6(e,t,r=fetch){const n=await C6(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return n6.parse(await n.json())}async function nd(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?nd(e,void 0,r):void 0;throw n}}function k6(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function J0(e,t,r=fetch){return await nd(e,{"MCP-Protocol-Version":t},r)}function S6(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function C6(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??js;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=k6(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await J0(a,s,r);if(!n?.metadataUrl&&S6(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await J0(l,s,r)}return i}function I6(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function x6(e,{fetchFn:t=fetch,protocolVersion:r=js}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=I6(e);for(const{url:s,type:a}of o){const i=await nd(s,n,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?B0.parse(await i.json()):s6.parse(await i.json())}}}async function E6(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Xu))throw new Error(`Incompatible auth server: does not support response type ${Xu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ed))throw new Error(`Incompatible auth server: does not support code challenge method ${ed}`)}else i=new URL("/authorize",e);const l=await H0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",Xu),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",ed),i.searchParams.set("redirect_uri",String(n)),s&&i.searchParams.set("state",s),o&&i.searchParams.set("scope",o),o?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:c}}function $6(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function K0(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,i,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],f=m6(n,u);g6(f,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await G0(c);return a6.parse(await c.json())}async function R6(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await K0(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function P6(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a)),!i){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();i=$6(o,c,e.redirectUrl)}const l=await e.clientInformation();return K0(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function M6(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await G0(s);return u6.parse(await s.json())}class N6 extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Zo{constructor(t,r){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=V0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Sr("No auth provider");let t;try{t=await no(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Sr;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=dl(this._requestInit?.headers);return new Headers({...t,...r})}_startOrAuth(){const t=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new ul(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const i=await t(o,{...s,headers:a});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=gl(i);this._resourceMetadataUrl=l,this._scope=c}return i}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const s=new N6(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{const s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=o=>{const s=o;let a;try{a=dn.parse(JSON.parse(s.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new Sr("No auth provider");if(await no(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Sr("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(t),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){const s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){const{resourceMetadataUrl:a,scope:i}=gl(o);if(this._resourceMetadataUrl=a,this._scope=i,await no(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Sr;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(t){this._protocolVersion=t}}class Fo extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=D0({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}const O6={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Vo extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class Xs{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=V0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??O6}async _authThenStart(){if(!this._authProvider)throw new Sr("No auth provider");let t;try{t=await no(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Sr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=dl(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){const{resumptionToken:r}=t;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Vo(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let a,i=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new Fo({onRetry:h=>{this._serverRetryMs=h}})).getReader();for(;;){const{value:h,done:m}=await u.read();if(m)break;if(h.id&&(a=h.id,i=!0,o?.(h.id)),!!h.data&&(!h.event||h.event==="message"))try{const _=dn.parse(JSON.parse(h.data));Us(_)&&(l=!0,s!==void 0&&(_.id=s)),this.onmessage?.(_)}catch(_){this.onerror?.(_)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(h){this.onerror?.(new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new Sr("No auth provider");if(await no(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Sr("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{const{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Bc(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),l=i.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!i.ok){const p=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Vo(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:h,scope:m}=gl(i);if(this._resourceMetadataUrl=h,this._scope=m,await no(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Sr;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:h,scope:m,error:_}=gl(i);if(_==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Vo(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=y??void 0,await no(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Sr;return this.send(t)}}throw new Vo(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),K4(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const u=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,f=i.headers.get("content-type");if(u)if(f?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:o},!1);else if(f?.includes("application/json")){const p=await i.json(),h=Array.isArray(p)?p.map(m=>dn.parse(m)):[dn.parse(p)];for(const m of h)this.onmessage?.(m)}else throw await i.body?.cancel(),new Vo(-1,`Unexpected content type: ${f}`);else await i.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Vo(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}const A6="mcp";class Y0{constructor(t){this._url=t}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._socket=new WebSocket(this._url,A6),this._socket.onerror=n=>{const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),this.onerror?.(o)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let o;try{o=dn.parse(JSON.parse(n.data))}catch(s){this.onerror?.(s);return}this.onmessage?.(o)}})}async close(){this._socket?.close()}send(t){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(t)),r()})}}const Pn=dr;(function(e,t){const r=dr,n=dr,o=e();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(yl,-118057+3521*-35+-2099*-233);const Q0=()=>{const e=dr,t=dr,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(a,i){return a!==i},r[t(394)]=t(414),r.ktWqD=function(a,i){return a!==i},r[e(424)]=e(391);const n=r,o=n[t(420)].split("|");let s=859*2+-3*-1039+-4835*1;for(;;){switch(o[s++]){case"0":if(n[t(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[t(405)](typeof global,"undefined"))return global;continue;case"3":if(n[t(405)](typeof globalThis,n[e(394)]))return globalThis;continue;case"4":return Function(n[e(424)])()}break}},q6=(e,t,r)=>{const n=dr,o=dr,s={};s.eOzBp=function(i,l){return i!==l},s.ooaJk="undefined",s[n(402)]=function(i,l){return i===l},s[n(421)]="function";const a=s;a[o(389)](typeof window,a.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&a.pTvSc(typeof e[o(423)],a[n(421)])&&e.postMessage(t,r)},L6=(e,t)=>{const r=dr,n=dr,o={};o.nTCfA=function(a,i){return a in i},o[r(390)]="addEventListener",o[r(385)]=function(a,i){return a===i},o[r(409)]="function",o.VaHpd=n(392),o[n(384)]=r(417),o.FPOYW=function(a,i){return a!==i};const s=o;s.nTCfA(s.ogKey,e)&&s[n(385)](typeof e.addEventListener,s[n(409)])?e[n(386)](s.VaHpd,t):s[n(384)]in e&&s[r(398)](typeof e[n(417)],r(414))&&(e.onmessage=t)};class ea{constructor(t){this._port=t}async[Pn(401)](){const t=Pn,r=Pn;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=dn.parse(n.data.message);(o=this.onmessage)==null||o.call(this,i,n[a(412)][a(428)])}catch(i){const l=new Error("MessageChannel failed to parse message: "+i);(s=this[a(383)])==null||s.call(this,l)}},this._port.onmessageerror=n=>{var o;const s=r,a=new Error("MessageChannel transport error: "+JSON[s(415)](n));(o=this.onerror)==null||o.call(this,a)},this[r(422)].start())}async send(t,r){const n={EoBZE:function(o){return o()},leEiG:function(o,s){return o instanceof s},cDUwk:function(o,s){return o(s)}};return new Promise((o,s)=>{var a;const i=dr,l=dr;try{const c={};c[i(404)]=r?.[i(404)];const u={};u[i(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[i(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(a=this.onerror)==null||a.call(this,u),s(u)}})}async close(){var t,r;const n=Pn,o=Pn;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class od extends ea{constructor(t,r=Q0()){const n=Pn,o={lSpBh:function(a,i,l,c){return a(i,l,c)}};super(),this._endpoint=t,this._globalObject=r;const s=new MessageChannel;this._port=s[n(410)],o[n(418)](q6,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}class sd extends ea{constructor(t,r=Q0()){const n=Pn,o=Pn,s={HITdC:function(a,i){return a===i},QdDxM:function(a){return a()},jowPp:function(a,i,l){return a(i,l)}};super(),this[n(397)]=t,this[o(388)]=r,this[o(416)]=new Promise(a=>{const i=n,l={XlglK:function(c,u){return s.HITdC(c,u)},pXlad:function(c){return s.QdDxM(c)}};s[i(427)](L6,this._globalObject,c=>{const u=i,f=i;c[u(412)]&&l.XlglK(c.data[f(396)],this._endpoint)&&(this[u(422)]=c[f(430)][-3036+-1518*-2],l.pXlad(a))})})}async listen(){return this._listen}}function yl(){const e=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return yl=function(){return e},yl()}function dr(e,t){const r=yl();return dr=function(n,o){return n=n-(17227+1*-16844),r[n]},dr(e,t)}const j6=()=>{const e=new MessageChannel;return[new ea(e.port1),new ea(e.port2)]};(function(e,t){const r=rt,n=rt,o=e();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(vl,-411935*1+228107+208149*2);const D6=async(e,t,r)=>{var n;const o=rt,s=rt,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[o(475)]=o(411),a.SoCaE="resources/templates/list",a[s(484)]="resources/read",a[o(461)]="prompts/get",a.srIIC=s(477),a[s(436)]=s(478),a[s(442)]=o(437),a.dEmVs=o(465);const i=a,{id:l,method:c,params:u}=r;let f={};switch(c){case i.VRyiJ:f=await t.listTools(u);break;case i.VkPYu:f=await t.callTool(u);break;case i.fgMSD:f=await t.listResources(u);break;case i[s(466)]:f=await t.listResourceTemplates(u);break;case i.sthgI:f=await t[o(455)](u);break;case s(486):f=await t.subscribeResource(u);break;case o(410):f=await t.unsubscribeResource(u);break;case i[s(461)]:f=await t[s(414)](u);break;case i[o(412)]:f=await t[o(491)](u);break;case i[o(436)]:f=await t[o(478)]();break;case i.kkNqg:f=await t.complete(u);break;case o(464):f=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=f,p.jsonrpc=i[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},U6=async(e,t,r)=>{var n;const o=rt,s=rt,a={};a[o(487)]=s(462),a.ypHTC="ping",a.fPExS=o(465);const i=a,{id:l,method:c,params:u}=r;let f={};switch(c){case"roots/list":const h={};h.method=c,h[s(446)]=u,f=await t[o(469)](h,ku);break;case"sampling/createMessage":const m={};m[o(481)]=c,m[o(446)]=u,f=await t.request(m,ol);break;case i[o(487)]:const _={};_.method=c,_[s(446)]=u,f=await t.request(_,Bs);break;case i.ypHTC:const y={};y.method=c,f=await t.request(y,$n);break}const p={};return p.result=f,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),f};function rt(e,t){const r=vl();return rt=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},rt(e,t)}const z6=(e,t)=>{const r=rt,n=rt,o={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,l,c){return a(i,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(a,i)=>{var l,c,u,f,p;const h=n,m=r,{id:_,method:y}=a;try{o[h(451)](y,o.DhPFX)?await s.call(e,a,i):await o[m(474)](D6,e,t,a)}catch(w){const{code:v,message:g,data:S}=w;try{if(v){const b={};b[m(485)]=v,b[h(422)]=g,b.data=S;const k={};k[m(448)]=b,k.jsonrpc=o[h(417)],k.id=_,await((l=e?.transport)==null?void 0:l[m(460)](k))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(b){(p=(f=e?.transport)==null?void 0:f.onerror)==null||p.call(f,b)}}}},Z6=(e,t)=>{const r=rt,n=rt,o={};o[r(476)]=r(439),o[r(431)]=function(a,i){return a!==i},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async a=>{var i,l;const c=r,u=n,{method:f,params:p}=a;if(f!==s[c(476)]&&(s.QWYMz(f,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](a)}catch(h){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,h)}}},F6=(e,t)=>async r=>{var n,o,s,a,i;const l=rt,c=rt,u={TJhyV:function(f,p,h,m){return f(p,h,m)},MMNTY:l(465)};try{return await u.TJhyV(U6,e,t,r)}catch(f){const{code:p,message:h,data:m}=f;try{if(p){const _={};_.code=p,_[l(422)]=h,_[c(419)]=m;const y={};y[l(448)]=_,y[l(424)]=u.MMNTY,y.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](y))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,f)}catch(_){(i=(a=e?.[l(488)])==null?void 0:a.onerror)==null||i.call(a,_)}}},V6=(e,t)=>async r=>{var n,o,s;const a=rt,i=rt,l={};l.xmcLM=function(p,h){return p!==h},l.xSWLt="notifications/initialized",l[a(420)]=i(453);const c=l,{method:u,params:f}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||f?.[i(490)]))try{const p={...r};p.jsonrpc=a(465),await((n=t?.[a(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function vl(){const e=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return vl=function(){return e},vl()}const H6=(e,t)=>async r=>{var n,o,s,a,i,l;const c=rt,u=rt,f={};f.kSvAZ=c(465);const p=f;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(h){const{code:m,message:_,data:y}=h;try{if(m){const w={};w.code=m,w.message=_,w.data=y;const v={};v.error=w,v[u(424)]=p.kSvAZ,v.id=r.id,await((o=e?.transport)==null?void 0:o.send(v))}else(a=(s=e?.transport)==null?void 0:s[c(480)])==null||a.call(s,h)}catch(w){(l=(i=e?.[c(488)])==null?void 0:i[u(480)])==null||l.call(i,w)}}},ad=()=>{const e=rt,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=rt;if(c){const f=[];for(const p of r)try{f.push(p(l,c))}catch{}for(const p of f)if(t.rgPZO(p,null))return p}else for(const f of r)try{t[u(427)](f,l)}catch{}},o=l=>{const c=rt,u=rt;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=rt,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=rt;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},B6=e=>{const t=rt,r=rt,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)](ad);e._onresponse=o,e[r(438)]=s,e.removeResponseListener=a,e.clearResponseListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(489)](ad);e[t(432)]=o,e[r(473)]=s,e.removeRequestListener=a,e.clearRequestListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n.jsmFN(ad);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},W6=(e,{beforeInit:t,afterInit:r}={})=>{const n=rt,o=rt,s={HucXo:function(i,l){return i===l},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,l){return i(l)},UynHf:function(i,l){return i===l},yCyFn:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),s.HucXo(typeof t,s.HicFO)&&s[n(435)](t),s[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),s.DclXr(B6,e),e[o(438)](i=>{const l=n;e.originalOnResponse[l(440)](e,i)}),s[n(429)](typeof r,s.HicFO)&&s[o(425)](r),e[o(444)](i=>{const l=o,{method:c}=i,u=a[l(483)](c);s[l(467)](typeof u,"function")&&u(i)})},G6=fn;(function(e,t){const r=fn,n=fn,o=e();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(_l,995159+-6*-266138+-1619768);const J6=()=>{const e=fn,t=fn,r={};r.svuxn=function(o,s){return o&s},r.ZUPdr=function(o,s){return o===s},r[e(227)]=function(o,s){return o===s},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[t(227)](typeof crypto,"object")&&crypto[e(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,o=>{const s=e,a=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[s(225)](o,"x")?a:n[s(209)](a,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},K6=e=>{const t=fn,r=fn,n=new Uint8Array(e);return crypto[t(221)](n),Array[r(218)](n,o=>o[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[t(213)]("")},Mn={};Mn[G6(211)]=J6,Mn.randomBytes=K6;function fn(e,t){const r=_l();return fn=function(n,o){return n=n-(-7373+7187*1+395),r[n]},fn(e,t)}function _l(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return _l=function(){return e},_l()}function hn(e,t){const r=wl();return hn=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},hn(e,t)}const Dr=hn,ta=hn;(function(e,t){const r=hn,n=hn,o=e();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(wl,-4*308317+753182*2+658196);const Y6=(e,t)=>{const r=hn,n=hn,o={olCWX:function(l,c,u){return l(c,u)},sfXDX:function(l,c,u){return l(c,u)},ksWFu:function(l,c,u){return l(c,u)}};o[r(283)](z6,e,t),Z6(e,t);const s=o[n(283)](F6,t,e),a=o[n(294)](H6,t,e),i=o[r(277)](V6,t,e);t.addRequestListener(s),t.addResponseListener(a),t[n(287)](i),e.onclose=()=>{const l=r,c=n;t[l(247)](s),t.removeResponseListener(a),t[c(252)](i)}},id=(e,t,r)=>{const n={QhPqi:function(a,i){return a instanceof i},AIICR:"close",Qalmc:function(a,i,l){return a(i,l)}},o=()=>{var a;n.QhPqi(r,Zo)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[hn(295)])==null||i.close()})),n.Qalmc(Y6,e,t)},s={};s.afterInit=o,n.Qalmc(W6,t,s)},X0=(e,t=Mn[Dr(299)]())=>{const r=Dr,n=Dr,o={RVabx:function(u,f,p){return u(f,p)},crCTs:"include"},s={};s["sse-session-id"]=t;const a=s,i={};i["sse-session-id"]=t;const l={};l.headers=i,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,f){const p=r,h=r,m=new Headers(f?.[p(268)]||{});Object.entries(a).forEach(([y,w])=>{m.set(y,w)});const _={...f};return _.headers=m,o[h(279)](fetch,u,_)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,a.Authorization=n(256)+e),c},e2=(e,t=Mn[Dr(299)]())=>{const r=ta,n=Dr,o={};o[r(271)]="include";const s=o,a={};a["stream-session-id"]=t;const i={};i[n(268)]=a,i.credentials=s[r(271)];const l={};l.requestInit=i;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},ld=async(e,t,r)=>{const n=Dr,o=Dr,s={rRtFD:function(i){return i()},ToRAF:function(i,l){return i instanceof l}},a=s[n(276)](r);try{return await e[o(260)](a),a}catch(i){if(s[n(275)](i,Sr)){const l=await t();return await a[n(257)](l),await ld(e,t,r)}else throw i}},t2=(e,t)=>{const r=ta,n=ta,o={};o[r(267)]=function(a,i){return a in i},o.timcZ="waitForOAuthCode",o[r(253)]=function(a,i){return a===i},o.ufiEQ=r(285),o[n(250)]=r(293);const s=o;if(s.oGmBG(s[r(258)],e))return e[n(278)];if(s[n(253)](typeof t,s.ufiEQ))return t;throw new Error(s.daYBw)};function wl(){const e=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return wl=function(){return e},wl()}const Q6=async e=>{const t=ta,r=Dr,n={GKDjq:function(I,j,N){return I(j,N)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(I){return I()},kdowC:function(I,j,N,L){return I(j,N,L)},KkViY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:f}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const h=p,m=i||Mn[r(299)](),_=n[t(289)](X0,a,m);if(c){const I={..._.requestInit,...c};I[r(268)]={..._[r(280)][t(268)],...c.headers},h.requestInit=I}else h.requestInit=_[t(280)];if(u){const I={..._[t(270)],...u};h.eventSourceInit=I}else h.eventSourceInit=_[t(270)];const y={};y[t(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[r(303)]={};const v=w,g={};g.name=n[r(261)],g[t(288)]=n.mcbiU;const S={};S[t(251)]=v;const b=new Gs(g,S),k=()=>new Zo(new URL(s),h);let C=n[t(282)](k);if(l){const I=t2(l,f);C=await n[t(263)](ld,b,I,k)}else await b.connect(C);id(b,o,C),C.sessionId=C[r(274)].searchParams[t(297)](n.KkViY);const R={};return R.transport=C,R.sessionId=C[r(286)],R},X6=async e=>{const t=ta,r=Dr,n={wfHUn:function(I,j,N){return I(j,N)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(I){return I()},PdsSn:function(I,j,N,L){return I(j,N,L)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:f}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const h=p,m=i||Mn.randomUUID(),_=n[r(272)](e2,a,m);if(c){const I={..._[t(280)],...c};I.headers={..._.requestInit[t(268)],...c.headers},h.requestInit=I}else h[r(280)]=_[r(280)];const y={};y[r(254)]=!0;const w={};w.roots=y,w[t(298)]={},w[t(303)]={};const v=w,g={};g.name=n[t(262)],g.version=n.omKPe;const S={};S.capabilities=v;const b=new Gs(g,S),k=()=>new Xs(new URL(s),h);let C=n.rSiEq(k);if(l){const I=n[t(272)](t2,l,f);C=await n[t(296)](ld,b,I,k)}else await b[t(260)](C);n.PdsSn(id,b,o,C);const R={};return R.transport=C,R[r(286)]=C[r(286)],R},eI=async e=>{const t=Dr,r=Dr,n={eZwNI:function(w,v,g,S){return w(v,g,S)}},{client:o,url:s,token:a,sessionId:i}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,f={};f.name="mcp-socket-proxy-client",f.version=r(248);const p={};p[r(251)]=u;const h=new Gs(f,p),m=i||Mn[r(299)](),_=new Y0(new URL(s+"?sessionId="+m+r(265)+a));await h.connect(_),n[t(259)](id,h,o,_);const y={};return y.transport=_,y[r(286)]=m,y},Nn=Ur,ra=Ur;(function(e,t){const r=Ur,n=Ur,o=e();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(bl,1297719+-42747*-22+-1289197);function Ur(e,t){const r=bl();return Ur=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Ur(e,t)}const tI=()=>Mn.randomBytes(-8746+-382*-23);class rI{constructor(t){const r=Ur,n=Ur,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:s,state:a,redirectCallback:i,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=s,this[r(206)]=s.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=a||o.HbwOh(tI),this._redirectCallback=i||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,a,i;const l=Ur,c=Ur,u={};u[l(198)]="GET";const f=await fetch(t,u);!f.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+f[c(205)]));const p=await this[c(195)](this._redirectUrl,this[l(197)]);if(!p.ok){(s=(o=this[l(207)]).reject)==null||s.call(o,"Failed to fetch auth code: "+p[c(205)]);return}const h=await p.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,h.code)}async[Nn(191)](t,r){const n=Nn,o={};o.xAOmI="POST";const s=o,a={};a["Content-Type"]=n(217);const i={};return i.state=r,fetch(t,{method:s.xAOmI,headers:a,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=Ur;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[Nn(206)]}get[ra(190)](){return this._clientMetadata}[Nn(213)](){return this[Nn(197)]}[ra(218)](){return this[ra(200)]}[Nn(194)](t){this._clientInformation=t}tokens(){return this[ra(210)]}saveTokens(t){const r=ra;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[Nn(212)](){const t=Nn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function bl(){const e=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return bl=function(){return e},bl()}(function(e,t){for(var r=kl,n=kl,o=e();;)try{var s=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Tl,262*-2438+1346066*-1+2*1373311);function Tl(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return Tl=function(){return e},Tl()}function kl(e,t){var r=Tl();return kl=function(n,o){n=n-287;var s=r[n];return s},kl(e,t)}class nI{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}}class oI extends $0{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(tl.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{const s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new A0,this.setRequestHandler(Jm,n=>this._oninitialize(n)),this.setNotificationHandler(Kc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(rl,async(n,o)=>{const s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,i=tl.safeParse(a);return i.success&&this._loggingLevels.set(s,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new nI(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=P0(this._capabilities,t)}setRequestHandler(t,r){const o=Ao(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Or(o)){const i=o;s=i._zod?.def?.value??i.value}else{const i=o;s=i._def?.value??i.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){const i=async(l,c)=>{const u=Ar(el,l);if(!u.success){const m=u.error instanceof Error?u.error.message:String(u.error);throw new ce(fe.InvalidParams,`Invalid tools/call request: ${m}`)}const{params:f}=u.data,p=await Promise.resolve(r(l,c));if(f.task){const m=Ar(Po,p);if(!m.success){const _=m.error instanceof Error?m.error.message:String(m.error);throw new ce(fe.InvalidParams,`Invalid task creation result: ${_}`)}return m.data}const h=Ar(No,p);if(!h.success){const m=h.error instanceof Error?h.error.message:String(h.error);throw new ce(fe.InvalidParams,`Invalid tools/call result: ${m}`)}return h.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);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 ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);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 ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);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 ${t})`);break}}assertTaskCapability(t){L0(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&q0(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){const r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:Fm.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"},$n)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){const n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(c=>c.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,i=a?Array.isArray(a.content)?a.content:[a.content]:[],l=i.some(c=>c.type==="tool_use");if(s){if(o.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){const c=new Set(i.filter(f=>f.type==="tool_use").map(f=>f.id)),u=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(c.size!==u.size||![...c].every(f=>u.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},wu,r):this.request({method:"sampling/createMessage",params:t},ol,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const o=t;return this.request({method:"elicitation/create",params:o},Bs,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const o=t.mode==="form"?t:{...t,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Bs,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!i.valid)throw new ce(fe.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(a){throw a instanceof ce?a:new ce(fe.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return s}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},ku,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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 cd=Symbol.for("mcp.completable");function sI(e,t){return Object.defineProperty(e,cd,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function r2(e){return!!e&&typeof e=="object"&&cd in e}function aI(e){return e[cd]?.complete}var n2;(function(e){e.Completable="McpCompletable"})(n2||(n2={}));const o2=1e6,ud=1e6,s2=1e4,iI=1e6;class mn{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,n){if(t.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${t.length})`)}get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}constructor(t){mn.validateLength(t,o2,"Template"),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){const r=[];let n="",o=0,s=0;for(;o<t.length;)if(t[o]==="{"){n&&(r.push(n),n="");const a=t.indexOf("}",o);if(a===-1)throw new Error("Unclosed template expression");if(s++,s>s2)throw new Error(`Template contains too many expressions (max ${s2})`);const i=t.slice(o+1,a),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),f=u[0];for(const p of u)mn.validateLength(p,ud,"Variable name");r.push({name:f,operator:l,names:u,exploded:c}),o=a+1}else n+=t[o],o++;return n&&r.push(n),r}getOperator(t){return["+","#",".","/","?","&"].find(n=>t.startsWith(n))||""}getNames(t){const r=this.getOperator(t);return t.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(t,r){return mn.validateLength(t,ud,"Variable value"),r==="+"||r==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,r){if(t.operator==="?"||t.operator==="&"){const a=t.names.map(l=>{const c=r[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(f=>this.encodeValue(f,t.operator)).join(","):this.encodeValue(c.toString(),t.operator);return`${l}=${u}`}).filter(l=>l.length>0);return a.length===0?"":(t.operator==="?"?"?":"&")+a.join("&")}if(t.names.length>1){const a=t.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[t.name];if(n===void 0)return"";const s=(Array.isArray(n)?n:[n]).map(a=>this.encodeValue(a,t.operator));switch(t.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(t){let r="",n=!1;for(const o of this.parts){if(typeof o=="string"){r+=o;continue}const s=this.expandPart(o,t);s&&((o.operator==="?"||o.operator==="&")&&n?r+=s.replace("?","&"):r+=s,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(t){const r=[];for(const s of t.names)mn.validateLength(s,ud,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let s=0;s<t.names.length;s++){const a=t.names[s],i=s===0?"\\"+t.operator:"&";r.push({pattern:i+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let n;const o=t.name;switch(t.operator){case"":n=t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:o}),r}match(t){mn.validateLength(t,o2,"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+="$",mn.validateLength(r,iI,"Generated regex pattern");const o=new RegExp(r),s=t.match(o);if(!s)return null;const a={};for(let i=0;i<n.length;i++){const{name:l,exploded:c}=n[i],u=s[i+1],f=l.replace("*","");c&&u.includes(",")?a[f]=u.split(","):a[f]=u}return a}}const lI=/^[A-Za-z0-9._-]{1,128}$/;function cI(e){const t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!lI.test(e)){const r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return t.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:t}}return{isValid:!0,warnings:t}}function uI(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const r of t)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 a2(e){const t=cI(e);return uI(e,t.warnings),t.isValid}class dI{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){const o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}class i2{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new oI(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new dI(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(On(yu)),this.server.assertCanSetRequestHandler(On(el)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(yu,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{const n={name:t,title:r.title,description:r.description,inputSchema:(()=>{const o=Ws(r.inputSchema);return o?I0(o,{strictUnions:!0,pipeStrategy:"input"}):fI})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const o=Ws(r.outputSchema);o&&(n.outputSchema=I0(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(el,async(t,r)=>{try{const n=this._registeredTools[t.params.name];if(!n)throw new ce(fe.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new ce(fe.InvalidParams,`Tool ${t.params.name} disabled`);const o=!!t.params.task,s=n.execution?.taskSupport,a="createTask"in n.handler;if((s==="required"||s==="optional")&&!a)throw new ce(fe.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new ce(fe.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&a)return await this.handleAutomaticTaskPolling(n,t,r);const i=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,i,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof ce&&n.code===fe.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;const s=Ws(t.inputSchema)??t.inputSchema,a=await Su(s,r);if(!a.success){const i="error"in a?a.error:"Unknown error",l=Cu(i);throw new ce(fe.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return a.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new ce(fe.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const o=Ws(t.outputSchema),s=await Su(o,r.structuredContent);if(!s.success){const a="error"in s?s.error:"Unknown error",i=Cu(a);throw new ce(fe.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(t,r,n){const o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");const a={...n,taskStore:n.taskStore};if(t.inputSchema){const i=o;return await Promise.resolve(i.createTask(r,a))}else{const i=o;return await Promise.resolve(i.createTask(a))}}if(t.inputSchema){const a=o;return await Promise.resolve(a(r,n))}else{const a=o;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const o=await this.validateToolInput(t,r.params.arguments,r.params.name),s=t.handler,a={...n,taskStore:n.taskStore},i=o?await Promise.resolve(s.createTask(o,a)):await Promise.resolve(s.createTask(a)),l=i.task.taskId;let c=i.task;const u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(p=>setTimeout(p,u));const f=await n.taskStore.getTask(l);if(!f)throw new ce(fe.InternalError,`Task ${l} not found during polling`);c=f}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(On(Tu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Tu,async t=>{switch(t.params.ref.type){case"ref/prompt":return GS(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return JS(t),this.handleResourceCompletion(t,t.params.ref);default:throw new ce(fe.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){const n=this._registeredPrompts[r.name];if(!n)throw new ce(fe.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new ce(fe.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return na;const s=Ao(n.argsSchema)?.[t.params.argument.name];if(!r2(s))return na;const a=aI(s);if(!a)return na;const i=await a(t.params.argument.value,t.params.context);return u2(i)}async handleResourceCompletion(t,r){const n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return na;throw new ce(fe.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}const o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return na;const s=await o(t.params.argument.value,t.params.context);return u2(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(On(Xi)),this.server.assertCanSetRequestHandler(On(au)),this.server.assertCanSetRequestHandler(On(lu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Xi,async(t,r)=>{const n=Object.entries(this._registeredResources).filter(([s,a])=>a.enabled).map(([s,a])=>({uri:s,name:a.name,...a.metadata})),o=[];for(const s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;const a=await s.resourceTemplate.listCallback(r);for(const i of a.resources)o.push({...s.metadata,...i})}return{resources:[...n,...o]}}),this.server.setRequestHandler(au,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(lu,async(t,r)=>{const n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new ce(fe.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(const s of Object.values(this._registeredResourceTemplates)){const a=s.resourceTemplate.uriTemplate.match(n.toString());if(a)return s.readCallback(n,a,r)}throw new ce(fe.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(On(uu)),this.server.assertCanSetRequestHandler(On(du)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(uu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?mI(r.argsSchema):void 0}))})),this.server.setRequestHandler(du,async(t,r)=>{const n=this._registeredPrompts[t.params.name];if(!n)throw new ce(fe.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new ce(fe.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){const o=Ws(n.argsSchema),s=await Su(o,t.params.arguments);if(!s.success){const l="error"in s?s.error:"Unknown error",c=Cu(l);throw new ce(fe.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}const a=s.data,i=n.callback;return await Promise.resolve(i(a,r))}else{const o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());const s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const a=this._createRegisteredResourceTemplate(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const s=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,n,o,s){const a={name:t,title:r,metadata:o,readCallback:s,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(t,r,n,o,s){const a={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=a)),typeof c.title<"u"&&(a.title=c.title),typeof c.template<"u"&&(a.resourceTemplate=c.template),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=a;const i=n.uriTemplate.variableNames;return Array.isArray(i)&&i.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(t,r,n,o,s){const a={title:r,description:n,argsSchema:o===void 0?void 0:Oo(o),callback:s,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!==t&&(delete this._registeredPrompts[t],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=Oo(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=a,o&&Object.values(o).some(l=>{const c=l instanceof Nr?l._def?.innerType:l;return r2(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,r,n,o,s,a,i,l,c){a2(t);const u={title:r,description:n,inputSchema:c2(o),outputSchema:c2(s),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:f=>{typeof f.name<"u"&&f.name!==t&&(typeof f.name=="string"&&a2(f.name),delete this._registeredTools[t],f.name&&(this._registeredTools[f.name]=u)),typeof f.title<"u"&&(u.title=f.title),typeof f.description<"u"&&(u.description=f.description),typeof f.paramsSchema<"u"&&(u.inputSchema=Oo(f.paramsSchema)),typeof f.outputSchema<"u"&&(u.outputSchema=Oo(f.outputSchema)),typeof f.callback<"u"&&(u.handler=f.callback),typeof f.annotations<"u"&&(u.annotations=f.annotations),typeof f._meta<"u"&&(u._meta=f._meta),typeof f.enabled<"u"&&(u.enabled=f.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,s,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const l=r[0];dd(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!dd(r[0])&&(a=r.shift())):typeof l=="object"&&l!==null&&(a=r.shift())}const i=r[0];return this._createRegisteredTool(t,void 0,n,o,s,a,{taskSupport:"forbidden"},void 0,i)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);const{title:o,description:s,inputSchema:a,outputSchema:i,annotations:l,_meta:c}=r;return this._createRegisteredTool(t,o,s,a,i,l,{taskSupport:"forbidden"},c,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());const s=r[0],a=this._createRegisteredPrompt(t,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);const{title:o,description:s,argsSchema:a}=r,i=this._createRegisteredPrompt(t,o,s,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class pI{constructor(t,r){this._callbacks=r,this._uriTemplate=typeof t=="string"?new mn(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}}const fI={type:"object",properties:{}};function l2(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function hI(e){return"_def"in e||"_zod"in e||l2(e)}function dd(e){return typeof e!="object"||e===null||hI(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(l2)}function c2(e){if(e)return dd(e)?Oo(e):e}function mI(e){const t=Ao(e);return t?Object.entries(t).map(([r,n])=>{const o=eC(n),s=tC(n);return{name:r,description:o,required:!s}}):[]}function On(e){const r=Ao(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=g0(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function u2(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const na={completion:{values:[],hasMore:!1}};function gI(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}class oa{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new oa,r=new oa;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(;this._messageQueue.length>0;){const t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){const t=this._otherTransport;this._otherTransport=void 0,await t?.close(),this.onclose?.()}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}class yI{constructor(t,r){const n={name:"web-mcp-server",version:"1.0.0"},o={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new i2(t||n,r||{capabilities:o}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=s=>{this.onerror?.(s)},this.server.server.setRequestHandler(rl,async()=>({}))}async connect(t){return typeof t.start=="function"?(this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new sd(t),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(t,r,n){return this.server.registerTool(t,r,n)}registerPrompt(t,r,n){return this.server.registerPrompt(t,r,n)}registerResource(t,r,n,o){return typeof r=="string"?this.server.registerResource(t,r,n,o):this.server.registerResource(t,r,n,o)}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(t,r){return await this.server.server.createMessage(t,r)}async elicitInput(t,r){return await this.server.server.elicitInput(t,r)}async listRoots(t,r){return await this.server.server.listRoots(t,r)}async sendLoggingMessage(t){return await this.server.server.sendLoggingMessage(t)}async sendResourceUpdated(t){return await this.server.server.sendResourceUpdated(t)}request(t,r,n){return this.server.server.request(t,r,n)}async notification(t,r){return await this.server.server.notification(t,r)}setRequestHandler(t,r){this.server.server.setRequestHandler(t,r)}removeRequestHandler(t){this.server.server.removeRequestHandler(t)}setNotificationHandler(t,r){this.server.server.setNotificationHandler(t,r)}removeNotificationHandler(t){this.server.server.removeNotificationHandler(t)}onSubscribe(t){this.server.server.setRequestHandler(o0,t)}onUnsubscribe(t){this.server.server.setRequestHandler(s0,t)}onSetLogLevel(t){this.server.server.setRequestHandler(rl,t)}onListResources(t){this.server.server.setRequestHandler(Xi,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(h0,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const vI=(e,t)=>new sd(e,t),_I=()=>j6(),wI=e=>e instanceof sd,bI=e=>e instanceof i2;class d2{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Gs(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:s,agent:a,onError:i}=t;if(a===!0){const u={client:this.client,url:r,token:n,sessionId:o};let f;return await(async()=>{const{transport:h,sessionId:m}=s==="sse"?await Q6(u):s==="socket"?await eI(u):await X6(u);h.onerror=async _=>{i?.(_)},f={transport:h,sessionId:m}})(),f}const l=new URL(r);let c;if(s==="channel"&&(c=new od(r),await this.client.connect(c)),s==="sse"){const u=X0(n,o);c=new Zo(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new Y0(new URL(`${r}?sessionId=${o}&token=${n}`)),c.sessionId=o,await this.client.connect(c)),typeof c>"u"){const u=e2(n,o);c=new Xs(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,r){return await this.client.complete(t,r)}async setLoggingLevel(t,r){return await this.client.setLoggingLevel(t,r)}async getPrompt(t,r){return await this.client.getPrompt(t,r)}async listPrompts(t,r){return await this.client.listPrompts(t,r)}async listResources(t,r){return await this.client.listResources(t,r)}async listResourceTemplates(t,r){return await this.client.listResourceTemplates(t,r)}async readResource(t,r){return await this.client.readResource(t,r)}async subscribeResource(t,r){return await this.client.subscribeResource(t,r)}async unsubscribeResource(t,r){return await this.client.unsubscribeResource(t,r)}async callTool(t,r){return await this.client.callTool(t,No,r)}async listTools(t,r){return await this.client.listTools(t,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,r,n){return this.client.request(t,r,n)}async notification(t,r){return await this.client.notification(t,r)}setRequestHandler(t,r){this.client.setRequestHandler(t,r)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,r){this.client.setNotificationHandler(t,r)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(bu,t)}onCreateMessage(t){this.client.setRequestHandler(_u,t)}onListRoots(t){this.client.setRequestHandler(f0,t)}onToolListChanged(t){this.client.setNotificationHandler(vu,t)}onPromptListChanged(t){this.client.setNotificationHandler(gu,t)}onResourceListChanged(t){this.client.setNotificationHandler(cu,t)}onResourceUpdated(t){this.client.setNotificationHandler(a0,t)}onLoggingMessage(t){this.client.setNotificationHandler(d0,t)}async onPagehide(t){t.persisted||(p2(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const TI=(e,t)=>new Zo(e,t),kI=(e,t)=>new Xs(e,t),SI=(e,t)=>new od(e,t),CI=e=>e instanceof Zo,p2=e=>e instanceof Xs,II=e=>e instanceof od,xI=e=>e instanceof Gs,Ho=(e,t,r)=>{window.postMessage({type:e,direction:r,data:t},"*")},EI=(e,t,r)=>{const n=async function(o){o.source===window&&o.data.type===e&&o.data.direction===r&&await t(o.data.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)},pd=(e,t,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:r,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:r,type:e,data:t})},f2=(e,t,r,n)=>{const o=(s,a,i)=>{if(s.type===e&&s.direction===r&&(!n||n&&s.tabId===n)){const{data:l}=s;t(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class h2{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=f2("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=dn.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->bg")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");let n;if(chrome.sessionRegistry){const o=chrome.sessionRegistry.get(this.targetSessionId);o&&o.tabIds.length>0&&(n=o.tabIds[o.tabIds.length-1])}n==null&&(n=await chrome.runtime.sendMessage({type:"get-session-tab-id",sessionId:this.targetSessionId})),this._throwError(()=>n==null,`【Client Transport】后台未找到活动的tabId用于${this.targetSessionId}`),pd("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,mcpMessage:t},"bg->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 fd=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});class $I{constructor(t=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||fd(),this._messageListener2=EI("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=dn.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&Ho("update-page-app-message",{status:"run",message:r.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(t,r){if(t()){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(t,r){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),Ho("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&t.result?.content&&Ho("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{Ho("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...t,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._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(t))}}}class RI{constructor(t=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||fd(),this.tabId=r}_throwError(t,r){if(t()){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】 已关闭,无法重新启动");f2("mcp-client-to-server",t=>{if(!(t.sessionId!==this.sessionId||t.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",t.mcpMessage);const r=dn.parse(t.mcpMessage);this.onmessage?.(r),t.mcpMessage.params?.name&&Ho("update-page-app-message",{status:"run",message:t.mcpMessage.params?.name},"page->content")}catch(r){console.log("【Content Svr Transport】 处理消息时发生错误:",r)}},"bg->content",this.tabId),this._isStarted=!0}}async send(t,r){this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",t),pd("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:t},"content->bg"),"result"in t&&t.result?.content&&Ho("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(t){this._isStarted&&(this._lastRegistration=t,pd("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...t,url:window.location.origin,title:document.title}},"content->bg"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(t))}}}var Bo={},hd,m2;function PI(){return m2||(m2=1,hd=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),hd}var md={},An={},g2;function oo(){if(g2)return An;g2=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return An.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},An.getSymbolTotalCodewords=function(n){return t[n]},An.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},An.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},An.isKanjiModeEnabled=function(){return typeof e<"u"},An.toSJIS=function(n){return e(n)},An}var gd={},y2;function yd(){return y2||(y2=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,o){if(e.isValid(n))return n;try{return t(n)}catch{return o}}})(gd)),gd}var vd,v2;function MI(){if(v2)return vd;v2=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},vd=e,vd}var _d,_2;function NI(){if(_2)return _d;_2=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,o){const s=t*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},_d=e,_d}var wd={},w2;function OI(){return w2||(w2=1,(function(e){const t=oo().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=t(n),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(n){const o=[],s=e.getRowColCoords(n),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(wd)),wd}var bd={},b2;function AI(){if(b2)return bd;b2=1;const e=oo().getSymbolSize,t=7;return bd.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},bd}var Td={},T2;function qI(){return T2||(T2=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,c=null,u=null;for(let f=0;f<s;f++){i=l=0,c=u=null;for(let p=0;p<s;p++){let h=o.get(f,p);h===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=h,i=1),h=o.get(p,f),h===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=h,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const c=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(c===4||c===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let c=0;c<s;c++){i=l=0;for(let u=0;u<s;u++)i=i<<1&2047|o.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function r(n,o,s){switch(n){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,r(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){s(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,i=c)}return i}})(Td)),Td}var Sl={},k2;function S2(){if(k2)return Sl;k2=1;const e=yd(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return Sl.getBlocksCount=function(o,s){switch(s){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},Sl.getTotalCodewordsCount=function(o,s){switch(s){case e.L:return r[(o-1)*4+0];case e.M:return r[(o-1)*4+1];case e.Q:return r[(o-1)*4+2];case e.H:return r[(o-1)*4+3];default:return}},Sl}var kd={},sa={},C2;function LI(){if(C2)return sa;C2=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)e[o]=n,t[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),sa.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},sa.exp=function(n){return e[n]},sa.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},sa}var I2;function jI(){return I2||(I2=1,(function(e){const t=LI();e.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(n[a],o[i]);return s},e.mod=function(n,o){let s=new Uint8Array(n);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}})(kd)),kd}var Sd,x2;function DI(){if(x2)return Sd;x2=1;const e=jI();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const s=e.mod(o,this.genPoly),a=this.degree-s.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(s,a),i}return s},Sd=t,Sd}var Cd={},Id={},xd={},E2;function $2(){return E2||(E2=1,xd.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),xd}var Yr={},R2;function P2(){if(R2)return Yr;R2=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
44
- ]))+`;Yr.KANJI=new RegExp(r,"g"),Yr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Yr.BYTE=new RegExp(n,"g"),Yr.NUMERIC=new RegExp(e,"g"),Yr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Yr.testKanji=function(l){return o.test(l)},Yr.testNumeric=function(l){return s.test(l)},Yr.testAlphanumeric=function(l){return a.test(l)},Yr}var M2;function so(){return M2||(M2=1,(function(e){const t=$2(),r=P2();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return r.testNumeric(s)?e.NUMERIC:r.testAlphanumeric(s)?e.ALPHANUMERIC:r.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function n(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,a){if(e.isValid(s))return s;try{return n(s)}catch{return a}}})(Id)),Id}var N2;function UI(){return N2||(N2=1,(function(e){const t=oo(),r=S2(),n=yd(),o=so(),s=$2(),a=7973,i=t.getBCHDigit(a);function l(p,h,m){for(let _=1;_<=40;_++)if(h<=e.getCapacity(_,m,p))return _}function c(p,h){return o.getCharCountIndicator(p,h)+4}function u(p,h){let m=0;return p.forEach(function(_){const y=c(_.mode,h);m+=y+_.getBitsLength()}),m}function f(p,h){for(let m=1;m<=40;m++)if(u(p,m)<=e.getCapacity(m,h,o.MIXED))return m}e.from=function(h,m){return s.isValid(h)?parseInt(h,10):m},e.getCapacity=function(h,m,_){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof _>"u"&&(_=o.BYTE);const y=t.getSymbolTotalCodewords(h),w=r.getTotalCodewordsCount(h,m),v=(y-w)*8;if(_===o.MIXED)return v;const g=v-c(_,h);switch(_){case o.NUMERIC:return Math.floor(g/10*3);case o.ALPHANUMERIC:return Math.floor(g/11*2);case o.KANJI:return Math.floor(g/13);case o.BYTE:default:return Math.floor(g/8)}},e.getBestVersionForData=function(h,m){let _;const y=n.from(m,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,y);if(h.length===0)return 1;_=h[0]}else _=h;return l(_.mode,_.getLength(),y)},e.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let m=h<<12;for(;t.getBCHDigit(m)-i>=0;)m^=a<<t.getBCHDigit(m)-i;return h<<12|m}})(Cd)),Cd}var Ed={},O2;function zI(){if(O2)return Ed;O2=1;const e=oo(),t=1335,r=21522,n=e.getBCHDigit(t);return Ed.getEncodedBits=function(s,a){const i=s.bit<<3|a;let l=i<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(i<<10|l)^r},Ed}var $d={},Rd,A2;function ZI(){if(A2)return Rd;A2=1;const e=so();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,s,a;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),a=parseInt(s,10),n.put(a,10);const i=this.data.length-o;i>0&&(s=this.data.substr(o),a=parseInt(s,10),n.put(a,i*3+1))},Rd=t,Rd}var Pd,q2;function FI(){if(q2)return Pd;q2=1;const e=so(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let a=t.indexOf(this.data[s])*45;a+=t.indexOf(this.data[s+1]),o.put(a,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},Pd=r,Pd}var Md,L2;function VI(){if(L2)return Md;L2=1;const e=so();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},Md=t,Md}var Nd,j2;function HI(){if(j2)return Nd;j2=1;const e=so(),t=oo();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
45
- Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},Nd=r,Nd}var Od={exports:{}},D2;function BI(){return D2||(D2=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},a={};a[n]=0;var i=t.PriorityQueue.make();i.push(n,0);for(var l,c,u,f,p,h,m,_,y;!i.empty();){l=i.pop(),c=l.value,f=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(h=p[u],m=f+h,_=a[u],y=typeof a[u]>"u",(y||_>m)&&(a[u]=m,i.push(u,m),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Od)),Od.exports}var U2;function WI(){return U2||(U2=1,(function(e){const t=so(),r=ZI(),n=FI(),o=VI(),s=HI(),a=P2(),i=oo(),l=BI();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,v,g){const S=[];let b;for(;(b=w.exec(g))!==null;)S.push({data:b[0],index:b.index,mode:v,length:b[0].length});return S}function f(w){const v=u(a.NUMERIC,t.NUMERIC,w),g=u(a.ALPHANUMERIC,t.ALPHANUMERIC,w);let S,b;return i.isKanjiModeEnabled()?(S=u(a.BYTE,t.BYTE,w),b=u(a.KANJI,t.KANJI,w)):(S=u(a.BYTE_KANJI,t.BYTE,w),b=[]),v.concat(g,S,b).sort(function(C,R){return C.index-R.index}).map(function(C){return{data:C.data,mode:C.mode,length:C.length}})}function p(w,v){switch(v){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return s.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(v,g){const S=v.length-1>=0?v[v.length-1]:null;return S&&S.mode===g.mode?(v[v.length-1].data+=g.data,v):(v.push(g),v)},[])}function m(w){const v=[];for(let g=0;g<w.length;g++){const S=w[g];switch(S.mode){case t.NUMERIC:v.push([S,{data:S.data,mode:t.ALPHANUMERIC,length:S.length},{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.ALPHANUMERIC:v.push([S,{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.KANJI:v.push([S,{data:S.data,mode:t.BYTE,length:c(S.data)}]);break;case t.BYTE:v.push([{data:S.data,mode:t.BYTE,length:c(S.data)}])}}return v}function _(w,v){const g={},S={start:{}};let b=["start"];for(let k=0;k<w.length;k++){const C=w[k],R=[];for(let I=0;I<C.length;I++){const j=C[I],N=""+k+I;R.push(N),g[N]={node:j,lastCount:0},S[N]={};for(let L=0;L<b.length;L++){const z=b[L];g[z]&&g[z].node.mode===j.mode?(S[z][N]=p(g[z].lastCount+j.length,j.mode)-p(g[z].lastCount,j.mode),g[z].lastCount+=j.length):(g[z]&&(g[z].lastCount=j.length),S[z][N]=p(j.length,j.mode)+4+t.getCharCountIndicator(j.mode,v))}}b=R}for(let k=0;k<b.length;k++)S[b[k]].end=0;return{map:S,table:g}}function y(w,v){let g;const S=t.getBestModeForData(w);if(g=t.from(v,S),g!==t.BYTE&&g.bit<S.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(g)+`.
46
- Suggested mode is: `+t.toString(S));switch(g===t.KANJI&&!i.isKanjiModeEnabled()&&(g=t.BYTE),g){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(v){return v.reduce(function(g,S){return typeof S=="string"?g.push(y(S,null)):S.data&&g.push(y(S.data,S.mode)),g},[])},e.fromString=function(v,g){const S=f(v,i.isKanjiModeEnabled()),b=m(S),k=_(b,g),C=l.find_path(k.map,"start","end"),R=[];for(let I=1;I<C.length-1;I++)R.push(k.table[C[I]].node);return e.fromArray(h(R))},e.rawSplit=function(v){return e.fromArray(f(v,i.isKanjiModeEnabled()))}})($d)),$d}var z2;function GI(){if(z2)return md;z2=1;const e=oo(),t=yd(),r=MI(),n=NI(),o=OI(),s=AI(),a=qI(),i=S2(),l=DI(),c=UI(),u=zI(),f=so(),p=WI();function h(k,C){const R=k.size,I=s.getPositions(C);for(let j=0;j<I.length;j++){const N=I[j][0],L=I[j][1];for(let z=-1;z<=7;z++)if(!(N+z<=-1||R<=N+z))for(let H=-1;H<=7;H++)L+H<=-1||R<=L+H||(z>=0&&z<=6&&(H===0||H===6)||H>=0&&H<=6&&(z===0||z===6)||z>=2&&z<=4&&H>=2&&H<=4?k.set(N+z,L+H,!0,!0):k.set(N+z,L+H,!1,!0))}}function m(k){const C=k.size;for(let R=8;R<C-8;R++){const I=R%2===0;k.set(R,6,I,!0),k.set(6,R,I,!0)}}function _(k,C){const R=o.getPositions(C);for(let I=0;I<R.length;I++){const j=R[I][0],N=R[I][1];for(let L=-2;L<=2;L++)for(let z=-2;z<=2;z++)L===-2||L===2||z===-2||z===2||L===0&&z===0?k.set(j+L,N+z,!0,!0):k.set(j+L,N+z,!1,!0)}}function y(k,C){const R=k.size,I=c.getEncodedBits(C);let j,N,L;for(let z=0;z<18;z++)j=Math.floor(z/3),N=z%3+R-8-3,L=(I>>z&1)===1,k.set(j,N,L,!0),k.set(N,j,L,!0)}function w(k,C,R){const I=k.size,j=u.getEncodedBits(C,R);let N,L;for(N=0;N<15;N++)L=(j>>N&1)===1,N<6?k.set(N,8,L,!0):N<8?k.set(N+1,8,L,!0):k.set(I-15+N,8,L,!0),N<8?k.set(8,I-N-1,L,!0):N<9?k.set(8,15-N-1+1,L,!0):k.set(8,15-N-1,L,!0);k.set(I-8,8,1,!0)}function v(k,C){const R=k.size;let I=-1,j=R-1,N=7,L=0;for(let z=R-1;z>0;z-=2)for(z===6&&z--;;){for(let H=0;H<2;H++)if(!k.isReserved(j,z-H)){let ee=!1;L<C.length&&(ee=(C[L]>>>N&1)===1),k.set(j,z-H,ee),N--,N===-1&&(L++,N=7)}if(j+=I,j<0||R<=j){j-=I,I=-I;break}}}function g(k,C,R){const I=new r;R.forEach(function(H){I.put(H.mode.bit,4),I.put(H.getLength(),f.getCharCountIndicator(H.mode,k)),H.write(I)});const j=e.getSymbolTotalCodewords(k),N=i.getTotalCodewordsCount(k,C),L=(j-N)*8;for(I.getLengthInBits()+4<=L&&I.put(0,4);I.getLengthInBits()%8!==0;)I.putBit(0);const z=(L-I.getLengthInBits())/8;for(let H=0;H<z;H++)I.put(H%2?17:236,8);return S(I,k,C)}function S(k,C,R){const I=e.getSymbolTotalCodewords(C),j=i.getTotalCodewordsCount(C,R),N=I-j,L=i.getBlocksCount(C,R),z=I%L,H=L-z,ee=Math.floor(I/L),te=Math.floor(N/L),X=te+1,V=ee-te,se=new l(V);let D=0;const E=new Array(L),U=new Array(L);let Z=0;const x=new Uint8Array(k.buffer);for(let we=0;we<L;we++){const K=we<H?te:X;E[we]=x.slice(D,D+K),U[we]=se.encode(E[we]),D+=K,Z=Math.max(Z,K)}const M=new Uint8Array(I);let W=0,oe,ne;for(oe=0;oe<Z;oe++)for(ne=0;ne<L;ne++)oe<E[ne].length&&(M[W++]=E[ne][oe]);for(oe=0;oe<V;oe++)for(ne=0;ne<L;ne++)M[W++]=U[ne][oe];return M}function b(k,C,R,I){let j;if(Array.isArray(k))j=p.fromArray(k);else if(typeof k=="string"){let ee=C;if(!ee){const te=p.rawSplit(k);ee=c.getBestVersionForData(te,R)}j=p.fromString(k,ee||40)}else throw new Error("Invalid data");const N=c.getBestVersionForData(j,R);if(!N)throw new Error("The amount of data is too big to be stored in a QR Code");if(!C)C=N;else if(C<N)throw new Error(`
43
+ `&&n++}}return[t,r]}class F0 extends Event{constructor(t,r){var n,o;super(t),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,r,n){return n(V0(this),r)}[Symbol.for("Deno.customInspect")](t,r){return t(V0(this),r)}}function ax(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Au(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Au).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Au(e.cause)}`:e.message:`${e}`}function V0(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var H0=e=>{throw TypeError(e)},qu=(e,t,r)=>t.has(e)||H0("Cannot "+r),He=(e,t,r)=>(qu(e,t,"read from private field"),r?r.call(e):t.get(e)),Rt=(e,t,r)=>t.has(e)?H0("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),mt=(e,t,r,n)=>(qu(e,t,"write to private field"),t.set(e,r),r),mn=(e,t,r)=>(qu(e,t,"access private method"),r),or,ao,Vo,fl,hl,ea,Ho,ta,On,Bo,Jo,Wo,ra,Lr,ju,Lu,Du,B0,Uu,zu,na,Zu,Fu;class ml extends EventTarget{constructor(t,r){var n,o;super(),Rt(this,Lr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Rt(this,or),Rt(this,ao),Rt(this,Vo),Rt(this,fl),Rt(this,hl),Rt(this,ea),Rt(this,Ho),Rt(this,ta,null),Rt(this,On),Rt(this,Bo),Rt(this,Jo,null),Rt(this,Wo,null),Rt(this,ra,null),Rt(this,Lu,async s=>{var a;He(this,Bo).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){mn(this,Lr,na).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?mt(this,Vo,new URL(s.url)):mt(this,Vo,void 0),c!==200){mn(this,Lr,na).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){mn(this,Lr,na).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(He(this,or)===this.CLOSED)return;mt(this,or,this.OPEN);const f=new Event("open");if((a=He(this,ra))==null||a.call(this,f),this.dispatchEvent(f),typeof i!="object"||!i||!("getReader"in i)){mn(this,Lr,na).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const p=new TextDecoder,h=i.getReader();let m=!0;do{const{done:_,value:g}=await h.read();g&&He(this,Bo).feed(p.decode(g,{stream:!_})),_&&(m=!1,He(this,Bo).reset(),mn(this,Lr,Zu).call(this))}while(m)}),Rt(this,Du,s=>{mt(this,On,void 0),!(s.name==="AbortError"||s.type==="aborted")&&mn(this,Lr,Zu).call(this,Au(s))}),Rt(this,Uu,s=>{typeof s.id=="string"&&mt(this,ta,s.id);const a=new MessageEvent(s.event||"message",{data:s.data,origin:He(this,Vo)?He(this,Vo).origin:He(this,ao).origin,lastEventId:s.id||""});He(this,Wo)&&(!s.event||s.event==="message")&&He(this,Wo).call(this,a),this.dispatchEvent(a)}),Rt(this,zu,s=>{mt(this,ea,s)}),Rt(this,Fu,()=>{mt(this,Ho,void 0),He(this,or)===this.CONNECTING&&mn(this,Lr,ju).call(this)});try{if(t instanceof URL)mt(this,ao,t);else if(typeof t=="string")mt(this,ao,new URL(t,ix()));else throw new Error("Invalid URL")}catch{throw ax("An invalid or illegal string was specified")}mt(this,Bo,Z0({onEvent:He(this,Uu),onRetry:He(this,zu)})),mt(this,or,this.CONNECTING),mt(this,ea,3e3),mt(this,hl,(n=r?.fetch)!=null?n:globalThis.fetch),mt(this,fl,(o=r?.withCredentials)!=null?o:!1),mn(this,Lr,ju).call(this)}get readyState(){return He(this,or)}get url(){return He(this,ao).href}get withCredentials(){return He(this,fl)}get onerror(){return He(this,Jo)}set onerror(t){mt(this,Jo,t)}get onmessage(){return He(this,Wo)}set onmessage(t){mt(this,Wo,t)}get onopen(){return He(this,ra)}set onopen(t){mt(this,ra,t)}addEventListener(t,r,n){const o=r;super.addEventListener(t,o,n)}removeEventListener(t,r,n){const o=r;super.removeEventListener(t,o,n)}close(){He(this,Ho)&&clearTimeout(He(this,Ho)),He(this,or)!==this.CLOSED&&(He(this,On)&&He(this,On).abort(),mt(this,or,this.CLOSED),mt(this,On,void 0))}}or=new WeakMap,ao=new WeakMap,Vo=new WeakMap,fl=new WeakMap,hl=new WeakMap,ea=new WeakMap,Ho=new WeakMap,ta=new WeakMap,On=new WeakMap,Bo=new WeakMap,Jo=new WeakMap,Wo=new WeakMap,ra=new WeakMap,Lr=new WeakSet,ju=function(){mt(this,or,this.CONNECTING),mt(this,On,new AbortController),He(this,hl)(He(this,ao),mn(this,Lr,B0).call(this)).then(He(this,Lu)).catch(He(this,Du))},Lu=new WeakMap,Du=new WeakMap,B0=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...He(this,ta)?{"Last-Event-ID":He(this,ta)}:void 0},cache:"no-store",signal:(e=He(this,On))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Uu=new WeakMap,zu=new WeakMap,na=function(e,t){var r;He(this,or)!==this.CLOSED&&mt(this,or,this.CLOSED);const n=new F0("error",{code:t,message:e});(r=He(this,Jo))==null||r.call(this,n),this.dispatchEvent(n)},Zu=function(e,t){var r;if(He(this,or)===this.CLOSED)return;mt(this,or,this.CONNECTING);const n=new F0("error",{code:t,message:e});(r=He(this,Jo))==null||r.call(this,n),this.dispatchEvent(n),mt(this,Ho,setTimeout(He(this,Fu),He(this,ea)))},Fu=new WeakMap,ml.CONNECTING=0,ml.OPEN=1,ml.CLOSED=2;function ix(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}function gl(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function J0(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...gl(t.headers),...gl(n.headers)}:t.headers};return e(r,o)}:e}let Vu;Vu=globalThis.crypto;async function lx(e){return(await Vu).getRandomValues(new Uint8Array(e))}async function cx(e){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length;let n="";for(;n.length<e;){const o=await lx(e-n.length);for(const s of o)s<r&&(n+=t[s%t.length])}return n}async function ux(e){return await cx(e)}async function dx(e){const t=await(await Vu).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function W0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await ux(e),r=await dx(t);return{code_verifier:t,code_challenge:r}}const Ut=r4().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Vm.custom,message:"URL must be parseable",fatal:!0}),zh}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),px=vt({resource:d().url(),authorization_servers:j(Ut).optional(),jwks_uri:d().url().optional(),scopes_supported:j(d()).optional(),bearer_methods_supported:j(d()).optional(),resource_signing_alg_values_supported:j(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:Te().optional(),authorization_details_types_supported:j(d()).optional(),dpop_signing_alg_values_supported:j(d()).optional(),dpop_bound_access_tokens_required:Te().optional()}),G0=vt({issuer:d(),authorization_endpoint:Ut,token_endpoint:Ut,registration_endpoint:Ut.optional(),scopes_supported:j(d()).optional(),response_types_supported:j(d()),response_modes_supported:j(d()).optional(),grant_types_supported:j(d()).optional(),token_endpoint_auth_methods_supported:j(d()).optional(),token_endpoint_auth_signing_alg_values_supported:j(d()).optional(),service_documentation:Ut.optional(),revocation_endpoint:Ut.optional(),revocation_endpoint_auth_methods_supported:j(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:j(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:j(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:j(d()).optional(),code_challenge_methods_supported:j(d()).optional(),client_id_metadata_document_supported:Te().optional()}),fx=vt({issuer:d(),authorization_endpoint:Ut,token_endpoint:Ut,userinfo_endpoint:Ut.optional(),jwks_uri:Ut,registration_endpoint:Ut.optional(),scopes_supported:j(d()).optional(),response_types_supported:j(d()),response_modes_supported:j(d()).optional(),grant_types_supported:j(d()).optional(),acr_values_supported:j(d()).optional(),subject_types_supported:j(d()),id_token_signing_alg_values_supported:j(d()),id_token_encryption_alg_values_supported:j(d()).optional(),id_token_encryption_enc_values_supported:j(d()).optional(),userinfo_signing_alg_values_supported:j(d()).optional(),userinfo_encryption_alg_values_supported:j(d()).optional(),userinfo_encryption_enc_values_supported:j(d()).optional(),request_object_signing_alg_values_supported:j(d()).optional(),request_object_encryption_alg_values_supported:j(d()).optional(),request_object_encryption_enc_values_supported:j(d()).optional(),token_endpoint_auth_methods_supported:j(d()).optional(),token_endpoint_auth_signing_alg_values_supported:j(d()).optional(),display_values_supported:j(d()).optional(),claim_types_supported:j(d()).optional(),claims_supported:j(d()).optional(),service_documentation:d().optional(),claims_locales_supported:j(d()).optional(),ui_locales_supported:j(d()).optional(),claims_parameter_supported:Te().optional(),request_parameter_supported:Te().optional(),request_uri_parameter_supported:Te().optional(),require_request_uri_registration:Te().optional(),op_policy_uri:Ut.optional(),op_tos_uri:Ut.optional(),client_id_metadata_document_supported:Te().optional()}),hx=k({...fx.shape,...G0.pick({code_challenge_methods_supported:!0}).shape}),mx=k({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:Hm().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),gx=k({error:d(),error_description:d().optional(),error_uri:d().optional()}),K0=Ut.optional().or(P("").transform(()=>{})),yx=k({redirect_uris:j(Ut),token_endpoint_auth_method:d().optional(),grant_types:j(d()).optional(),response_types:j(d()).optional(),client_name:d().optional(),client_uri:Ut.optional(),logo_uri:K0,scope:d().optional(),contacts:j(d()).optional(),tos_uri:K0,policy_uri:d().optional(),jwks_uri:Ut.optional(),jwks:xt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),vx=k({client_id:d(),client_secret:d().optional(),client_id_issued_at:N().optional(),client_secret_expires_at:N().optional()}).strip(),_x=yx.merge(vx);k({error:d(),error_description:d().optional()}).strip(),k({token:d(),token_type_hint:d().optional()}).strip();function wx(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function bx({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}class Ot extends Error{constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}}class Hu extends Ot{}Hu.errorCode="invalid_request";let yl=class extends Ot{};yl.errorCode="invalid_client";let vl=class extends Ot{};vl.errorCode="invalid_grant";let _l=class extends Ot{};_l.errorCode="unauthorized_client";class Bu extends Ot{}Bu.errorCode="unsupported_grant_type";class Ju extends Ot{}Ju.errorCode="invalid_scope";class Wu extends Ot{}Wu.errorCode="access_denied";let Go=class extends Ot{};Go.errorCode="server_error";class Gu extends Ot{}Gu.errorCode="temporarily_unavailable";class Ku extends Ot{}Ku.errorCode="unsupported_response_type";class Yu extends Ot{}Yu.errorCode="unsupported_token_type";class Qu extends Ot{}Qu.errorCode="invalid_token";class Xu extends Ot{}Xu.errorCode="method_not_allowed";class ed extends Ot{}ed.errorCode="too_many_requests";class wl extends Ot{}wl.errorCode="invalid_client_metadata";class td extends Ot{}td.errorCode="insufficient_scope";class rd extends Ot{}rd.errorCode="invalid_target";const kx={[Hu.errorCode]:Hu,[yl.errorCode]:yl,[vl.errorCode]:vl,[_l.errorCode]:_l,[Bu.errorCode]:Bu,[Ju.errorCode]:Ju,[Wu.errorCode]:Wu,[Go.errorCode]:Go,[Gu.errorCode]:Gu,[Ku.errorCode]:Ku,[Yu.errorCode]:Yu,[Qu.errorCode]:Qu,[Xu.errorCode]:Xu,[ed.errorCode]:ed,[wl.errorCode]:wl,[td.errorCode]:td,[rd.errorCode]:rd};let Cr=class extends Error{constructor(t){super(t??"Unauthorized")}};function Tx(e){return["client_secret_basic","client_secret_post","none"].includes(e)}const nd="code",od="S256";function Sx(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Tx(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function Cx(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":xx(o,s,r);return;case"client_secret_post":Ix(o,s,n);return;case"none":$x(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function xx(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function Ix(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function $x(e,t){t.set("client_id",e)}async function Y0(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=gx.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=kx[o]||Go;return new i(s||"",a)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Go(o)}}async function io(e,t){try{return await sd(e,t)}catch(r){if(r instanceof yl||r instanceof _l)return await e.invalidateCredentials?.("all"),await sd(e,t);if(r instanceof vl)return await e.invalidateCredentials?.("tokens"),await sd(e,t);throw r}}async function sd(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let a,i;try{a=await Px(t,{resourceMetadataUrl:o},s),a.authorization_servers&&a.authorization_servers.length>0&&(i=a.authorization_servers[0])}catch{}i||(i=new URL("/",t));const l=await Rx(t,e,a),c=await qx(i,{fetchFn:s});let u=await Promise.resolve(e.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const g=c?.client_id_metadata_document_supported===!0,w=e.clientMetadataUrl;if(w&&!Ex(w))throw new wl(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${w}`);if(g&&w)u={client_id:w},await e.saveClientInformation?.(u);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const y=await zx(i,{metadata:c,clientMetadata:e.clientMetadata,fetchFn:s});await e.saveClientInformation(y),u=y}}const f=!e.redirectUrl;if(r!==void 0||f){const g=await Ux(e,i,{metadata:c,resource:l,authorizationCode:r,fetchFn:s});return await e.saveTokens(g),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const g=await Dx(i,{metadata:c,clientInformation:u,refreshToken:p.refresh_token,resource:l,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof Ot)||g instanceof Go))throw g}const h=e.state?await e.state():void 0,{authorizationUrl:m,codeVerifier:_}=await jx(i,{metadata:c,clientInformation:u,state:h,redirectUrl:e.redirectUrl,scope:n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,resource:l});return await e.saveCodeVerifier(_),await e.redirectToAuthorization(m),"REDIRECT"}function Ex(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function Rx(e,t,r){const n=wx(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!bx({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 bl(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=ad(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const a=ad(e,"scope")||void 0,i=ad(e,"error")||void 0;return{resourceMetadataUrl:s,scope:a,error:i}}function ad(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function Px(e,t,r=fetch){const n=await Nx(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return px.parse(await n.json())}async function id(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?id(e,void 0,r):void 0;throw n}}function Mx(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Q0(e,t,r=fetch){return await id(e,{"MCP-Protocol-Version":t},r)}function Ox(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function Nx(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??Fs;let a;if(n?.metadataUrl)a=new URL(n.metadataUrl);else{const l=Mx(t,o.pathname);a=new URL(l,n?.metadataServerUrl??o),a.search=o.search}let i=await Q0(a,s,r);if(!n?.metadataUrl&&Ox(i,o.pathname)){const l=new URL(`/.well-known/${t}`,o);i=await Q0(l,s,r)}return i}function Ax(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function qx(e,{fetchFn:t=fetch,protocolVersion:r=Fs}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=Ax(e);for(const{url:s,type:a}of o){const i=await id(s,n,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return a==="oauth"?G0.parse(await i.json()):hx.parse(await i.json())}}}async function jx(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){let i;if(t){if(i=new URL(t.authorization_endpoint),!t.response_types_supported.includes(nd))throw new Error(`Incompatible auth server: does not support response type ${nd}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(od))throw new Error(`Incompatible auth server: does not support code challenge method ${od}`)}else i=new URL("/authorize",e);const l=await W0(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",nd),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",od),i.searchParams.set("redirect_uri",String(n)),s&&i.searchParams.set("state",s),o&&i.searchParams.set("scope",o),o?.includes("offline_access")&&i.searchParams.append("prompt","consent"),a&&i.searchParams.set("resource",a.href),{authorizationUrl:i,codeVerifier:c}}function Lx(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function X0(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:a}){const i=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,i,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],f=Sx(n,u);Cx(f,n,l,r)}const c=await(a??fetch)(i,{method:"POST",headers:l,body:r});if(!c.ok)throw await Y0(c);return mx.parse(await c.json())}async function Dx(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){const i=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await X0(e,{metadata:t,tokenRequestParams:i,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:a});return{refresh_token:n,...l}}async function Ux(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const a=e.clientMetadata.scope;let i;if(e.prepareTokenRequest&&(i=await e.prepareTokenRequest(a)),!i){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();i=Lx(o,c,e.redirectUrl)}const l=await e.clientInformation();return X0(t,{metadata:r,tokenRequestParams:i,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function zx(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Y0(s);return _x.parse(await s.json())}class Zx extends Error{constructor(t,r,n){super(`SSE error: ${r}`),this.code=t,this.event=n}}class Ko{constructor(t,r){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=J0(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Cr("No auth provider");let t;try{t=await io(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Cr;return await this._startOrAuth()}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=gl(this._requestInit?.headers);return new Headers({...t,...r})}_startOrAuth(){const t=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new ml(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{const a=await this._commonHeaders();a.set("Accept","text/event-stream");const i=await t(o,{...s,headers:a});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:l,scope:c}=bl(i);this._resourceMetadataUrl=l,this._scope=c}return i}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}const s=new Zx(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{const s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){n(a),this.onerror?.(a),this.close();return}r()}),this._eventSource.onmessage=o=>{const s=o;let a;try{a=hn.parse(JSON.parse(s.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(a)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new Cr("No auth provider");if(await io(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Cr("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(t){if(!this._endpoint)throw new Error("Not connected");try{const r=await this._commonHeaders();r.set("content-type","application/json");const n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(t),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){const s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){const{resourceMetadataUrl:a,scope:i}=bl(o);if(this._resourceMetadataUrl=a,this._scope=i,await io(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Cr;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(t){this._protocolVersion=t}}class Yo extends TransformStream{constructor({onError:t,onRetry:r,onComment:n}={}){let o;super({start(s){o=Z0({onEvent:a=>{s.enqueue(a)},onError(a){t==="terminate"?s.error(a):typeof t=="function"&&t(a)},onRetry:r,onComment:n})},transform(s){o.feed(s)}})}}const Fx={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Qo extends Error{constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}}class oa{constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=J0(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Fx}async _authThenStart(){if(!this._authProvider)throw new Cr("No auth provider");let t;try{t=await io(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Cr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const t={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);const r=gl(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){const{resumptionToken:r}=t;try{const n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);const o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new Qo(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),o)}_scheduleReconnection(t,r=0){const n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,r+1)})},o)}_handleSseStream(t,r,n){if(!t)return;const{onresumptiontoken:o,replayMessageId:s}=r;let a,i=!1,l=!1;(async()=>{try{const u=t.pipeThrough(new TextDecoderStream).pipeThrough(new Yo({onRetry:h=>{this._serverRetryMs=h}})).getReader();for(;;){const{value:h,done:m}=await u.read();if(m)break;if(h.id&&(a=h.id,i=!0,o?.(h.id)),!!h.data&&(!h.event||h.event==="message"))try{const _=hn.parse(JSON.parse(h.data));Hs(_)&&(l=!0,s!==void 0&&(_.id=s)),this.onmessage?.(_)}catch(_){this.onerror?.(_)}}(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(u){if(this.onerror?.(new Error(`SSE stream disconnected: ${u}`)),(n||i)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:s},0)}catch(h){this.onerror?.(new Error(`Failed to reconnect: ${h instanceof Error?h.message:String(h)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new Cr("No auth provider");if(await io(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Cr("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{const{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Kc(t)?t.id:void 0}).catch(p=>this.onerror?.(p));return}const s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");const a={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,a),l=i.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!i.ok){const p=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Qo(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:h,scope:m}=bl(i);if(this._resourceMetadataUrl=h,this._scope=m,await io(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Cr;return this._hasCompletedAuthFlow=!0,this.send(t)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:h,scope:m,error:_}=bl(i);if(_==="insufficient_scope"){const g=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Qo(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=g??void 0,await io(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Cr;return this.send(t)}}throw new Qo(i.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),sS(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}const u=(Array.isArray(t)?t:[t]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,f=i.headers.get("content-type");if(u)if(f?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:o},!1);else if(f?.includes("application/json")){const p=await i.json(),h=Array.isArray(p)?p.map(m=>hn.parse(m)):[hn.parse(p)];for(const m of h)this.onmessage?.(m)}else throw await i.body?.cancel(),new Qo(-1,`Unexpected content type: ${f}`);else await i.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Qo(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}}const Vx="mcp";class e2{constructor(t){this._url=t}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((t,r)=>{this._socket=new WebSocket(this._url,Vx),this._socket.onerror=n=>{const o="error"in n?n.error:new Error(`WebSocket error: ${JSON.stringify(n)}`);r(o),this.onerror?.(o)},this._socket.onopen=()=>{t()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=n=>{let o;try{o=hn.parse(JSON.parse(n.data))}catch(s){this.onerror?.(s);return}this.onmessage?.(o)}})}async close(){this._socket?.close()}send(t){return new Promise((r,n)=>{if(!this._socket){n(new Error("Not connected"));return}this._socket?.send(JSON.stringify(t)),r()})}}const Nn=fr;(function(e,t){const r=fr,n=fr,o=e();for(;;)try{if(parseInt(r(403))/1+-parseInt(r(411))/2*(-parseInt(n(406))/3)+-parseInt(n(425))/4*(parseInt(r(387))/5)+-parseInt(n(426))/6+parseInt(n(395))/7*(-parseInt(r(419))/8)+-parseInt(r(413))/9+parseInt(n(400))/10===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(kl,-118057+3521*-35+-2099*-233);const t2=()=>{const e=fr,t=fr,r={};r[e(420)]="3|0|2|1|4",r.vQYJZ=function(a,i){return a!==i},r[t(394)]=t(414),r.ktWqD=function(a,i){return a!==i},r[e(424)]=e(391);const n=r,o=n[t(420)].split("|");let s=859*2+-3*-1039+-4835*1;for(;;){switch(o[s++]){case"0":if(n[t(407)](typeof window,"undefined"))return window;continue;case"1":if(n.vQYJZ(typeof self,n.NZmUq))return self;continue;case"2":if(n[t(405)](typeof global,"undefined"))return global;continue;case"3":if(n[t(405)](typeof globalThis,n[e(394)]))return globalThis;continue;case"4":return Function(n[e(424)])()}break}},Hx=(e,t,r)=>{const n=fr,o=fr,s={};s.eOzBp=function(i,l){return i!==l},s.ooaJk="undefined",s[n(402)]=function(i,l){return i===l},s[n(421)]="function";const a=s;a[o(389)](typeof window,a.ooaJk)?e[o(423)](t,"*",r):n(423)in e&&a.pTvSc(typeof e[o(423)],a[n(421)])&&e.postMessage(t,r)},Bx=(e,t)=>{const r=fr,n=fr,o={};o.nTCfA=function(a,i){return a in i},o[r(390)]="addEventListener",o[r(385)]=function(a,i){return a===i},o[r(409)]="function",o.VaHpd=n(392),o[n(384)]=r(417),o.FPOYW=function(a,i){return a!==i};const s=o;s.nTCfA(s.ogKey,e)&&s[n(385)](typeof e.addEventListener,s[n(409)])?e[n(386)](s.VaHpd,t):s[n(384)]in e&&s[r(398)](typeof e[n(417)],r(414))&&(e.onmessage=t)};class sa{constructor(t){this._port=t}async[Nn(401)](){const t=Nn,r=Nn;this[t(422)]&&(this[r(422)].onmessage=n=>{var o,s;const a=t;try{const i=hn.parse(n.data.message);(o=this.onmessage)==null||o.call(this,i,n[a(412)][a(428)])}catch(i){const l=new Error("MessageChannel failed to parse message: "+i);(s=this[a(383)])==null||s.call(this,l)}},this._port.onmessageerror=n=>{var o;const s=r,a=new Error("MessageChannel transport error: "+JSON[s(415)](n));(o=this.onerror)==null||o.call(this,a)},this[r(422)].start())}async send(t,r){const n={EoBZE:function(o){return o()},leEiG:function(o,s){return o instanceof s},cDUwk:function(o,s){return o(s)}};return new Promise((o,s)=>{var a;const i=fr,l=fr;try{const c={};c[i(404)]=r?.[i(404)];const u={};u[i(392)]=t,u.extra=c,this._port&&this._port[l(423)](u),n[i(399)](o)}catch(c){const u=n.leEiG(c,Error)?c:new Error(n.cDUwk(String,c));(a=this.onerror)==null||a.call(this,u),s(u)}})}async close(){var t,r;const n=Nn,o=Nn;(t=this._port)==null||t[n(393)](),this[n(422)]=void 0,(r=this[o(408)])==null||r.call(this)}}class ld extends sa{constructor(t,r=t2()){const n=Nn,o={lSpBh:function(a,i,l,c){return a(i,l,c)}};super(),this._endpoint=t,this._globalObject=r;const s=new MessageChannel;this._port=s[n(410)],o[n(418)](Hx,this._globalObject,{endpoint:this[n(397)]},[s[n(429)]])}}class cd extends sa{constructor(t,r=t2()){const n=Nn,o=Nn,s={HITdC:function(a,i){return a===i},QdDxM:function(a){return a()},jowPp:function(a,i,l){return a(i,l)}};super(),this[n(397)]=t,this[o(388)]=r,this[o(416)]=new Promise(a=>{const i=n,l={XlglK:function(c,u){return s.HITdC(c,u)},pXlad:function(c){return s.QdDxM(c)}};s[i(427)](Bx,this._globalObject,c=>{const u=i,f=i;c[u(412)]&&l.XlglK(c.data[f(396)],this._endpoint)&&(this[u(422)]=c[f(430)][-3036+-1518*-2],l.pXlad(a))})})}async listen(){return this._listen}}function kl(){const e=["message","close","NZmUq","177464iLQCGm","endpoint","_endpoint","FPOYW","EoBZE","3022630ngzRBs","start","pTvSc","272809yMhhPJ","authInfo","ktWqD","21849KofsKk","vQYJZ","onclose","mkHJS","port1","22dUTKmE","data","608229RXNlUs","undefined","stringify","_listen","onmessage","lSpBh","8FmlYyF","XwdDB","cHbAW","_port","postMessage","kFtNB","72572mbPnfL","689424jqaGZE","jowPp","extra","port2","ports","onerror","Fzdib","mkuHv","addEventListener","55juYkZZ","_globalObject","eOzBp","ogKey","return this"];return kl=function(){return e},kl()}function fr(e,t){const r=kl();return fr=function(n,o){return n=n-(17227+1*-16844),r[n]},fr(e,t)}const Jx=()=>{const e=new MessageChannel;return[new sa(e.port1),new sa(e.port2)]};(function(e,t){const r=ct,n=ct,o=e();for(;;)try{if(parseInt(r(452))/1*(parseInt(n(441))/2)+parseInt(n(434))/3*(-parseInt(n(418))/4)+parseInt(r(459))/5+parseInt(r(482))/6*(-parseInt(r(479))/7)+-parseInt(r(458))/8*(parseInt(r(457))/9)+-parseInt(n(416))/10+-parseInt(r(450))/11*(-parseInt(r(433))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Tl,-411935*1+228107+208149*2);const Wx=async(e,t,r)=>{var n;const o=ct,s=ct,a={};a.VRyiJ="tools/list",a.VkPYu="tools/call",a[o(475)]=o(411),a.SoCaE="resources/templates/list",a[s(484)]="resources/read",a[o(461)]="prompts/get",a.srIIC=s(477),a[s(436)]=s(478),a[s(442)]=o(437),a.dEmVs=o(465);const i=a,{id:l,method:c,params:u}=r;let f={};switch(c){case i.VRyiJ:f=await t.listTools(u);break;case i.VkPYu:f=await t.callTool(u);break;case i.fgMSD:f=await t.listResources(u);break;case i[s(466)]:f=await t.listResourceTemplates(u);break;case i.sthgI:f=await t[o(455)](u);break;case s(486):f=await t.subscribeResource(u);break;case o(410):f=await t.unsubscribeResource(u);break;case i[s(461)]:f=await t[s(414)](u);break;case i[o(412)]:f=await t[o(491)](u);break;case i[o(436)]:f=await t[o(478)]();break;case i.kkNqg:f=await t.complete(u);break;case o(464):f=await t.setLoggingLevel(u?.[s(443)]);break}const p={};p.result=f,p.jsonrpc=i[s(472)],p.id=l,await((n=e?.[s(488)])==null?void 0:n[o(460)](p))},Gx=async(e,t,r)=>{var n;const o=ct,s=ct,a={};a[o(487)]=s(462),a.ypHTC="ping",a.fPExS=o(465);const i=a,{id:l,method:c,params:u}=r;let f={};switch(c){case"roots/list":const h={};h.method=c,h[s(446)]=u,f=await t[o(469)](h,Iu);break;case"sampling/createMessage":const m={};m[o(481)]=c,m[o(446)]=u,f=await t.request(m,cl);break;case i[o(487)]:const _={};_.method=c,_[s(446)]=u,f=await t.request(_,Ys);break;case i.ypHTC:const g={};g.method=c,f=await t.request(g,Mn);break}const p={};return p.result=f,p.jsonrpc=i.fPExS,p.id=l,await((n=e?.transport)==null?void 0:n.send(p)),f};function ct(e,t){const r=Tl();return ct=function(n,o){return n=n-(-8023+4*-2344+-17809*-1),r[n]},ct(e,t)}const Kx=(e,t)=>{const r=ct,n=ct,o={vYlhn:function(a,i){return a===i},DhPFX:r(470),NYVNC:function(a,i,l,c){return a(i,l,c)},yfZbw:"2.0"},s=e._onrequest;e[n(463)]=async(a,i)=>{var l,c,u,f,p;const h=n,m=r,{id:_,method:g}=a;try{o[h(451)](g,o.DhPFX)?await s.call(e,a,i):await o[m(474)](Wx,e,t,a)}catch(w){const{code:v,message:y,data:S}=w;try{if(v){const b={};b[m(485)]=v,b[h(422)]=y,b.data=S;const T={};T[m(448)]=b,T.jsonrpc=o[h(417)],T.id=_,await((l=e?.transport)==null?void 0:l[m(460)](T))}else(u=(c=e?.transport)==null?void 0:c.onerror)==null||u.call(c,w)}catch(b){(p=(f=e?.transport)==null?void 0:f.onerror)==null||p.call(f,b)}}}},Yx=(e,t)=>{const r=ct,n=ct,o={};o[r(476)]=r(439),o[r(431)]=function(a,i){return a!==i},o.UPdQt="notifications/cancelled";const s=o;e[r(421)]=async a=>{var i,l;const c=r,u=n,{method:f,params:p}=a;if(f!==s[c(476)]&&(s.QWYMz(f,s.UPdQt)||p?.[u(490)]))try{await t[c(445)](a)}catch(h){(l=(i=e?.[c(488)])==null?void 0:i[c(480)])==null||l.call(i,h)}}},Qx=(e,t)=>async r=>{var n,o,s,a,i;const l=ct,c=ct,u={TJhyV:function(f,p,h,m){return f(p,h,m)},MMNTY:l(465)};try{return await u.TJhyV(Gx,e,t,r)}catch(f){const{code:p,message:h,data:m}=f;try{if(p){const _={};_.code=p,_[l(422)]=h,_[c(419)]=m;const g={};g[l(448)]=_,g[l(424)]=u.MMNTY,g.id=r.id,await((n=e?.transport)==null?void 0:n[c(460)](g))}else(s=(o=e?.transport)==null?void 0:o[l(480)])==null||s.call(o,f)}catch(_){(i=(a=e?.[l(488)])==null?void 0:a.onerror)==null||i.call(a,_)}}},Xx=(e,t)=>async r=>{var n,o,s;const a=ct,i=ct,l={};l.xmcLM=function(p,h){return p!==h},l.xSWLt="notifications/initialized",l[a(420)]=i(453);const c=l,{method:u,params:f}=r;if(c.xmcLM(u,c.xSWLt)&&(c.xmcLM(u,c[i(420)])||f?.[i(490)]))try{const p={...r};p.jsonrpc=a(465),await((n=t?.[a(488)])==null?void 0:n.send(p))}catch(p){(s=(o=e?.transport)==null?void 0:o.onerror)==null||s.call(o,p)}};function Tl(){const e=["JMaxV","cNneM","completion/complete","addResponseListener","notifications/initialized","call","570686biwZQB","kkNqg","level","addNotificationListener","notification","params","addListener","error","_onresponse","164054EGcqjc","vYlhn","1PDRdga","notifications/cancelled","_requestHandlers","readResource","FjTAY","1782ueLDLp","4496TJFZWc","1767765yPcVQJ","send","HefvS","elicitation/create","_onrequest","logging/setLevel","2.0","SoCaE","HucXo","function","request","initialize","push","dEmVs","addRequestListener","NYVNC","fgMSD","CSjwA","prompts/list","ping","35pZrnNj","onerror","method","238086YifXhM","get","sthgI","code","resources/subscribe","sttJM","transport","jsmFN","forward","listPrompts","resources/unsubscribe","resources/list","srIIC","originalOnResponse","getPrompt","indexOf","3653560KcjkMk","yfZbw","4SAWlvk","data","rCDHw","_onnotification","message","UlqiY","jsonrpc","yCyFn","clearNotificationListener","VWsxO","name","UynHf","length","QWYMz","fallbackRequestHandler","492jTClKn","1028589HsbHVQ"];return Tl=function(){return e},Tl()}const eI=(e,t)=>async r=>{var n,o,s,a,i,l;const c=ct,u=ct,f={};f.kSvAZ=c(465);const p=f;try{await((n=t?.[u(488)])==null?void 0:n[u(460)](r))}catch(h){const{code:m,message:_,data:g}=h;try{if(m){const w={};w.code=m,w.message=_,w.data=g;const v={};v.error=w,v[u(424)]=p.kSvAZ,v.id=r.id,await((o=e?.transport)==null?void 0:o.send(v))}else(a=(s=e?.transport)==null?void 0:s[c(480)])==null||a.call(s,h)}catch(w){(l=(i=e?.[c(488)])==null?void 0:i[u(480)])==null||l.call(i,w)}}},ud=()=>{const e=ct,t={rgPZO:function(l,c){return l!==c},VWsxO:function(l,c){return l(c)},FjTAY:"function"},r=[],n=(l,c)=>{const u=ct;if(c){const f=[];for(const p of r)try{f.push(p(l,c))}catch{}for(const p of f)if(t.rgPZO(p,null))return p}else for(const f of r)try{t[u(427)](f,l)}catch{}},o=l=>{const c=ct,u=ct;typeof l===t[c(456)]&&!r.includes(l)&&r[u(471)](l)},s=l=>{const c=ct,u=r[c(415)](l);u!==-1&&r.splice(u,-17591+6*2932)},a=()=>{const l=ct;r[l(430)]=-505*7+1322+2213},i={};return i.handleListener=n,i[e(447)]=o,i.removeListener=s,i.clearListener=a,i},tI=e=>{const t=ct,r=ct,n={UlqiY:function(o){return o()},jsmFN:function(o){return o()}};{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(423)](ud);e._onresponse=o,e[r(438)]=s,e.removeResponseListener=a,e.clearResponseListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n[t(489)](ud);e[t(432)]=o,e[r(473)]=s,e.removeRequestListener=a,e.clearRequestListener=i}{const{handleListener:o,addListener:s,removeListener:a,clearListener:i}=n.jsmFN(ud);e.fallbackNotificationHandler=o,e[t(444)]=s,e.removeNotificationListener=a,e[r(426)]=i}},rI=(e,{beforeInit:t,afterInit:r}={})=>{const n=ct,o=ct,s={HucXo:function(i,l){return i===l},HicFO:n(468),JMaxV:function(i){return i()},DclXr:function(i,l){return i(l)},UynHf:function(i,l){return i===l},yCyFn:function(i){return i()}},a=new Map(e._notificationHandlers);e[n(454)].clear(),e._notificationHandlers.clear(),s.HucXo(typeof t,s.HicFO)&&s[n(435)](t),s[n(467)](e[n(449)][o(428)],n(449))&&(e[o(413)]=e[o(449)]),s.DclXr(tI,e),e[o(438)](i=>{const l=n;e.originalOnResponse[l(440)](e,i)}),s[n(429)](typeof r,s.HicFO)&&s[o(425)](r),e[o(444)](i=>{const l=o,{method:c}=i,u=a[l(483)](c);s[l(467)](typeof u,"function")&&u(i)})},nI=gn;(function(e,t){const r=gn,n=gn,o=e();for(;;)try{if(parseInt(r(215))/1*(-parseInt(n(217))/2)+parseInt(r(216))/3+parseInt(r(210))/4*(parseInt(n(223))/5)+-parseInt(n(214))/6*(parseInt(n(220))/7)+parseInt(n(212))/8*(parseInt(r(228))/9)+parseInt(r(219))/10+parseInt(r(222))/11*(parseInt(r(224))/12)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Sl,995159+-6*-266138+-1619768);const oI=()=>{const e=gn,t=gn,r={};r.svuxn=function(o,s){return o&s},r.ZUPdr=function(o,s){return o===s},r[e(227)]=function(o,s){return o===s},r.SpRzi="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const n=r;return n[t(227)](typeof crypto,"object")&&crypto[e(211)]?crypto.randomUUID():n.SpRzi.replace(/[xy]/g,o=>{const s=e,a=n.svuxn(crypto.getRandomValues(new Uint8Array(-3798+8571*-1+12370))[0],-8324+8339*1);return(n[s(225)](o,"x")?a:n[s(209)](a,-12998+-1*-13001)|813*10+-3707+883*-5).toString(-1*-1851+6493+-8328)})},sI=e=>{const t=gn,r=gn,n=new Uint8Array(e);return crypto[t(221)](n),Array[r(218)](n,o=>o[r(226)](11424+4*-2852).padStart(8950+2237*-4,"0"))[t(213)]("")},An={};An[nI(211)]=oI,An.randomBytes=sI;function gn(e,t){const r=Sl();return gn=function(n,o){return n=n-(-7373+7187*1+395),r[n]},gn(e,t)}function Sl(){const e=["join","2500590yHdCUG","3CzpgOE","219762yRRBUK","592022JqIdxi","from","6033730pSHJFF","28gKZiuO","getRandomValues","147169GUBreL","5fFOMNB","1140KVOWlq","ZUPdr","toString","DBGzc","45351XtLuDF","svuxn","9892WpQPGF","randomUUID","2504EaskHQ"];return Sl=function(){return e},Sl()}function yn(e,t){const r=Cl();return yn=function(n,o){return n=n-(-1483*3+-5564+20*513),r[n]},yn(e,t)}const Dr=yn,aa=yn;(function(e,t){const r=yn,n=yn,o=e();for(;;)try{if(parseInt(r(302))/1+-parseInt(n(249))/2+-parseInt(r(291))/3+-parseInt(r(292))/4*(parseInt(r(264))/5)+-parseInt(n(273))/6*(parseInt(r(266))/7)+parseInt(r(300))/8*(parseInt(r(269))/9)+parseInt(n(255))/10*(parseInt(r(284))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Cl,-4*308317+753182*2+658196);const aI=(e,t)=>{const r=yn,n=yn,o={olCWX:function(l,c,u){return l(c,u)},sfXDX:function(l,c,u){return l(c,u)},ksWFu:function(l,c,u){return l(c,u)}};o[r(283)](Kx,e,t),Yx(e,t);const s=o[n(283)](Qx,t,e),a=o[n(294)](eI,t,e),i=o[r(277)](Xx,t,e);t.addRequestListener(s),t.addResponseListener(a),t[n(287)](i),e.onclose=()=>{const l=r,c=n;t[l(247)](s),t.removeResponseListener(a),t[c(252)](i)}},dd=(e,t,r)=>{const n={QhPqi:function(a,i){return a instanceof i},AIICR:"close",Qalmc:function(a,i,l){return a(i,l)}},o=()=>{var a;n.QhPqi(r,Ko)&&((a=r._eventSource)==null||a.addEventListener(n.AIICR,()=>{var i;(i=r[yn(295)])==null||i.close()})),n.Qalmc(aI,e,t)},s={};s.afterInit=o,n.Qalmc(rI,t,s)},r2=(e,t=An[Dr(299)]())=>{const r=Dr,n=Dr,o={RVabx:function(u,f,p){return u(f,p)},crCTs:"include"},s={};s["sse-session-id"]=t;const a=s,i={};i["sse-session-id"]=t;const l={};l.headers=i,l.credentials=o[r(304)];const c={requestInit:l,eventSourceInit:{async fetch(u,f){const p=r,h=r,m=new Headers(f?.[p(268)]||{});Object.entries(a).forEach(([g,w])=>{m.set(g,w)});const _={...f};return _.headers=m,o[h(279)](fetch,u,_)},withCredentials:!0}};return e&&(c[r(280)].headers.Authorization="Bearer "+e,a.Authorization=n(256)+e),c},n2=(e,t=An[Dr(299)]())=>{const r=aa,n=Dr,o={};o[r(271)]="include";const s=o,a={};a["stream-session-id"]=t;const i={};i[n(268)]=a,i.credentials=s[r(271)];const l={};l.requestInit=i;const c=l;return e&&(c[n(280)][r(268)][n(301)]=r(256)+e),c},pd=async(e,t,r)=>{const n=Dr,o=Dr,s={rRtFD:function(i){return i()},ToRAF:function(i,l){return i instanceof l}},a=s[n(276)](r);try{return await e[o(260)](a),a}catch(i){if(s[n(275)](i,Cr)){const l=await t();return await a[n(257)](l),await pd(e,t,r)}else throw i}},o2=(e,t)=>{const r=aa,n=aa,o={};o[r(267)]=function(a,i){return a in i},o.timcZ="waitForOAuthCode",o[r(253)]=function(a,i){return a===i},o.ufiEQ=r(285),o[n(250)]=r(293);const s=o;if(s.oGmBG(s[r(258)],e))return e[n(278)];if(s[n(253)](typeof t,s.ufiEQ))return t;throw new Error(s.daYBw)};function Cl(){const e=["oGmBG","headers","1233BqDPfE","eventSourceInit","jmVYh","wfHUn","1336686qzpbXm","_endpoint","ToRAF","rRtFD","ksWFu","waitForOAuthCode","RVabx","requestInit","mcp-sse-proxy-client","CfBXU","olCWX","341WrxLOu","function","sessionId","addNotificationListener","version","GKDjq","roots","5390433vAXkON","4NpGpPF","waitForOAuthCode need to be provided when authProvider is provided","sfXDX","_eventSource","PdsSn","get","sampling","randomUUID","4064jocfPO","Authorization","452565rqIeHi","elicitation","crCTs","authProvider","removeRequestListener","1.0.0","104070FoHgyi","daYBw","capabilities","removeNotificationListener","lauIp","listChanged","1255910ovFXHu","Bearer ","finishAuth","timcZ","eZwNI","connect","JzpWy","tUMle","kdowC","379385gxVFVP","&token=","49TIzdXg"];return Cl=function(){return e},Cl()}const iI=async e=>{const t=aa,r=Dr,n={GKDjq:function(C,L,O){return C(L,O)},JzpWy:t(281),mcbiU:"1.0.0",CfBXU:function(C){return C()},kdowC:function(C,L,O,q){return C(L,O,q)},KkViY:"sessionId"},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:f}=e,p={};p[r(305)]=l,p.requestInit=c,p.eventSourceInit=u;const h=p,m=i||An[r(299)](),_=n[t(289)](r2,a,m);if(c){const C={..._.requestInit,...c};C[r(268)]={..._[r(280)][t(268)],...c.headers},h.requestInit=C}else h.requestInit=_[t(280)];if(u){const C={..._[t(270)],...u};h.eventSourceInit=C}else h.eventSourceInit=_[t(270)];const g={};g[t(254)]=!0;const w={};w.roots=g,w[t(298)]={},w[r(303)]={};const v=w,y={};y.name=n[r(261)],y[t(288)]=n.mcbiU;const S={};S[t(251)]=v;const b=new Xs(y,S),T=()=>new Ko(new URL(s),h);let x=n[t(282)](T);if(l){const C=o2(l,f);x=await n[t(263)](pd,b,C,T)}else await b.connect(x);dd(b,o,x),x.sessionId=x[r(274)].searchParams[t(297)](n.KkViY);const R={};return R.transport=x,R.sessionId=x[r(286)],R},lI=async e=>{const t=aa,r=Dr,n={wfHUn:function(C,L,O){return C(L,O)},tUMle:"mcp-stream-proxy-client",omKPe:t(248),rSiEq:function(C){return C()},PdsSn:function(C,L,O,q){return C(L,O,q)}},{client:o,url:s,token:a,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:f}=e,p={};p.authProvider=l,p.requestInit=c,p.reconnectionOptions=u;const h=p,m=i||An.randomUUID(),_=n[r(272)](n2,a,m);if(c){const C={..._[t(280)],...c};C.headers={..._.requestInit[t(268)],...c.headers},h.requestInit=C}else h[r(280)]=_[r(280)];const g={};g[r(254)]=!0;const w={};w.roots=g,w[t(298)]={},w[t(303)]={};const v=w,y={};y.name=n[t(262)],y.version=n.omKPe;const S={};S.capabilities=v;const b=new Xs(y,S),T=()=>new oa(new URL(s),h);let x=n.rSiEq(T);if(l){const C=n[t(272)](o2,l,f);x=await n[t(296)](pd,b,C,T)}else await b[t(260)](x);n.PdsSn(dd,b,o,x);const R={};return R.transport=x,R[r(286)]=x[r(286)],R},cI=async e=>{const t=Dr,r=Dr,n={eZwNI:function(w,v,y,S){return w(v,y,S)}},{client:o,url:s,token:a,sessionId:i}=e,l={};l[t(254)]=!0;const c={};c[r(290)]=l,c.sampling={},c.elicitation={};const u=c,f={};f.name="mcp-socket-proxy-client",f.version=r(248);const p={};p[r(251)]=u;const h=new Xs(f,p),m=i||An[r(299)](),_=new e2(new URL(s+"?sessionId="+m+r(265)+a));await h.connect(_),n[t(259)](dd,h,o,_);const g={};return g.transport=_,g[r(286)]=m,g},qn=Ur,ia=Ur;(function(e,t){const r=Ur,n=Ur,o=e();for(;;)try{if(parseInt(r(216))/1+-parseInt(n(219))/2+-parseInt(r(203))/3*(-parseInt(n(204))/4)+-parseInt(n(199))/5*(parseInt(r(193))/6)+-parseInt(r(211))/7*(-parseInt(r(192))/8)+-parseInt(n(221))/9+parseInt(n(201))/10*(parseInt(r(220))/11)===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(xl,1297719+-42747*-22+-1289197);function Ur(e,t){const r=xl();return Ur=function(n,o){return n=n-(-4158*1+-2*581+-1*-5510),r[n]},Ur(e,t)}const uI=()=>An.randomBytes(-8746+-382*-23);class dI{constructor(t){const r=Ur,n=Ur,o={HbwOh:function(u){return u()}};this._callBackPromise={};const{clientMetadata:s,state:a,redirectCallback:i,getAuthCodeByState:l,waitForOAuthCode:c}=t;this._clientMetadata=s,this[r(206)]=s.redirect_uris[-10*629+1*7646+-1356],this[n(197)]=a||o.HbwOh(uI),this._redirectCallback=i||this[n(202)],this[n(195)]=l||this[r(191)],this.waitForOAuthCode=c||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(t){var r,n,o,s,a,i;const l=Ur,c=Ur,u={};u[l(198)]="GET";const f=await fetch(t,u);!f.ok&&((n=(r=this[c(207)])[c(196)])==null||n.call(r,l(208)+f[c(205)]));const p=await this[c(195)](this._redirectUrl,this[l(197)]);if(!p.ok){(s=(o=this[l(207)]).reject)==null||s.call(o,"Failed to fetch auth code: "+p[c(205)]);return}const h=await p.json();(i=(a=this._callBackPromise).resolve)==null||i.call(a,h.code)}async[qn(191)](t,r){const n=qn,o={};o.xAOmI="POST";const s=o,a={};a["Content-Type"]=n(217);const i={};return i.state=r,fetch(t,{method:s.xAOmI,headers:a,body:new URLSearchParams(i)})}waitForOAuthCodeFunction(){const t=this._callBackPromise;return()=>new Promise((r,n)=>{const o=Ur;t.resolve=r,t[o(196)]=n})}get redirectUrl(){return this[qn(206)]}get[ia(190)](){return this._clientMetadata}[qn(213)](){return this[qn(197)]}[ia(218)](){return this[ia(200)]}[qn(194)](t){this._clientInformation=t}tokens(){return this[ia(210)]}saveTokens(t){const r=ia;this[r(210)]=t}redirectToAuthorization(t){this._redirectCallback(t)}saveCodeVerifier(t){this._codeVerifier=t}[qn(212)](){const t=qn,r={};r[t(215)]=t(214);const n=r;if(!this[t(209)])throw new Error(n.mMdVl);return this[t(209)]}}function xl(){const e=["370aKMzOb","redirectCallbackFunction","6AWGiLu","697420WEpDtk","statusText","_redirectUrl","_callBackPromise","Failed to redirect: ","_codeVerifier","_tokens","21ofrYNd","codeVerifier","state","No code verifier saved","mMdVl","1546908KURscU","application/x-www-form-urlencoded","clientInformation","2551694UzDoIS","571637jVsNJQ","4355271orhxAD","clientMetadata","getAuthCodeByStateFunction","1400360ybYjeP","30zRTJNb","saveClientInformation","_getAuthCodeByState","reject","_state","method","1634810cQPomO","_clientInformation"];return xl=function(){return e},xl()}(function(e,t){for(var r=$l,n=$l,o=e();;)try{var s=parseInt(r(291))/1+-parseInt(r(295))/2*(parseInt(r(288))/3)+parseInt(r(290))/4*(parseInt(r(296))/5)+-parseInt(n(289))/6+parseInt(r(293))/7*(-parseInt(n(294))/8)+parseInt(n(287))/9+parseInt(n(292))/10;if(s===t)break;o.push(o.shift())}catch{o.push(o.shift())}})(Il,262*-2438+1346066*-1+2*1373311);function Il(){var e=["279100FsqxFu","7326315yxcNFg","50823VTWXXj","6441948uoPUwt","92BSiBRu","1361711dyawqa","5202960gnlAWp","7tNVFlv","11056792usEcvw","90CRWXmt"];return Il=function(){return e},Il()}function $l(e,t){var r=Il();return $l=function(n,o){n=n-287;var s=r[n];return s},$l(e,t)}class pI{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}}class fI extends M0{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(al.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{const s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new L0,this.setRequestHandler(Qm,n=>this._oninitialize(n)),this.setNotificationHandler(eu,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(il,async(n,o)=>{const s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,i=al.safeParse(a);return i.success&&this._loggingLevels.set(s,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new pI(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=N0(this._capabilities,t)}setRequestHandler(t,r){const o=Fo(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Nr(o)){const i=o;s=i._zod?.def?.value??i.value}else{const i=o;s=i._def?.value??i.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){const i=async(l,c)=>{const u=Ar(sl,l);if(!u.success){const m=u.error instanceof Error?u.error.message:String(u.error);throw new fe(ye.InvalidParams,`Invalid tools/call request: ${m}`)}const{params:f}=u.data,p=await Promise.resolve(r(l,c));if(f.task){const m=Ar(Do,p);if(!m.success){const _=m.error instanceof Error?m.error.message:String(m.error);throw new fe(ye.InvalidParams,`Invalid task creation result: ${_}`)}return m.data}const h=Ar(zo,p);if(!h.success){const m=h.error instanceof Error?h.error.message:String(h.error);throw new fe(ye.InvalidParams,`Invalid tools/call result: ${m}`)}return h.data};return super.setRequestHandler(t,i)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);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 ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);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 ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);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 ${t})`);break}}assertTaskCapability(t){U0(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&D0(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){const r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:Bm.includes(r)?r:Fs,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"},Mn)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){const n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(c=>c.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,i=a?Array.isArray(a.content)?a.content:[a.content]:[],l=i.some(c=>c.type==="tool_use");if(s){if(o.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){const c=new Set(i.filter(f=>f.type==="tool_use").map(f=>f.id)),u=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(c.size!==u.size||![...c].every(f=>u.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},Su,r):this.request({method:"sampling/createMessage",params:t},cl,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");const o=t;return this.request({method:"elicitation/create",params:o},Ys,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");const o=t.mode==="form"?t:{...t,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Ys,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{const i=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!i.valid)throw new fe(ye.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(a){throw a instanceof fe?a:new fe(ye.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return s}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},Iu,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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 fd=Symbol.for("mcp.completable");function hI(e,t){return Object.defineProperty(e,fd,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function s2(e){return!!e&&typeof e=="object"&&fd in e}function mI(e){return e[fd]?.complete}var a2;(function(e){e.Completable="McpCompletable"})(a2||(a2={}));const i2=1e6,hd=1e6,l2=1e4,gI=1e6;class vn{static isTemplate(t){return/\{[^}\s]+\}/.test(t)}static validateLength(t,r,n){if(t.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${t.length})`)}get variableNames(){return this.parts.flatMap(t=>typeof t=="string"?[]:t.names)}constructor(t){vn.validateLength(t,i2,"Template"),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){const r=[];let n="",o=0,s=0;for(;o<t.length;)if(t[o]==="{"){n&&(r.push(n),n="");const a=t.indexOf("}",o);if(a===-1)throw new Error("Unclosed template expression");if(s++,s>l2)throw new Error(`Template contains too many expressions (max ${l2})`);const i=t.slice(o+1,a),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),f=u[0];for(const p of u)vn.validateLength(p,hd,"Variable name");r.push({name:f,operator:l,names:u,exploded:c}),o=a+1}else n+=t[o],o++;return n&&r.push(n),r}getOperator(t){return["+","#",".","/","?","&"].find(n=>t.startsWith(n))||""}getNames(t){const r=this.getOperator(t);return t.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(t,r){return vn.validateLength(t,hd,"Variable value"),r==="+"||r==="#"?encodeURI(t):encodeURIComponent(t)}expandPart(t,r){if(t.operator==="?"||t.operator==="&"){const a=t.names.map(l=>{const c=r[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(f=>this.encodeValue(f,t.operator)).join(","):this.encodeValue(c.toString(),t.operator);return`${l}=${u}`}).filter(l=>l.length>0);return a.length===0?"":(t.operator==="?"?"?":"&")+a.join("&")}if(t.names.length>1){const a=t.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[t.name];if(n===void 0)return"";const s=(Array.isArray(n)?n:[n]).map(a=>this.encodeValue(a,t.operator));switch(t.operator){case"":return s.join(",");case"+":return s.join(",");case"#":return"#"+s.join(",");case".":return"."+s.join(".");case"/":return"/"+s.join("/");default:return s.join(",")}}expand(t){let r="",n=!1;for(const o of this.parts){if(typeof o=="string"){r+=o;continue}const s=this.expandPart(o,t);s&&((o.operator==="?"||o.operator==="&")&&n?r+=s.replace("?","&"):r+=s,(o.operator==="?"||o.operator==="&")&&(n=!0))}return r}escapeRegExp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(t){const r=[];for(const s of t.names)vn.validateLength(s,hd,"Variable name");if(t.operator==="?"||t.operator==="&"){for(let s=0;s<t.names.length;s++){const a=t.names[s],i=s===0?"\\"+t.operator:"&";r.push({pattern:i+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let n;const o=t.name;switch(t.operator){case"":n=t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(t.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:o}),r}match(t){vn.validateLength(t,i2,"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+="$",vn.validateLength(r,gI,"Generated regex pattern");const o=new RegExp(r),s=t.match(o);if(!s)return null;const a={};for(let i=0;i<n.length;i++){const{name:l,exploded:c}=n[i],u=s[i+1],f=l.replace("*","");c&&u.includes(",")?a[f]=u.split(","):a[f]=u}return a}}const yI=/^[A-Za-z0-9._-]{1,128}$/;function vI(e){const t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!yI.test(e)){const r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return t.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:t}}return{isValid:!0,warnings:t}}function _I(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(const r of t)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 c2(e){const t=vI(e);return _I(e,t.warnings),t.isValid}class wI{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){const o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}class u2{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new fI(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new wI(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(jn(bu)),this.server.assertCanSetRequestHandler(jn(sl)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(bu,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{const n={name:t,title:r.title,description:r.description,inputSchema:(()=>{const o=Qs(r.inputSchema);return o?E0(o,{strictUnions:!0,pipeStrategy:"input"}):kI})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){const o=Qs(r.outputSchema);o&&(n.outputSchema=E0(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(sl,async(t,r)=>{try{const n=this._registeredTools[t.params.name];if(!n)throw new fe(ye.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new fe(ye.InvalidParams,`Tool ${t.params.name} disabled`);const o=!!t.params.task,s=n.execution?.taskSupport,a="createTask"in n.handler;if((s==="required"||s==="optional")&&!a)throw new fe(ye.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new fe(ye.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&a)return await this.handleAutomaticTaskPolling(n,t,r);const i=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,i,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof fe&&n.code===ye.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;const s=Qs(t.inputSchema)??t.inputSchema,a=await $u(s,r);if(!a.success){const i="error"in a?a.error:"Unknown error",l=Eu(i);throw new fe(ye.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return a.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new fe(ye.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);const o=Qs(t.outputSchema),s=await $u(o,r.structuredContent);if(!s.success){const a="error"in s?s.error:"Unknown error",i=Eu(a);throw new fe(ye.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${i}`)}}async executeToolHandler(t,r,n){const o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");const a={...n,taskStore:n.taskStore};if(t.inputSchema){const i=o;return await Promise.resolve(i.createTask(r,a))}else{const i=o;return await Promise.resolve(i.createTask(a))}}if(t.inputSchema){const a=o;return await Promise.resolve(a(r,n))}else{const a=o;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");const o=await this.validateToolInput(t,r.params.arguments,r.params.name),s=t.handler,a={...n,taskStore:n.taskStore},i=o?await Promise.resolve(s.createTask(o,a)):await Promise.resolve(s.createTask(a)),l=i.task.taskId;let c=i.task;const u=c.pollInterval??5e3;for(;c.status!=="completed"&&c.status!=="failed"&&c.status!=="cancelled";){await new Promise(p=>setTimeout(p,u));const f=await n.taskStore.getTask(l);if(!f)throw new fe(ye.InternalError,`Task ${l} not found during polling`);c=f}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(jn(xu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(xu,async t=>{switch(t.params.ref.type){case"ref/prompt":return nC(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return oC(t),this.handleResourceCompletion(t,t.params.ref);default:throw new fe(ye.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){const n=this._registeredPrompts[r.name];if(!n)throw new fe(ye.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new fe(ye.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return la;const s=Fo(n.argsSchema)?.[t.params.argument.name];if(!s2(s))return la;const a=mI(s);if(!a)return la;const i=await a(t.params.argument.value,t.params.context);return f2(i)}async handleResourceCompletion(t,r){const n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return la;throw new fe(ye.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}const o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return la;const s=await o(t.params.argument.value,t.params.context);return f2(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(jn(ol)),this.server.assertCanSetRequestHandler(jn(uu)),this.server.assertCanSetRequestHandler(jn(pu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ol,async(t,r)=>{const n=Object.entries(this._registeredResources).filter(([s,a])=>a.enabled).map(([s,a])=>({uri:s,name:a.name,...a.metadata})),o=[];for(const s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;const a=await s.resourceTemplate.listCallback(r);for(const i of a.resources)o.push({...s.metadata,...i})}return{resources:[...n,...o]}}),this.server.setRequestHandler(uu,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(pu,async(t,r)=>{const n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new fe(ye.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(const s of Object.values(this._registeredResourceTemplates)){const a=s.resourceTemplate.uriTemplate.match(n.toString());if(a)return s.readCallback(n,a,r)}throw new fe(ye.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(jn(hu)),this.server.assertCanSetRequestHandler(jn(mu)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(hu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?SI(r.argsSchema):void 0}))})),this.server.setRequestHandler(mu,async(t,r)=>{const n=this._registeredPrompts[t.params.name];if(!n)throw new fe(ye.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new fe(ye.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){const o=Qs(n.argsSchema),s=await $u(o,t.params.arguments);if(!s.success){const l="error"in s?s.error:"Unknown error",c=Eu(l);throw new fe(ye.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${c}`)}const a=s.data,i=n.callback;return await Promise.resolve(i(a,r))}else{const o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());const s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const a=this._createRegisteredResource(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const a=this._createRegisteredResourceTemplate(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);const s=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,n,o,s){const a={name:t,title:r,metadata:o,readCallback:s,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(t,r,n,o,s){const a={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==t&&(delete this._registeredResourceTemplates[t],c.name&&(this._registeredResourceTemplates[c.name]=a)),typeof c.title<"u"&&(a.title=c.title),typeof c.template<"u"&&(a.resourceTemplate=c.template),typeof c.metadata<"u"&&(a.metadata=c.metadata),typeof c.callback<"u"&&(a.readCallback=c.callback),typeof c.enabled<"u"&&(a.enabled=c.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=a;const i=n.uriTemplate.variableNames;return Array.isArray(i)&&i.some(c=>!!n.completeCallback(c))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(t,r,n,o,s){const a={title:r,description:n,argsSchema:o===void 0?void 0:Zo(o),callback:s,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!==t&&(delete this._registeredPrompts[t],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=Zo(i.argsSchema)),typeof i.callback<"u"&&(a.callback=i.callback),typeof i.enabled<"u"&&(a.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=a,o&&Object.values(o).some(l=>{const c=l instanceof Or?l._def?.innerType:l;return s2(c)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(t,r,n,o,s,a,i,l,c){c2(t);const u={title:r,description:n,inputSchema:p2(o),outputSchema:p2(s),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:f=>{typeof f.name<"u"&&f.name!==t&&(typeof f.name=="string"&&c2(f.name),delete this._registeredTools[t],f.name&&(this._registeredTools[f.name]=u)),typeof f.title<"u"&&(u.title=f.title),typeof f.description<"u"&&(u.description=f.description),typeof f.paramsSchema<"u"&&(u.inputSchema=Zo(f.paramsSchema)),typeof f.outputSchema<"u"&&(u.outputSchema=Zo(f.outputSchema)),typeof f.callback<"u"&&(u.handler=f.callback),typeof f.annotations<"u"&&(u.annotations=f.annotations),typeof f._meta<"u"&&(u._meta=f._meta),typeof f.enabled<"u"&&(u.enabled=f.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,s,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){const l=r[0];md(l)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!md(r[0])&&(a=r.shift())):typeof l=="object"&&l!==null&&(a=r.shift())}const i=r[0];return this._createRegisteredTool(t,void 0,n,o,s,a,{taskSupport:"forbidden"},void 0,i)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);const{title:o,description:s,inputSchema:a,outputSchema:i,annotations:l,_meta:c}=r;return this._createRegisteredTool(t,o,s,a,i,l,{taskSupport:"forbidden"},c,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());const s=r[0],a=this._createRegisteredPrompt(t,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);const{title:o,description:s,argsSchema:a}=r,i=this._createRegisteredPrompt(t,o,s,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class bI{constructor(t,r){this._callbacks=r,this._uriTemplate=typeof t=="string"?new vn(t):t}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(t){return this._callbacks.complete?.[t]}}const kI={type:"object",properties:{}};function d2(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function TI(e){return"_def"in e||"_zod"in e||d2(e)}function md(e){return typeof e!="object"||e===null||TI(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(d2)}function p2(e){if(e)return md(e)?Zo(e):e}function SI(e){const t=Fo(e);return t?Object.entries(t).map(([r,n])=>{const o=cC(n),s=uC(n);return{name:r,description:o,required:!s}}):[]}function jn(e){const r=Fo(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=_0(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function f2(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const la={completion:{values:[],hasMore:!1}};function CI(e){return e.title!==void 0&&e.title!==""?e.title:"annotations"in e&&e.annotations?.title?e.annotations.title:e.name}class ca{constructor(){this._messageQueue=[]}static createLinkedPair(){const t=new ca,r=new ca;return t._otherTransport=r,r._otherTransport=t,[t,r]}async start(){for(;this._messageQueue.length>0;){const t=this._messageQueue.shift();this.onmessage?.(t.message,t.extra)}}async close(){const t=this._otherTransport;this._otherTransport=void 0,await t?.close(),this.onclose?.()}async send(t,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(t,{authInfo:r?.authInfo}):this._otherTransport._messageQueue.push({message:t,extra:{authInfo:r?.authInfo}})}}class xI{constructor(t,r){const n={name:"web-mcp-server",version:"1.0.0"},o={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new u2(t||n,r||{capabilities:o}),this.server.server.oninitialized=()=>{this.oninitialized?.()},this.server.server.onclose=()=>{this.onclose?.()},this.server.server.onerror=s=>{this.onerror?.(s)},this.server.server.setRequestHandler(il,async()=>({}))}async connect(t){return typeof t.start=="function"?(this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new cd(t),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(t,r,n){return this.server.registerTool(t,r,n)}registerPrompt(t,r,n){return this.server.registerPrompt(t,r,n)}registerResource(t,r,n,o){return typeof r=="string"?this.server.registerResource(t,r,n,o):this.server.registerResource(t,r,n,o)}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(t,r){return await this.server.server.createMessage(t,r)}async elicitInput(t,r){return await this.server.server.elicitInput(t,r)}async listRoots(t,r){return await this.server.server.listRoots(t,r)}async sendLoggingMessage(t){return await this.server.server.sendLoggingMessage(t)}async sendResourceUpdated(t){return await this.server.server.sendResourceUpdated(t)}request(t,r,n){return this.server.server.request(t,r,n)}async notification(t,r){return await this.server.server.notification(t,r)}setRequestHandler(t,r){this.server.server.setRequestHandler(t,r)}removeRequestHandler(t){this.server.server.removeRequestHandler(t)}setNotificationHandler(t,r){this.server.server.setNotificationHandler(t,r)}removeNotificationHandler(t){this.server.server.removeNotificationHandler(t)}onSubscribe(t){this.server.server.setRequestHandler(i0,t)}onUnsubscribe(t){this.server.server.setRequestHandler(l0,t)}onSetLogLevel(t){this.server.server.setRequestHandler(il,t)}onListResources(t){this.server.server.setRequestHandler(ol,t)}onRootsListChanged(t){this.server.server.setNotificationHandler(y0,t)}async onPagehide(t){t.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const II=(e,t)=>new cd(e,t),$I=()=>Jx(),EI=e=>e instanceof cd,RI=e=>e instanceof u2,PI=e=>{e.onmessage=async t=>{if(!t||typeof t!="object")return;const r=t.id;try{if(t.method==="initialize")await e.send({jsonrpc:"2.0",id:r,result:{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"browser-builtin-webmcp-proxy",version:"1.0.0"}}});else if(t.method!=="notifications/initialized")if(t.method==="ping"||t.method==="custom_ping")await e.send({jsonrpc:"2.0",id:r,result:{}});else if(t.method==="tools/list"){const n=typeof navigator<"u"?navigator.modelContextTesting||navigator.modelContext:null;if(n&&n.listTools){const s=(await n.listTools()).map(a=>{let i={};if(typeof a.inputSchema=="string")try{i=JSON.parse(a.inputSchema)}catch(l){console.error("Failed to parse inputSchema:",l)}else typeof a.inputSchema=="object"&&a.inputSchema!==null&&(i=a.inputSchema);return{name:a.name,description:a.description||"",inputSchema:{type:"object",properties:i.properties||{},required:i.required||[]}}});await e.send({jsonrpc:"2.0",id:r,result:{tools:s}})}else await e.send({jsonrpc:"2.0",id:r,result:{tools:[]}})}else if(t.method==="tools/call"){const n=typeof navigator<"u"?navigator.modelContextTesting||navigator.modelContext:null;if(n&&n.executeTool){const{name:o,arguments:s}=t.params,a=await n.executeTool(o,JSON.stringify(s||{})),i=a&&typeof a=="object"&&"content"in a?a:{content:[{type:"text",text:typeof a=="string"?a:JSON.stringify(a)}]};await e.send({jsonrpc:"2.0",id:r,result:i})}else await e.send({jsonrpc:"2.0",id:r,error:{code:-32601,message:"Browser built-in WebMCP not available"}})}else r!==void 0&&await e.send({jsonrpc:"2.0",id:r,error:{code:-32601,message:`Method not found: ${t.method}`}})}catch(n){r!==void 0&&await e.send({jsonrpc:"2.0",id:r,error:{code:-32e3,message:n.message||String(n)}})}}};class h2{constructor(t,r){const n={name:"web-mcp-client",version:"1.0.0"},o={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Xs(t||n,r||{capabilities:o}),this.client.onclose=()=>{this.onclose?.()},this.client.onerror=s=>{this.onerror?.(s)}}async connect(t){if(typeof t.start=="function")return this.transport=t,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:n,sessionId:o,type:s,agent:a,builtin:i,onError:l}=t;if(a===!0){const f={client:this.client,url:r,token:n,sessionId:o};let p;return await(async()=>{const{transport:m,sessionId:_}=s==="sse"?await iI(f):s==="socket"?await cI(f):await lI(f);m.onerror=async g=>{l?.(g)},i===!0&&PI(m),p={transport:m,sessionId:_}})(),p}const c=new URL(r);let u;if(s==="channel"&&(u=new ld(r),await this.client.connect(u)),s==="sse"){const f=r2(n,o);u=new Ko(c,f),await this.client.connect(u)}if(s==="socket"&&(u=new e2(new URL(`${r}?sessionId=${o}&token=${n}`)),u.sessionId=o,await this.client.connect(u)),typeof u>"u"){const f=n2(n,o);u=new oa(c,f),await this.client.connect(u)}return this.transport=u,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(t){return await this.client.ping(t)}async complete(t,r){return await this.client.complete(t,r)}async setLoggingLevel(t,r){return await this.client.setLoggingLevel(t,r)}async getPrompt(t,r){return await this.client.getPrompt(t,r)}async listPrompts(t,r){return await this.client.listPrompts(t,r)}async listResources(t,r){return await this.client.listResources(t,r)}async listResourceTemplates(t,r){return await this.client.listResourceTemplates(t,r)}async readResource(t,r){return await this.client.readResource(t,r)}async subscribeResource(t,r){return await this.client.subscribeResource(t,r)}async unsubscribeResource(t,r){return await this.client.unsubscribeResource(t,r)}async callTool(t,r){return await this.client.callTool(t,zo,r)}async listTools(t,r){return await this.client.listTools(t,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(t,r,n){return this.client.request(t,r,n)}async notification(t,r){return await this.client.notification(t,r)}setRequestHandler(t,r){this.client.setRequestHandler(t,r)}removeRequestHandler(t){this.client.removeRequestHandler(t)}setNotificationHandler(t,r){this.client.setNotificationHandler(t,r)}removeNotificationHandler(t){this.client.removeNotificationHandler(t)}onElicit(t){this.client.setRequestHandler(Cu,t)}onCreateMessage(t){this.client.setRequestHandler(Tu,t)}onListRoots(t){this.client.setRequestHandler(g0,t)}onToolListChanged(t){this.client.setNotificationHandler(ku,t)}onPromptListChanged(t){this.client.setNotificationHandler(wu,t)}onResourceListChanged(t){this.client.setNotificationHandler(fu,t)}onResourceUpdated(t){this.client.setNotificationHandler(c0,t)}onLoggingMessage(t){this.client.setNotificationHandler(h0,t)}async onPagehide(t){t.persisted||(m2(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const MI=(e,t)=>new Ko(e,t),OI=(e,t)=>new oa(e,t),NI=(e,t)=>new ld(e,t),AI=e=>e instanceof Ko,m2=e=>e instanceof oa,qI=e=>e instanceof ld,jI=e=>e instanceof Xs,Xo=(e,t,r)=>{window.postMessage({type:e,direction:r,data:t},"*")},LI=(e,t,r)=>{const n=async function(o){o.source===window&&o.data.type===e&&o.data.direction===r&&await t(o.data.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)},gd=(e,t,r)=>{if(r.endsWith("content"))chrome.tabs.query({},n=>{n.forEach(o=>{chrome.tabs.sendMessage(o.id,{type:e,data:t,direction:r,tabId:o.id})})});else return chrome.runtime.sendMessage({direction:r,type:e,data:t})},g2=(e,t,r,n)=>{const o=(s,a,i)=>{if(s.type===e&&s.direction===r&&(!n||n&&s.tabId===n)){const{data:l}=s;t(l,a,i),i(a)}};return chrome.runtime.onMessage.addListener(o),()=>chrome.runtime.onMessage.removeListener(o)};class y2{constructor(t){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=t,this._messageListener=g2("mcp-server-to-client",r=>{try{if(r.sessionId!==this.targetSessionId)return;const n=hn.parse(r.mcpMessage);this.onmessage?.(n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->bg")}_throwError(t,r){if(t()){const n=new Error(r);throw console.log(r,n),this.onerror&&this.onerror(n),n}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(t,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");let n;if(chrome.sessionRegistry){const o=chrome.sessionRegistry.get(this.targetSessionId);o&&o.tabIds.length>0&&(n=o.tabIds[o.tabIds.length-1])}n==null&&(n=await chrome.runtime.sendMessage({type:"get-session-tab-id",sessionId:this.targetSessionId})),this._throwError(()=>n==null,`【Client Transport】后台未找到活动的tabId用于${this.targetSessionId}`),gd("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,mcpMessage:t},"bg->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 yd=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)});class DI{constructor(t=null){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||yd(),this._messageListener2=LI("mcp-client-to-server-to-page",r=>{if(r.sessionId!==this.sessionId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",r.mcpMessage);const n=hn.parse(r.mcpMessage);this.onmessage?.(n),r.mcpMessage.params?.name&&Xo("update-page-app-message",{status:"run",message:r.mcpMessage.params?.name},"page->content")},"content->page")}_throwError(t,r){if(t()){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(t,r){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),Xo("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:t},"page->content"),"result"in t&&t.result?.content&&Xo("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(t){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=t;try{Xo("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...t,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._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(t))}}}class UI{constructor(t=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=t||yd(),this.tabId=r}_throwError(t,r){if(t()){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】 已关闭,无法重新启动");g2("mcp-client-to-server",t=>{if(!(t.sessionId!==this.sessionId||t.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",t.mcpMessage);const r=hn.parse(t.mcpMessage);this.onmessage?.(r),t.mcpMessage.params?.name&&Xo("update-page-app-message",{status:"run",message:t.mcpMessage.params?.name},"page->content")}catch(r){console.log("【Content Svr Transport】 处理消息时发生错误:",r)}},"bg->content",this.tabId),this._isStarted=!0}}async send(t,r){this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",t),gd("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:t},"content->bg"),"result"in t&&t.result?.content&&Xo("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(t){this._isStarted&&(this._lastRegistration=t,gd("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...t,url:window.location.origin,title:document.title}},"content->bg"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(t){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(t))}}}var es={},vd,v2;function zI(){return v2||(v2=1,vd=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),vd}var _d={},Ln={},_2;function lo(){if(_2)return Ln;_2=1;let e;const t=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Ln.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},Ln.getSymbolTotalCodewords=function(n){return t[n]},Ln.getBCHDigit=function(r){let n=0;for(;r!==0;)n++,r>>>=1;return n},Ln.setToSJISFunction=function(n){if(typeof n!="function")throw new Error('"toSJISFunc" is not a valid function.');e=n},Ln.isKanjiModeEnabled=function(){return typeof e<"u"},Ln.toSJIS=function(n){return e(n)},Ln}var wd={},w2;function bd(){return w2||(w2=1,(function(e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+r)}}e.isValid=function(n){return n&&typeof n.bit<"u"&&n.bit>=0&&n.bit<4},e.from=function(n,o){if(e.isValid(n))return n;try{return t(n)}catch{return o}}})(wd)),wd}var kd,b2;function ZI(){if(b2)return kd;b2=1;function e(){this.buffer=[],this.length=0}return e.prototype={get:function(t){const r=Math.floor(t/8);return(this.buffer[r]>>>7-t%8&1)===1},put:function(t,r){for(let n=0;n<r;n++)this.putBit((t>>>r-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},kd=e,kd}var Td,k2;function FI(){if(k2)return Td;k2=1;function e(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}return e.prototype.set=function(t,r,n,o){const s=t*this.size+r;this.data[s]=n,o&&(this.reservedBit[s]=!0)},e.prototype.get=function(t,r){return this.data[t*this.size+r]},e.prototype.xor=function(t,r,n){this.data[t*this.size+r]^=n},e.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},Td=e,Td}var Sd={},T2;function VI(){return T2||(T2=1,(function(e){const t=lo().getSymbolSize;e.getRowColCoords=function(n){if(n===1)return[];const o=Math.floor(n/7)+2,s=t(n),a=s===145?26:Math.ceil((s-13)/(2*o-2))*2,i=[s-7];for(let l=1;l<o-1;l++)i[l]=i[l-1]-a;return i.push(6),i.reverse()},e.getPositions=function(n){const o=[],s=e.getRowColCoords(n),a=s.length;for(let i=0;i<a;i++)for(let l=0;l<a;l++)i===0&&l===0||i===0&&l===a-1||i===a-1&&l===0||o.push([s[i],s[l]]);return o}})(Sd)),Sd}var Cd={},S2;function HI(){if(S2)return Cd;S2=1;const e=lo().getSymbolSize,t=7;return Cd.getPositions=function(n){const o=e(n);return[[0,0],[o-t,0],[0,o-t]]},Cd}var xd={},C2;function BI(){return C2||(C2=1,(function(e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(o){return o!=null&&o!==""&&!isNaN(o)&&o>=0&&o<=7},e.from=function(o){return e.isValid(o)?parseInt(o,10):void 0},e.getPenaltyN1=function(o){const s=o.size;let a=0,i=0,l=0,c=null,u=null;for(let f=0;f<s;f++){i=l=0,c=u=null;for(let p=0;p<s;p++){let h=o.get(f,p);h===c?i++:(i>=5&&(a+=t.N1+(i-5)),c=h,i=1),h=o.get(p,f),h===u?l++:(l>=5&&(a+=t.N1+(l-5)),u=h,l=1)}i>=5&&(a+=t.N1+(i-5)),l>=5&&(a+=t.N1+(l-5))}return a},e.getPenaltyN2=function(o){const s=o.size;let a=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const c=o.get(i,l)+o.get(i,l+1)+o.get(i+1,l)+o.get(i+1,l+1);(c===4||c===0)&&a++}return a*t.N2},e.getPenaltyN3=function(o){const s=o.size;let a=0,i=0,l=0;for(let c=0;c<s;c++){i=l=0;for(let u=0;u<s;u++)i=i<<1&2047|o.get(c,u),u>=10&&(i===1488||i===93)&&a++,l=l<<1&2047|o.get(u,c),u>=10&&(l===1488||l===93)&&a++}return a*t.N3},e.getPenaltyN4=function(o){let s=0;const a=o.data.length;for(let l=0;l<a;l++)s+=o.data[l];return Math.abs(Math.ceil(s*100/a/5)-10)*t.N4};function r(n,o,s){switch(n){case e.Patterns.PATTERN000:return(o+s)%2===0;case e.Patterns.PATTERN001:return o%2===0;case e.Patterns.PATTERN010:return s%3===0;case e.Patterns.PATTERN011:return(o+s)%3===0;case e.Patterns.PATTERN100:return(Math.floor(o/2)+Math.floor(s/3))%2===0;case e.Patterns.PATTERN101:return o*s%2+o*s%3===0;case e.Patterns.PATTERN110:return(o*s%2+o*s%3)%2===0;case e.Patterns.PATTERN111:return(o*s%3+(o+s)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}e.applyMask=function(o,s){const a=s.size;for(let i=0;i<a;i++)for(let l=0;l<a;l++)s.isReserved(l,i)||s.xor(l,i,r(o,l,i))},e.getBestMask=function(o,s){const a=Object.keys(e.Patterns).length;let i=0,l=1/0;for(let c=0;c<a;c++){s(c),e.applyMask(c,o);const u=e.getPenaltyN1(o)+e.getPenaltyN2(o)+e.getPenaltyN3(o)+e.getPenaltyN4(o);e.applyMask(c,o),u<l&&(l=u,i=c)}return i}})(xd)),xd}var El={},x2;function I2(){if(x2)return El;x2=1;const e=bd(),t=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return El.getBlocksCount=function(o,s){switch(s){case e.L:return t[(o-1)*4+0];case e.M:return t[(o-1)*4+1];case e.Q:return t[(o-1)*4+2];case e.H:return t[(o-1)*4+3];default:return}},El.getTotalCodewordsCount=function(o,s){switch(s){case e.L:return r[(o-1)*4+0];case e.M:return r[(o-1)*4+1];case e.Q:return r[(o-1)*4+2];case e.H:return r[(o-1)*4+3];default:return}},El}var Id={},ua={},$2;function JI(){if($2)return ua;$2=1;const e=new Uint8Array(512),t=new Uint8Array(256);return(function(){let n=1;for(let o=0;o<255;o++)e[o]=n,t[n]=o,n<<=1,n&256&&(n^=285);for(let o=255;o<512;o++)e[o]=e[o-255]})(),ua.log=function(n){if(n<1)throw new Error("log("+n+")");return t[n]},ua.exp=function(n){return e[n]},ua.mul=function(n,o){return n===0||o===0?0:e[t[n]+t[o]]},ua}var E2;function WI(){return E2||(E2=1,(function(e){const t=JI();e.mul=function(n,o){const s=new Uint8Array(n.length+o.length-1);for(let a=0;a<n.length;a++)for(let i=0;i<o.length;i++)s[a+i]^=t.mul(n[a],o[i]);return s},e.mod=function(n,o){let s=new Uint8Array(n);for(;s.length-o.length>=0;){const a=s[0];for(let l=0;l<o.length;l++)s[l]^=t.mul(o[l],a);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},e.generateECPolynomial=function(n){let o=new Uint8Array([1]);for(let s=0;s<n;s++)o=e.mul(o,new Uint8Array([1,t.exp(s)]));return o}})(Id)),Id}var $d,R2;function GI(){if(R2)return $d;R2=1;const e=WI();function t(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}return t.prototype.initialize=function(n){this.degree=n,this.genPoly=e.generateECPolynomial(this.degree)},t.prototype.encode=function(n){if(!this.genPoly)throw new Error("Encoder not initialized");const o=new Uint8Array(n.length+this.degree);o.set(n);const s=e.mod(o,this.genPoly),a=this.degree-s.length;if(a>0){const i=new Uint8Array(this.degree);return i.set(s,a),i}return s},$d=t,$d}var Ed={},Rd={},Pd={},P2;function M2(){return P2||(P2=1,Pd.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}),Pd}var Yr={},O2;function N2(){if(O2)return Yr;O2=1;const e="[0-9]+",t="[A-Z $%*+\\-./:]+";let r="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";r=r.replace(/u/g,"\\u");const n="(?:(?![A-Z0-9 $%*+\\-./:]|"+r+`)(?:.|[\r
44
+ ]))+`;Yr.KANJI=new RegExp(r,"g"),Yr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Yr.BYTE=new RegExp(n,"g"),Yr.NUMERIC=new RegExp(e,"g"),Yr.ALPHANUMERIC=new RegExp(t,"g");const o=new RegExp("^"+r+"$"),s=new RegExp("^"+e+"$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Yr.testKanji=function(l){return o.test(l)},Yr.testNumeric=function(l){return s.test(l)},Yr.testAlphanumeric=function(l){return a.test(l)},Yr}var A2;function co(){return A2||(A2=1,(function(e){const t=M2(),r=N2();e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(s,a){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!t.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?s.ccBits[0]:a<27?s.ccBits[1]:s.ccBits[2]},e.getBestModeForData=function(s){return r.testNumeric(s)?e.NUMERIC:r.testAlphanumeric(s)?e.ALPHANUMERIC:r.testKanji(s)?e.KANJI:e.BYTE},e.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},e.isValid=function(s){return s&&s.bit&&s.ccBits};function n(o){if(typeof o!="string")throw new Error("Param is not a string");switch(o.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+o)}}e.from=function(s,a){if(e.isValid(s))return s;try{return n(s)}catch{return a}}})(Rd)),Rd}var q2;function KI(){return q2||(q2=1,(function(e){const t=lo(),r=I2(),n=bd(),o=co(),s=M2(),a=7973,i=t.getBCHDigit(a);function l(p,h,m){for(let _=1;_<=40;_++)if(h<=e.getCapacity(_,m,p))return _}function c(p,h){return o.getCharCountIndicator(p,h)+4}function u(p,h){let m=0;return p.forEach(function(_){const g=c(_.mode,h);m+=g+_.getBitsLength()}),m}function f(p,h){for(let m=1;m<=40;m++)if(u(p,m)<=e.getCapacity(m,h,o.MIXED))return m}e.from=function(h,m){return s.isValid(h)?parseInt(h,10):m},e.getCapacity=function(h,m,_){if(!s.isValid(h))throw new Error("Invalid QR Code version");typeof _>"u"&&(_=o.BYTE);const g=t.getSymbolTotalCodewords(h),w=r.getTotalCodewordsCount(h,m),v=(g-w)*8;if(_===o.MIXED)return v;const y=v-c(_,h);switch(_){case o.NUMERIC:return Math.floor(y/10*3);case o.ALPHANUMERIC:return Math.floor(y/11*2);case o.KANJI:return Math.floor(y/13);case o.BYTE:default:return Math.floor(y/8)}},e.getBestVersionForData=function(h,m){let _;const g=n.from(m,n.M);if(Array.isArray(h)){if(h.length>1)return f(h,g);if(h.length===0)return 1;_=h[0]}else _=h;return l(_.mode,_.getLength(),g)},e.getEncodedBits=function(h){if(!s.isValid(h)||h<7)throw new Error("Invalid QR Code version");let m=h<<12;for(;t.getBCHDigit(m)-i>=0;)m^=a<<t.getBCHDigit(m)-i;return h<<12|m}})(Ed)),Ed}var Md={},j2;function YI(){if(j2)return Md;j2=1;const e=lo(),t=1335,r=21522,n=e.getBCHDigit(t);return Md.getEncodedBits=function(s,a){const i=s.bit<<3|a;let l=i<<10;for(;e.getBCHDigit(l)-n>=0;)l^=t<<e.getBCHDigit(l)-n;return(i<<10|l)^r},Md}var Od={},Nd,L2;function QI(){if(L2)return Nd;L2=1;const e=co();function t(r){this.mode=e.NUMERIC,this.data=r.toString()}return t.getBitsLength=function(n){return 10*Math.floor(n/3)+(n%3?n%3*3+1:0)},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(n){let o,s,a;for(o=0;o+3<=this.data.length;o+=3)s=this.data.substr(o,3),a=parseInt(s,10),n.put(a,10);const i=this.data.length-o;i>0&&(s=this.data.substr(o),a=parseInt(s,10),n.put(a,i*3+1))},Nd=t,Nd}var Ad,D2;function XI(){if(D2)return Ad;D2=1;const e=co(),t=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function r(n){this.mode=e.ALPHANUMERIC,this.data=n}return r.getBitsLength=function(o){return 11*Math.floor(o/2)+6*(o%2)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(o){let s;for(s=0;s+2<=this.data.length;s+=2){let a=t.indexOf(this.data[s])*45;a+=t.indexOf(this.data[s+1]),o.put(a,11)}this.data.length%2&&o.put(t.indexOf(this.data[s]),6)},Ad=r,Ad}var qd,U2;function e6(){if(U2)return qd;U2=1;const e=co();function t(r){this.mode=e.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}return t.getBitsLength=function(n){return n*8},t.prototype.getLength=function(){return this.data.length},t.prototype.getBitsLength=function(){return t.getBitsLength(this.data.length)},t.prototype.write=function(r){for(let n=0,o=this.data.length;n<o;n++)r.put(this.data[n],8)},qd=t,qd}var jd,z2;function t6(){if(z2)return jd;z2=1;const e=co(),t=lo();function r(n){this.mode=e.KANJI,this.data=n}return r.getBitsLength=function(o){return o*13},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(n){let o;for(o=0;o<this.data.length;o++){let s=t.toSJIS(this.data[o]);if(s>=33088&&s<=40956)s-=33088;else if(s>=57408&&s<=60351)s-=49472;else throw new Error("Invalid SJIS character: "+this.data[o]+`
45
+ Make sure your charset is UTF-8`);s=(s>>>8&255)*192+(s&255),n.put(s,13)}},jd=r,jd}var Ld={exports:{}},Z2;function r6(){return Z2||(Z2=1,(function(e){var t={single_source_shortest_paths:function(r,n,o){var s={},a={};a[n]=0;var i=t.PriorityQueue.make();i.push(n,0);for(var l,c,u,f,p,h,m,_,g;!i.empty();){l=i.pop(),c=l.value,f=l.cost,p=r[c]||{};for(u in p)p.hasOwnProperty(u)&&(h=p[u],m=f+h,_=a[u],g=typeof a[u]>"u",(g||_>m)&&(a[u]=m,i.push(u,m),s[u]=c))}if(typeof o<"u"&&typeof a[o]>"u"){var w=["Could not find a path from ",n," to ",o,"."].join("");throw new Error(w)}return s},extract_shortest_path_from_predecessor_list:function(r,n){for(var o=[],s=n;s;)o.push(s),r[s],s=r[s];return o.reverse(),o},find_path:function(r,n,o){var s=t.single_source_shortest_paths(r,n,o);return t.extract_shortest_path_from_predecessor_list(s,o)},PriorityQueue:{make:function(r){var n=t.PriorityQueue,o={},s;r=r||{};for(s in n)n.hasOwnProperty(s)&&(o[s]=n[s]);return o.queue=[],o.sorter=r.sorter||n.default_sorter,o},default_sorter:function(r,n){return r.cost-n.cost},push:function(r,n){var o={value:r,cost:n};this.queue.push(o),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};e.exports=t})(Ld)),Ld.exports}var F2;function n6(){return F2||(F2=1,(function(e){const t=co(),r=QI(),n=XI(),o=e6(),s=t6(),a=N2(),i=lo(),l=r6();function c(w){return unescape(encodeURIComponent(w)).length}function u(w,v,y){const S=[];let b;for(;(b=w.exec(y))!==null;)S.push({data:b[0],index:b.index,mode:v,length:b[0].length});return S}function f(w){const v=u(a.NUMERIC,t.NUMERIC,w),y=u(a.ALPHANUMERIC,t.ALPHANUMERIC,w);let S,b;return i.isKanjiModeEnabled()?(S=u(a.BYTE,t.BYTE,w),b=u(a.KANJI,t.KANJI,w)):(S=u(a.BYTE_KANJI,t.BYTE,w),b=[]),v.concat(y,S,b).sort(function(x,R){return x.index-R.index}).map(function(x){return{data:x.data,mode:x.mode,length:x.length}})}function p(w,v){switch(v){case t.NUMERIC:return r.getBitsLength(w);case t.ALPHANUMERIC:return n.getBitsLength(w);case t.KANJI:return s.getBitsLength(w);case t.BYTE:return o.getBitsLength(w)}}function h(w){return w.reduce(function(v,y){const S=v.length-1>=0?v[v.length-1]:null;return S&&S.mode===y.mode?(v[v.length-1].data+=y.data,v):(v.push(y),v)},[])}function m(w){const v=[];for(let y=0;y<w.length;y++){const S=w[y];switch(S.mode){case t.NUMERIC:v.push([S,{data:S.data,mode:t.ALPHANUMERIC,length:S.length},{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.ALPHANUMERIC:v.push([S,{data:S.data,mode:t.BYTE,length:S.length}]);break;case t.KANJI:v.push([S,{data:S.data,mode:t.BYTE,length:c(S.data)}]);break;case t.BYTE:v.push([{data:S.data,mode:t.BYTE,length:c(S.data)}])}}return v}function _(w,v){const y={},S={start:{}};let b=["start"];for(let T=0;T<w.length;T++){const x=w[T],R=[];for(let C=0;C<x.length;C++){const L=x[C],O=""+T+C;R.push(O),y[O]={node:L,lastCount:0},S[O]={};for(let q=0;q<b.length;q++){const z=b[q];y[z]&&y[z].node.mode===L.mode?(S[z][O]=p(y[z].lastCount+L.length,L.mode)-p(y[z].lastCount,L.mode),y[z].lastCount+=L.length):(y[z]&&(y[z].lastCount=L.length),S[z][O]=p(L.length,L.mode)+4+t.getCharCountIndicator(L.mode,v))}}b=R}for(let T=0;T<b.length;T++)S[b[T]].end=0;return{map:S,table:y}}function g(w,v){let y;const S=t.getBestModeForData(w);if(y=t.from(v,S),y!==t.BYTE&&y.bit<S.bit)throw new Error('"'+w+'" cannot be encoded with mode '+t.toString(y)+`.
46
+ Suggested mode is: `+t.toString(S));switch(y===t.KANJI&&!i.isKanjiModeEnabled()&&(y=t.BYTE),y){case t.NUMERIC:return new r(w);case t.ALPHANUMERIC:return new n(w);case t.KANJI:return new s(w);case t.BYTE:return new o(w)}}e.fromArray=function(v){return v.reduce(function(y,S){return typeof S=="string"?y.push(g(S,null)):S.data&&y.push(g(S.data,S.mode)),y},[])},e.fromString=function(v,y){const S=f(v,i.isKanjiModeEnabled()),b=m(S),T=_(b,y),x=l.find_path(T.map,"start","end"),R=[];for(let C=1;C<x.length-1;C++)R.push(T.table[x[C]].node);return e.fromArray(h(R))},e.rawSplit=function(v){return e.fromArray(f(v,i.isKanjiModeEnabled()))}})(Od)),Od}var V2;function o6(){if(V2)return _d;V2=1;const e=lo(),t=bd(),r=ZI(),n=FI(),o=VI(),s=HI(),a=BI(),i=I2(),l=GI(),c=KI(),u=YI(),f=co(),p=n6();function h(T,x){const R=T.size,C=s.getPositions(x);for(let L=0;L<C.length;L++){const O=C[L][0],q=C[L][1];for(let z=-1;z<=7;z++)if(!(O+z<=-1||R<=O+z))for(let H=-1;H<=7;H++)q+H<=-1||R<=q+H||(z>=0&&z<=6&&(H===0||H===6)||H>=0&&H<=6&&(z===0||z===6)||z>=2&&z<=4&&H>=2&&H<=4?T.set(O+z,q+H,!0,!0):T.set(O+z,q+H,!1,!0))}}function m(T){const x=T.size;for(let R=8;R<x-8;R++){const C=R%2===0;T.set(R,6,C,!0),T.set(6,R,C,!0)}}function _(T,x){const R=o.getPositions(x);for(let C=0;C<R.length;C++){const L=R[C][0],O=R[C][1];for(let q=-2;q<=2;q++)for(let z=-2;z<=2;z++)q===-2||q===2||z===-2||z===2||q===0&&z===0?T.set(L+q,O+z,!0,!0):T.set(L+q,O+z,!1,!0)}}function g(T,x){const R=T.size,C=c.getEncodedBits(x);let L,O,q;for(let z=0;z<18;z++)L=Math.floor(z/3),O=z%3+R-8-3,q=(C>>z&1)===1,T.set(L,O,q,!0),T.set(O,L,q,!0)}function w(T,x,R){const C=T.size,L=u.getEncodedBits(x,R);let O,q;for(O=0;O<15;O++)q=(L>>O&1)===1,O<6?T.set(O,8,q,!0):O<8?T.set(O+1,8,q,!0):T.set(C-15+O,8,q,!0),O<8?T.set(8,C-O-1,q,!0):O<9?T.set(8,15-O-1+1,q,!0):T.set(8,15-O-1,q,!0);T.set(C-8,8,1,!0)}function v(T,x){const R=T.size;let C=-1,L=R-1,O=7,q=0;for(let z=R-1;z>0;z-=2)for(z===6&&z--;;){for(let H=0;H<2;H++)if(!T.isReserved(L,z-H)){let ee=!1;q<x.length&&(ee=(x[q]>>>O&1)===1),T.set(L,z-H,ee),O--,O===-1&&(q++,O=7)}if(L+=C,L<0||R<=L){L-=C,C=-C;break}}}function y(T,x,R){const C=new r;R.forEach(function(H){C.put(H.mode.bit,4),C.put(H.getLength(),f.getCharCountIndicator(H.mode,T)),H.write(C)});const L=e.getSymbolTotalCodewords(T),O=i.getTotalCodewordsCount(T,x),q=(L-O)*8;for(C.getLengthInBits()+4<=q&&C.put(0,4);C.getLengthInBits()%8!==0;)C.putBit(0);const z=(q-C.getLengthInBits())/8;for(let H=0;H<z;H++)C.put(H%2?17:236,8);return S(C,T,x)}function S(T,x,R){const C=e.getSymbolTotalCodewords(x),L=i.getTotalCodewordsCount(x,R),O=C-L,q=i.getBlocksCount(x,R),z=C%q,H=q-z,ee=Math.floor(C/q),re=Math.floor(O/q),X=re+1,V=ee-re,ie=new l(V);let D=0;const E=new Array(q),U=new Array(q);let Z=0;const I=new Uint8Array(T.buffer);for(let be=0;be<q;be++){const W=be<H?re:X;E[be]=I.slice(D,D+W),U[be]=ie.encode(E[be]),D+=W,Z=Math.max(Z,W)}const M=new Uint8Array(C);let B=0,oe,ne;for(oe=0;oe<Z;oe++)for(ne=0;ne<q;ne++)oe<E[ne].length&&(M[B++]=E[ne][oe]);for(oe=0;oe<V;oe++)for(ne=0;ne<q;ne++)M[B++]=U[ne][oe];return M}function b(T,x,R,C){let L;if(Array.isArray(T))L=p.fromArray(T);else if(typeof T=="string"){let ee=x;if(!ee){const re=p.rawSplit(T);ee=c.getBestVersionForData(re,R)}L=p.fromString(T,ee||40)}else throw new Error("Invalid data");const O=c.getBestVersionForData(L,R);if(!O)throw new Error("The amount of data is too big to be stored in a QR Code");if(!x)x=O;else if(x<O)throw new Error(`
47
47
  The chosen QR Code version cannot contain this amount of data.
48
- Minimum version required to store current data is: `+N+`.
49
- `);const L=g(C,R,j),z=e.getSymbolSize(C),H=new n(z);return h(H,C),m(H),_(H,C),w(H,R,0),C>=7&&y(H,C),v(H,L),isNaN(I)&&(I=a.getBestMask(H,w.bind(null,H,R))),a.applyMask(I,H),w(H,R,I),{modules:H,version:C,errorCorrectionLevel:R,maskPattern:I,segments:j}}return md.create=function(C,R){if(typeof C>"u"||C==="")throw new Error("No input text");let I=t.M,j,N;return typeof R<"u"&&(I=t.from(R.errorCorrectionLevel,t.M),j=c.from(R.version),N=a.from(R.maskPattern),R.toSJISFunc&&e.setToSJISFunction(R.toSJISFunc)),b(C,j,I,N)},md}var Ad={},qd={},Z2;function F2(){return Z2||(Z2=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),c=Math.floor((a+s.margin*2)*l),u=s.margin*l,f=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let h=0;h<c;h++){let m=(p*c+h)*4,_=s.color.light;if(p>=u&&h>=u&&p<c-u&&h<c-u){const y=Math.floor((p-u)/l),w=Math.floor((h-u)/l);_=f[i[y*a+w]?1:0]}n[m++]=_.r,n[m++]=_.g,n[m++]=_.b,n[m]=_.a}}})(qd)),qd}var V2;function JI(){return V2||(V2=1,(function(e){const t=F2();function r(o,s,a){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=a,s.width=a,s.style.height=a+"px",s.style.width=a+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,a,i){let l=i,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),f=c.getContext("2d"),p=f.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(f,c,u),f.putImageData(p,0,0),c},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=e.render(s,a,l),u=l.type||"image/png",f=l.rendererOpts||{};return c.toDataURL(u,f.quality)}})(Ad)),Ad}var Ld={},H2;function KI(){if(H2)return Ld;H2=1;const e=F2();function t(o,s){const a=o.a/255,i=s+'="'+o.hex+'"';return a<1?i+" "+s+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(o,s,a){let i=o+s;return typeof a<"u"&&(i+=" "+a),i}function n(o,s,a){let i="",l=0,c=!1,u=0;for(let f=0;f<o.length;f++){const p=Math.floor(f%s),h=Math.floor(f/s);!p&&!c&&(c=!0),o[f]?(u++,f>0&&p>0&&o[f-1]||(i+=c?r("M",p+a,.5+h+a):r("m",l,0),l=0,c=!1),p+1<s&&o[f+1]||(i+=r("h",u),u=0)):l++}return i}return Ld.render=function(s,a,i){const l=e.getOptions(a),c=s.modules.size,u=s.modules.data,f=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',m='viewBox="0 0 '+f+" "+f+'"',y='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+m+' shape-rendering="crispEdges">'+p+h+`</svg>
50
- `;return typeof i=="function"&&i(null,y),y},Ld}var B2;function YI(){if(B2)return Bo;B2=1;const e=PI(),t=GI(),r=JI(),n=KI();function o(s,a,i,l,c){const u=[].slice.call(arguments,1),f=u.length,p=typeof u[f-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(f<2)throw new Error("Too few arguments provided");f===2?(c=i,i=a,a=l=void 0):f===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(i=a,a=l=void 0):f===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(h,m){try{const _=t.create(i,l);h(s(_,a,l))}catch(_){m(_)}})}try{const h=t.create(i,l);c(null,s(h,a,l))}catch(h){c(h)}}return Bo.create=t.create,Bo.toCanvas=o.bind(null,r.render),Bo.toDataURL=o.bind(null,r.renderToDataURL),Bo.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),Bo}var QI=YI();const W2=Vn(QI);class G2{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=r,this.margin=n,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return W2.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return W2.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const XI={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class e5{constructor(t,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof t=="string"?document.querySelector(t):t,!this.el)throw new Error("Tooltip: invalid element");this.opts={...XI,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
48
+ Minimum version required to store current data is: `+O+`.
49
+ `);const q=y(x,R,L),z=e.getSymbolSize(x),H=new n(z);return h(H,x),m(H),_(H,x),w(H,R,0),x>=7&&g(H,x),v(H,q),isNaN(C)&&(C=a.getBestMask(H,w.bind(null,H,R))),a.applyMask(C,H),w(H,R,C),{modules:H,version:x,errorCorrectionLevel:R,maskPattern:C,segments:L}}return _d.create=function(x,R){if(typeof x>"u"||x==="")throw new Error("No input text");let C=t.M,L,O;return typeof R<"u"&&(C=t.from(R.errorCorrectionLevel,t.M),L=c.from(R.version),O=a.from(R.maskPattern),R.toSJISFunc&&e.setToSJISFunction(R.toSJISFunc)),b(x,L,C,O)},_d}var Dd={},Ud={},H2;function B2(){return H2||(H2=1,(function(e){function t(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let n=r.slice().replace("#","").split("");if(n.length<3||n.length===5||n.length>8)throw new Error("Invalid hex color: "+r);(n.length===3||n.length===4)&&(n=Array.prototype.concat.apply([],n.map(function(s){return[s,s]}))),n.length===6&&n.push("F","F");const o=parseInt(n.join(""),16);return{r:o>>24&255,g:o>>16&255,b:o>>8&255,a:o&255,hex:"#"+n.slice(0,6).join("")}}e.getOptions=function(n){n||(n={}),n.color||(n.color={});const o=typeof n.margin>"u"||n.margin===null||n.margin<0?4:n.margin,s=n.width&&n.width>=21?n.width:void 0,a=n.scale||4;return{width:s,scale:s?4:a,margin:o,color:{dark:t(n.color.dark||"#000000ff"),light:t(n.color.light||"#ffffffff")},type:n.type,rendererOpts:n.rendererOpts||{}}},e.getScale=function(n,o){return o.width&&o.width>=n+o.margin*2?o.width/(n+o.margin*2):o.scale},e.getImageWidth=function(n,o){const s=e.getScale(n,o);return Math.floor((n+o.margin*2)*s)},e.qrToImageData=function(n,o,s){const a=o.modules.size,i=o.modules.data,l=e.getScale(a,s),c=Math.floor((a+s.margin*2)*l),u=s.margin*l,f=[s.color.light,s.color.dark];for(let p=0;p<c;p++)for(let h=0;h<c;h++){let m=(p*c+h)*4,_=s.color.light;if(p>=u&&h>=u&&p<c-u&&h<c-u){const g=Math.floor((p-u)/l),w=Math.floor((h-u)/l);_=f[i[g*a+w]?1:0]}n[m++]=_.r,n[m++]=_.g,n[m++]=_.b,n[m]=_.a}}})(Ud)),Ud}var J2;function s6(){return J2||(J2=1,(function(e){const t=B2();function r(o,s,a){o.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=a,s.width=a,s.style.height=a+"px",s.style.width=a+"px"}function n(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}e.render=function(s,a,i){let l=i,c=a;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),a||(c=n()),l=t.getOptions(l);const u=t.getImageWidth(s.modules.size,l),f=c.getContext("2d"),p=f.createImageData(u,u);return t.qrToImageData(p.data,s,l),r(f,c,u),f.putImageData(p,0,0),c},e.renderToDataURL=function(s,a,i){let l=i;typeof l>"u"&&(!a||!a.getContext)&&(l=a,a=void 0),l||(l={});const c=e.render(s,a,l),u=l.type||"image/png",f=l.rendererOpts||{};return c.toDataURL(u,f.quality)}})(Dd)),Dd}var zd={},W2;function a6(){if(W2)return zd;W2=1;const e=B2();function t(o,s){const a=o.a/255,i=s+'="'+o.hex+'"';return a<1?i+" "+s+'-opacity="'+a.toFixed(2).slice(1)+'"':i}function r(o,s,a){let i=o+s;return typeof a<"u"&&(i+=" "+a),i}function n(o,s,a){let i="",l=0,c=!1,u=0;for(let f=0;f<o.length;f++){const p=Math.floor(f%s),h=Math.floor(f/s);!p&&!c&&(c=!0),o[f]?(u++,f>0&&p>0&&o[f-1]||(i+=c?r("M",p+a,.5+h+a):r("m",l,0),l=0,c=!1),p+1<s&&o[f+1]||(i+=r("h",u),u=0)):l++}return i}return zd.render=function(s,a,i){const l=e.getOptions(a),c=s.modules.size,u=s.modules.data,f=c+l.margin*2,p=l.color.light.a?"<path "+t(l.color.light,"fill")+' d="M0 0h'+f+"v"+f+'H0z"/>':"",h="<path "+t(l.color.dark,"stroke")+' d="'+n(u,c,l.margin)+'"/>',m='viewBox="0 0 '+f+" "+f+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(l.width?'width="'+l.width+'" height="'+l.width+'" ':"")+m+' shape-rendering="crispEdges">'+p+h+`</svg>
50
+ `;return typeof i=="function"&&i(null,g),g},zd}var G2;function i6(){if(G2)return es;G2=1;const e=zI(),t=o6(),r=s6(),n=a6();function o(s,a,i,l,c){const u=[].slice.call(arguments,1),f=u.length,p=typeof u[f-1]=="function";if(!p&&!e())throw new Error("Callback required as last argument");if(p){if(f<2)throw new Error("Too few arguments provided");f===2?(c=i,i=a,a=l=void 0):f===3&&(a.getContext&&typeof c>"u"?(c=l,l=void 0):(c=l,l=i,i=a,a=void 0))}else{if(f<1)throw new Error("Too few arguments provided");return f===1?(i=a,a=l=void 0):f===2&&!a.getContext&&(l=i,i=a,a=void 0),new Promise(function(h,m){try{const _=t.create(i,l);h(s(_,a,l))}catch(_){m(_)}})}try{const h=t.create(i,l);c(null,s(h,a,l))}catch(h){c(h)}}return es.create=t.create,es.toCanvas=o.bind(null,r.render),es.toDataURL=o.bind(null,r.renderToDataURL),es.toString=o.bind(null,function(s,a,i){return n.render(s,i)}),es}var l6=i6();const K2=Wn(l6);class Y2{constructor(t,{size:r=200,margin:n=4,color:o="#000",bgColor:s="#fff"}){this.value=t,this.size=r,this.margin=n,this.color=o,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return K2.toDataURL(this.value,this.qrCodeOption)}async toCanvas(t){return K2.toCanvas(t,this.value,this.qrCodeOption)}async toImage(t){t.src=await this.toDataURL()}}const c6={content:"",placement:"top",trigger:"hover",delay:150,hideDelay:150,container:document.body,className:"tiny-remoter-native-tooltip"};class u6{constructor(t,r={}){if(this.tip=null,this.showTimer=0,this.hideTimer=0,this.clickOutside=null,this.el=typeof t=="string"?document.querySelector(t):t,!this.el)throw new Error("Tooltip: invalid element");this.opts={...c6,...r},this.bindEvents()}open(){this.isShown()||(this.clearTimer(),this.showTimer=window.setTimeout(()=>{this.render(),this.opts.container.appendChild(this.tip),this.reposition(),this.attachExtraEvents()},this.opts.delay))}close(){this.clearTimer(),this.hideTimer=window.setTimeout(()=>{this.tip?.remove(),this.detachExtraEvents()},this.opts.hideDelay)}toggle(){this.isShown()?this.close():this.open()}destroy(){this.close();const t=this.opts.trigger;this.el.removeEventListener("mouseenter",this.open),this.el.removeEventListener("mouseleave",this.close),this.el.removeEventListener("focus",this.open),this.el.removeEventListener("blur",this.close),t==="click"&&this.el.removeEventListener("click",this.toggle)}bindEvents(){const t=this.opts.trigger;t==="hover"?(this.el.addEventListener("mouseenter",()=>this.open()),this.el.addEventListener("mouseleave",()=>this.close())):t==="focus"?(this.el.addEventListener("focus",()=>this.open()),this.el.addEventListener("blur",()=>this.close())):t==="click"&&this.el.addEventListener("click",()=>this.toggle())}render(){if(this.tip)return;const t=typeof this.opts.content=="function"?this.opts.content():this.opts.content;this.tip=document.createElement("div"),this.tip.className=`${this.opts.className} ${this.opts.className}--${this.opts.placement}`,this.tip.innerHTML=`
51
51
  <div class="${this.opts.className}__arrow"></div>
52
52
  <div class="${this.opts.className}__inner">${t}</div>
53
- `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,l="center"]=t.split("-");let c=0,u=0;return i==="top"?c=r.top+o-n.height-a:i==="bottom"?c=r.bottom+o+a:i==="left"?u=r.left+s-n.width-a:i==="right"&&(u=r.right+s+a),(i==="top"||i==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(i==="left"||i==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+a.width<=o-5&&t+a.height<=s-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const J2="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(J2))return;const e=document.createElement("style");e.id=J2,e.textContent=`
53
+ `}reposition(){const t=this.placementList(this.opts.placement);for(const r of t){const n=this.calcStyle(r);if(this.checkViewport(n)){this.applyStyle(n),this.tip.className=`${this.opts.className} ${this.opts.className}--${r}`;return}}this.applyStyle(this.calcStyle("top"))}calcStyle(t){const r=this.el.getBoundingClientRect(),n=this.tip.getBoundingClientRect(),o=window.pageYOffset||document.documentElement.scrollTop,s=window.pageXOffset||document.documentElement.scrollLeft,a=6,[i,l="center"]=t.split("-");let c=0,u=0;return i==="top"?c=r.top+o-n.height-a:i==="bottom"?c=r.bottom+o+a:i==="left"?u=r.left+s-n.width-a:i==="right"&&(u=r.right+s+a),(i==="top"||i==="bottom")&&(l==="start"?u=r.left+s:l==="end"?u=r.right+s-n.width:u=(r.left+r.right)/2+s-n.width/2),(i==="left"||i==="right")&&(l==="start"?c=r.top+o:l==="end"?c=r.bottom+o-n.height:c=(r.top+r.bottom)/2+o-n.height/2),{top:Math.round(c),left:Math.round(u)}}applyStyle({top:t,left:r}){Object.assign(this.tip.style,{position:"absolute",top:`${t}px`,left:`${r}px`})}checkViewport({top:t,left:r}){const o=window.innerWidth,s=window.innerHeight,a=this.tip.getBoundingClientRect();return r>=5&&t>=5&&r+a.width<=o-5&&t+a.height<=s-5}placementList(t){const r={top:["top","bottom","top-start","bottom-start","top-end","bottom-end"],bottom:["bottom","top","bottom-start","top-start","bottom-end","top-end"],left:["left","right","left-start","right-start","left-end","right-end"],right:["right","left","right-start","left-start","right-end","left-end"]};return r[t.split("-")[0]]||r.top}attachExtraEvents(){this.opts.trigger==="click"?(this.clickOutside=t=>{const r=t.composedPath();!r.includes(this.el)&&!r.includes(this.tip)&&this.close()},document.addEventListener("mousedown",this.clickOutside)):this.opts.trigger==="hover"&&(this.tip.addEventListener("mouseenter",()=>this.clearTimer()),this.tip.addEventListener("mouseleave",()=>this.close()))}detachExtraEvents(){this.clickOutside&&(document.removeEventListener("mousedown",this.clickOutside),this.clickOutside=null)}clearTimer(){clearTimeout(this.showTimer),clearTimeout(this.hideTimer)}isShown(){return!!this.tip?.parentNode}}const Q2="tiny-remoter-native-tooltip-style";(()=>{if(document.getElementById(Q2))return;const e=document.createElement("style");e.id=Q2,e.textContent=`
54
54
  .tiny-remoter-native-tooltip {
55
55
  position: absolute;
56
56
  z-index: 9999;
@@ -97,7 +97,7 @@ Minimum version required to store current data is: `+N+`.
97
97
  transform: translateY(-50%);
98
98
  border-right-color: rgba(0,0,0,.75);
99
99
  }
100
- `,document.head.appendChild(e)})();const K2="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2039.9692'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='39.969238'%20fill='none'%20customFrame='url(%23clipPath_3)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_3'%3e%3crect%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_4'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_5'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_6'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_7'%3e%3crect%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_8'%3e%3crect%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='2'%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(239,246,255)'%20/%3e%3cg%20id='物业'%20clip-path='url(%23clipPath_4)'%20customFrame='url(%23clipPath_4)'%3e%3crect%20id='物业'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20/%3e%3cg%20id='物业服务'%3e%3cg%20id='00公共/红点/图标+红点'%20customFrame='url(%23clipPath_5)'%3e%3crect%20id='00公共/红点/图标+红点'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cg%20id='common_chats_line'%20customFrame='url(%23clipPath_6)'%3e%3crect%20id='common_chats_line'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cpath%20id='形状'%20d='M28.3332%2019.9847C28.3332%2015.3823%2024.6022%2011.6514%2019.9998%2011.6514C15.3975%2011.6514%2011.6665%2015.3823%2011.6665%2019.9847C11.6665%2024.5871%2015.3975%2028.318%2019.9998%2028.318C21.0018%2028.318%2021.9624%2028.1412%2022.8522%2027.8171L26.581%2028.1578C26.7205%2028.1706%2026.8611%2028.1598%2026.9971%2028.1259C27.6669%2027.959%2028.0746%2027.2806%2027.9077%2026.6108L27.2716%2024.0578C27.9477%2022.8535%2028.3332%2021.4641%2028.3332%2019.9847ZM19.9998%2013.1514C16.2259%2013.1514%2013.1665%2016.2108%2013.1665%2019.9847C13.1665%2023.7586%2016.2259%2026.818%2019.9998%2026.818C20.8089%2026.818%2021.5967%2026.678%2022.3388%2026.4077C22.505%2026.3471%2022.6803%2026.3166%2022.8565%2026.3171L22.9887%2026.3233L26.3665%2026.6322L25.8161%2024.4205C25.7352%2024.0958%2025.7655%2023.7548%2025.8997%2023.4512L25.9636%2023.3236C26.5311%2022.3126%2026.8332%2021.1723%2026.8332%2019.9847C26.8332%2016.2108%2023.7738%2013.1514%2019.9998%2013.1514ZM23.1152%2021.2468C23.352%2020.9069%2023.2684%2020.4394%2022.9286%2020.2026C22.5887%2019.9659%2022.1212%2020.0494%2021.8845%2020.3893C21.2894%2021.2433%2020.4268%2021.7347%2019.5102%2021.7347C18.9513%2021.7347%2018.4132%2021.554%2017.9375%2021.2122C17.6011%2020.9705%2017.1325%2021.0472%2016.8908%2021.3836C16.6491%2021.7199%2016.7258%2022.1886%2017.0622%2022.4303C17.7879%2022.9518%2018.6305%2023.2347%2019.5102%2023.2347C20.9394%2023.2347%2022.2505%2022.4878%2023.1152%2021.2468Z'%20fill='rgb(65,142,255)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3cg%20id='00公共/3位数红点'%20opacity='0'%20customFrame='url(%23clipPath_7)'%3e%3crect%20id='00公共/3位数红点'%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20opacity='0'%20fill='rgb(243,111,100)'%20/%3e%3cpath%20id='文本'%20d='M26.0421%2013.4421C26.4259%2013.4421%2026.7677%2013.5255%2027.0675%2013.6923C27.3672%2013.8591%2027.6005%2014.0931%2027.7673%2014.3942C27.9342%2014.694%2028.0176%2015.0351%2028.0176%2015.4176C28.0176%2015.7173%2027.9633%2015.994%2027.8548%2016.2476C27.7463%2016.4999%2027.5673%2016.8315%2027.3177%2017.2425L25.859%2019.6432L25.0167%2019.6432L26.276%2017.5924C26.3534%2017.4704%2026.4307%2017.3564%2026.508%2017.2507C26.3357%2017.3063%2026.1445%2017.3341%2025.9342%2017.3341C25.5721%2017.3341%2025.2493%2017.2479%2024.9658%2017.0757C24.6837%2016.9034%2024.4633%2016.6701%2024.3046%2016.3758C24.1459%2016.0815%2024.0666%2015.7566%2024.0666%2015.4013C24.0666%2015.0351%2024.1513%2014.7021%2024.3209%2014.4023C24.4904%2014.1012%2024.7264%2013.8659%2025.0289%2013.6964C25.3314%2013.5268%2025.6691%2013.4421%2026.0421%2013.4421ZM26.0421%2016.6505C26.4029%2016.6505%2026.6904%2016.5325%2026.9047%2016.2965C27.119%2016.0605%2027.2262%2015.7539%2027.2262%2015.3769C27.2262%2014.9985%2027.119%2014.694%2026.9047%2014.4634C26.6904%2014.2328%2026.4029%2014.1175%2026.0421%2014.1175C25.6867%2014.1175%2025.4019%2014.2342%2025.1876%2014.4674C24.9733%2014.7007%2024.8661%2015.0039%2024.8661%2015.3769C24.8661%2015.7539%2024.9719%2016.0605%2025.1835%2016.2965C25.3951%2016.5325%2025.6813%2016.6505%2026.0421%2016.6505ZM30.7921%2013.4421C31.1759%2013.4421%2031.5177%2013.5255%2031.8175%2013.6923C32.1172%2013.8591%2032.3505%2014.0931%2032.5173%2014.3942C32.6842%2014.694%2032.7676%2015.0351%2032.7676%2015.4176C32.7676%2015.7173%2032.7133%2015.994%2032.6048%2016.2476C32.4963%2016.4999%2032.3173%2016.8315%2032.0677%2017.2425L30.609%2019.6432L29.7667%2019.6432L31.026%2017.5924C31.1034%2017.4704%2031.1807%2017.3564%2031.258%2017.2507C31.0857%2017.3063%2030.8945%2017.3341%2030.6842%2017.3341C30.3221%2017.3341%2029.9993%2017.2479%2029.7158%2017.0757C29.4337%2016.9034%2029.2133%2016.6701%2029.0546%2016.3758C28.8959%2016.0815%2028.8166%2015.7566%2028.8166%2015.4013C28.8166%2015.0351%2028.9013%2014.7021%2029.0709%2014.4023C29.2404%2014.1012%2029.4764%2013.8659%2029.7789%2013.6964C30.0814%2013.5268%2030.4191%2013.4421%2030.7921%2013.4421ZM30.7921%2016.6505C31.1529%2016.6505%2031.4404%2016.5325%2031.6547%2016.2965C31.869%2016.0605%2031.9762%2015.7539%2031.9762%2015.3769C31.9762%2014.9985%2031.869%2014.694%2031.6547%2014.4634C31.4404%2014.2328%2031.1529%2014.1175%2030.7921%2014.1175C30.4367%2014.1175%2030.1519%2014.2342%2029.9376%2014.4674C29.7233%2014.7007%2029.6161%2015.0039%2029.6161%2015.3769C29.6161%2015.7539%2029.7219%2016.0605%2029.9335%2016.2965C30.1451%2016.5325%2030.4313%2016.6505%2030.7921%2016.6505ZM35.2674%2014.6851L35.9001%2014.6851L35.9001%2016.3188L37.5339%2016.3188L37.5339%2016.9516L35.9001%2016.9516L35.9001%2018.5853L35.2674%2018.5853L35.2674%2016.9516L33.6337%2016.9516L33.6337%2016.3188L35.2674%2016.3188L35.2674%2014.6851Z'%20fill='rgb(255,255,255)'%20fill-rule='nonzero'%20/%3e%3c/g%3e%3cg%20id='00公共/单红点'%20opacity='0'%20customFrame='url(%23clipPath_8)'%3e%3crect%20id='00公共/单红点'%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20opacity='0'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3ccircle%20id='红点'%20cx='26.6668301'%20cy='13.3179522'%20r='3.33333325'%20fill='rgb(243,111,100)'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",Y2="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_12)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_12'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_13'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_14'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='4'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(234,255,244)'%20/%3e%3cg%20id='我的信息'%20clip-path='url(%23clipPath_13)'%20customFrame='url(%23clipPath_13)'%3e%3crect%20id='我的信息'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='组合%208'%20customFrame='url(%23clipPath_14)'%3e%3crect%20id='组合%208'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='合并'%20d='M28.4994%2012.3142C28.4994%2012.2578%2028.4937%2012.2018%2028.4825%2012.1465C28.4713%2012.0911%2028.4547%2012.0373%2028.4327%2011.9851C28.4107%2011.933%2028.3836%2011.8835%2028.3516%2011.8365C28.3197%2011.7896%2028.2834%2011.7461%2028.2427%2011.7062C28.202%2011.6663%2028.1579%2011.6307%2028.1101%2011.5993C28.0622%2011.568%2028.0117%2011.5415%2027.9585%2011.5199C27.9054%2011.4983%2027.8506%2011.4819%2027.7942%2011.4709C27.7378%2011.4599%2027.6806%2011.4544%2027.6231%2011.4544L24.1832%2011.5199L24.1832%2010L29.0796%2010C29.1472%2010%2029.2143%2010.0065%2029.2806%2010.0194C29.347%2010.0324%2029.4114%2010.0516%2029.4739%2010.077C29.5364%2010.1024%2029.5961%2010.1336%2029.6523%2010.1705C29.7086%2010.2074%2029.7605%2010.2493%2029.8084%2010.2963C29.8562%2010.3433%2029.8991%2010.3944%2029.9367%2010.4496C29.9743%2010.5048%2030.006%2010.5631%2030.0319%2010.6244C30.0578%2010.6858%2030.0773%2010.7491%2030.0905%2010.8142C30.1037%2010.8794%2030.1104%2010.9451%2030.1104%2011.0115L30.1832%2014.4522L28.4992%2014.5L28.4994%2012.3142ZM11.6995%2012.3143C11.6995%2012.2579%2011.7051%2012.2019%2011.7163%2012.1466C11.7275%2012.0912%2011.7441%2012.0374%2011.7661%2011.9852C11.7882%2011.9331%2011.8152%2011.8836%2011.8472%2011.8366C11.8791%2011.7897%2011.9155%2011.7462%2011.9562%2011.7063C11.9968%2011.6664%2012.0409%2011.6308%2012.0888%2011.5994C12.1366%2011.5681%2012.1871%2011.5416%2012.2403%2011.52C12.2934%2011.4984%2012.3482%2011.482%2012.4046%2011.471C12.4611%2011.46%2012.5182%2011.4545%2012.5758%2011.4545L16.0157%2011.52L16.0157%2010.0001L11.1193%2010.0001C11.0516%2010.0001%2010.9846%2010.0066%2010.9182%2010.0196C10.8518%2010.0325%2010.7874%2010.0517%2010.7249%2010.0771C10.6624%2010.1025%2010.6028%2010.1337%2010.5465%2010.1706C10.4902%2010.2075%2010.4383%2010.2494%2010.3904%2010.2964C10.3426%2010.3434%2010.2997%2010.3945%2010.2621%2010.4497C10.2245%2010.5049%2010.1929%2010.5632%2010.167%2010.6245C10.1411%2010.6859%2010.1215%2010.7492%2010.1083%2010.8143C10.0951%2010.8795%2010.0885%2010.9452%2010.0884%2011.0116L10.0157%2014.4523L11.6997%2014.5L11.6995%2012.3143ZM25.3135%2021.8051L25.3135%2022.8167C25.7656%2022.8929%2026.2209%2022.9249%2026.6792%2022.9127C28.3381%2022.9127%2029.1675%2022.326%2029.1675%2021.1527C29.1733%2020.9869%2029.151%2020.825%2029.1006%2020.667C29.0503%2020.509%2028.9747%2020.3641%2028.8742%2020.2322C28.767%2020.1025%2028.6403%2019.9963%2028.4938%2019.9134C28.3474%2019.8306%2028.191%2019.7767%2028.0246%2019.7517L28.0246%2019.7011C28.0971%2019.6839%2028.1676%2019.6606%2028.236%2019.6311C28.3044%2019.6016%2028.3698%2019.5665%2028.4321%2019.5257C28.4944%2019.4848%2028.5526%2019.4389%2028.6069%2019.3879C28.6613%2019.3369%2028.7109%2019.2816%2028.7556%2019.222C28.8003%2019.1624%2028.8394%2019.0994%2028.8732%2019.033C28.9069%2018.9665%2028.9346%2018.8977%2028.9564%2018.8265C28.9782%2018.7552%2028.9937%2018.6826%2029.0028%2018.6086C29.0119%2018.5347%2029.0145%2018.4605%2029.0107%2018.3861C29.0217%2018.2675%2029.0176%2018.1495%2028.9984%2018.0319C28.9791%2017.9144%2028.9454%2017.8012%2028.8971%2017.6923C28.8489%2017.5834%2028.7875%2017.4823%2028.7134%2017.3891C28.6393%2017.2959%2028.5547%2017.2135%2028.4595%2017.1419C28.219%2017.0003%2027.963%2016.8972%2027.6915%2016.8326C27.4199%2016.7679%2027.1449%2016.7446%2026.8664%2016.7626C26.6258%2016.7621%2026.3864%2016.7791%2026.1482%2016.8132C25.9479%2016.8386%2025.7504%2016.8791%2025.5563%2016.9346L25.5563%2017.8854C25.743%2017.8264%2025.9337%2017.7842%2026.128%2017.759C26.3276%2017.73%2026.5282%2017.7148%2026.7298%2017.7134C27.0252%2017.6949%2027.3049%2017.7523%2027.5692%2017.8854C27.6168%2017.9161%2027.6595%2017.9525%2027.6972%2017.9947C27.7348%2018.037%2027.766%2018.0835%2027.791%2018.1343C27.816%2018.1851%2027.8337%2018.2383%2027.8441%2018.294C27.8545%2018.3496%2027.8573%2018.4056%2027.8525%2018.462C27.8566%2018.5278%2027.8514%2018.5927%2027.8367%2018.657C27.822%2018.7212%2027.7986%2018.7821%2027.7663%2018.8395C27.734%2018.897%2027.694%2018.9487%2027.6468%2018.9946C27.5995%2019.0405%2027.5468%2019.0787%2027.4885%2019.1093C27.1544%2019.2631%2026.8037%2019.3306%2026.4364%2019.3117L25.9862%2019.3117L25.9862%2020.1917L26.4466%2020.1917C26.8409%2020.1669%2027.2202%2020.2309%2027.5845%2020.3839C27.6459%2020.4167%2027.7011%2020.4576%2027.7505%2020.5066C27.7999%2020.5556%2027.8412%2020.6107%2027.8745%2020.6718C27.9077%2020.733%2027.9315%2020.7976%2027.9458%2020.8656C27.9602%2020.9337%2027.9644%2021.0024%2027.9587%2021.0717C27.9648%2021.1402%2027.9612%2021.2083%2027.9478%2021.2757C27.9344%2021.3432%2027.912%2021.4074%2027.8801%2021.4683C27.8483%2021.5293%2027.8086%2021.5846%2027.7609%2021.6341C27.7132%2021.6837%2027.6593%2021.7254%2027.5996%2021.7596C27.2884%2021.9045%2026.9613%2021.9685%2026.6184%2021.9518C26.1786%2021.9465%2025.7436%2021.8977%2025.3135%2021.8051ZM21.3382%2018.6238C21.3445%2018.5593%2021.343%2018.495%2021.3335%2018.4308C21.3241%2018.3667%2021.3069%2018.3046%2021.2822%2018.2447C21.2575%2018.1847%2021.226%2018.1287%2021.1876%2018.0765C21.1492%2018.0242%2021.1049%2017.9774%2021.055%2017.936C20.9359%2017.8608%2020.808%2017.806%2020.6714%2017.7714C20.5349%2017.7368%2020.3964%2017.7242%2020.2558%2017.7337C19.8009%2017.7395%2019.356%2017.8087%2018.9208%2017.9411L18.9208%2016.9598C19.4252%2016.8181%2019.9393%2016.7524%2020.4633%2016.7626C20.7322%2016.7484%2020.9964%2016.7773%2021.256%2016.8491C21.5156%2016.9209%2021.7571%2017.032%2021.9806%2017.1824C22.0729%2017.2601%2022.1548%2017.3474%2022.2263%2017.4446C22.2978%2017.5418%2022.3567%2017.646%2022.4034%2017.7573C22.45%2017.8686%2022.483%2017.9838%2022.5021%2018.1029C22.5213%2018.222%2022.5261%2018.3417%2022.5167%2018.462C22.5245%2018.7882%2022.4655%2019.1017%2022.3396%2019.4027C22.1879%2019.7384%2021.984%2020.0384%2021.7277%2020.3029C21.3021%2020.7337%2020.8502%2021.135%2020.3721%2021.5067L19.9928%2021.8051L19.9928%2021.8759L22.6938%2021.8759L22.6938%2022.8419L18.5464%2022.8419L18.5464%2021.7697C19.2882%2021.1796%2019.8579%2020.6975%2020.2558%2020.3232C20.574%2020.0432%2020.8523%2019.728%2021.0905%2019.3774C21.1675%2019.2665%2021.2269%2019.1469%2021.2691%2019.0187C21.3113%2018.8904%2021.3344%2018.7588%2021.3382%2018.6238ZM12.3102%2017.2127L12.3102%2018.1939L13.7769%2017.9107L13.7769%2022.8419L14.9605%2022.8419L14.9605%2016.8486L14.0957%2016.8486L12.3102%2017.2127ZM28.5524%2028.0475C28.5524%2028.104%2028.5467%2028.1599%2028.5353%2028.2152C28.5239%2028.2706%2028.5071%2028.3244%2028.4849%2028.3766C28.4626%2028.4287%2028.4352%2028.4782%2028.4028%2028.5252C28.3705%2028.5721%2028.3337%2028.6156%2028.2925%2028.6555C28.2513%2028.6954%2028.2067%2028.731%2028.1583%2028.7624C28.1098%2028.7937%2028.0587%2028.8202%2028.0049%2028.8418C27.9511%2028.8634%2027.8957%2028.8798%2027.8385%2028.8908C27.7814%2028.9018%2027.7235%2028.9073%2027.6653%2028.9073L24.1832%2028.8418L24.1832%2030.3617L29.1397%2030.3617C29.2082%2030.3617%2029.276%2030.3552%2029.3432%2030.3423C29.4104%2030.3293%2029.4756%2030.3101%2029.5389%2030.2847C29.6022%2030.2593%2029.6625%2030.2281%2029.7195%2030.1912C29.7765%2030.1543%2029.829%2030.1124%2029.8774%2030.0654C29.9259%2030.0184%2029.9693%2029.9673%2030.0074%2029.9121C30.0454%2029.8569%2030.0774%2029.7986%2030.1037%2029.7373C30.1299%2029.6759%2030.1497%2029.6126%2030.163%2029.5475C30.1764%2029.4823%2030.1831%2029.4166%2030.1832%2029.3502L30.1832%2026.0478L28.4785%2026L28.5524%2028.0475ZM11.6308%2028.0099C11.6308%2028.0664%2011.6365%2028.1223%2011.6479%2028.1777C11.6592%2028.233%2011.676%2028.2868%2011.6983%2028.339C11.7206%2028.3911%2011.748%2028.4406%2011.7803%2028.4876C11.8127%2028.5345%2011.8495%2028.578%2011.8906%2028.6179C11.9318%2028.6578%2011.9765%2028.6934%2012.0249%2028.7248C12.0733%2028.7562%2012.1244%2028.7826%2012.1783%2028.8042C12.2321%2028.8259%2012.2875%2028.8422%2012.3446%2028.8532C12.4017%2028.8642%2012.4596%2028.8697%2012.5178%2028.8698L16%2028.8042L16%2030.3241L11.0435%2030.3241C10.975%2030.3241%2010.9071%2030.3176%2010.8399%2030.3047C10.7727%2030.2917%2010.7076%2030.2725%2010.6443%2030.2471C10.581%2030.2217%2010.5206%2030.1906%2010.4637%2030.1537C10.4067%2030.1168%2010.3542%2030.0748%2010.3057%2030.0278C10.2573%2029.9809%2010.2138%2029.9298%2010.1758%2029.8745C10.1377%2029.8193%2010.1057%2029.7611%2010.0795%2029.6997C10.0533%2029.6383%2010.0335%2029.575%2010.0201%2029.5099C10.0068%2029.4448%2010%2029.379%2010%2029.3126L10%2026.0478L11.7047%2026L11.6308%2028.0099Z'%20fill='rgb(14,191,241)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/svg%3e",Q2="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_9)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_9'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_10'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_11'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='3'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='画板%202310'%20customFrame='url(%23clipPath_10)'%3e%3crect%20id='画板%202310'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='人事服务'%3e%3cg%20id='ic_public_link'%20clip-path='url(%23clipPath_11)'%20customFrame='url(%23clipPath_11)'%3e%3crect%20id='ic_public_link'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='path1'%20d='M9.9999%2019.9917C9.9999%2018.4292%209.99573%2016.8667%209.9999%2015.3042C9.99573%2014.5459%2010.0916%2013.7917%2010.2749%2013.0626C10.6874%2011.5126%2011.6957%2010.5917%2013.2457%2010.2334C14.0207%2010.0667%2014.8166%209.98756%2015.6082%2010.0001C18.6041%2010.0001%2021.5999%2010.0001%2024.5999%2010.0001C25.3541%209.99589%2026.1082%2010.0792%2026.8457%2010.2584C28.4416%2010.6459%2029.3999%2011.6584%2029.7624%2013.2501C29.9291%2014.0001%2030.0041%2014.7667%2029.9957%2015.5376C29.9957%2018.5667%2029.9957%2021.5959%2029.9957%2024.6209C29.9999%2025.3709%2029.9166%2026.1209%2029.7416%2026.8459C29.3499%2028.4459%2028.3332%2029.3959%2026.7457%2029.7626C25.9666%2029.9292%2025.1749%2030.0084%2024.3791%2029.9959C21.3957%2029.9959%2018.4124%2029.9959%2015.4291%2029.9959C14.6666%2030.0042%2013.9082%2029.9167%2013.1666%2029.7417C11.5624%2029.3542%2010.5999%2028.3376%2010.2374%2026.7376C10.0499%2025.9251%209.9999%2025.1126%209.9999%2024.2917C9.9999%2022.8584%209.9999%2021.4251%209.9999%2019.9917Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path3'%20d='M25.0333%2021.8666L26.9%2020C28.8083%2018.0916%2028.8083%2015%2026.9%2013.0958C24.9958%2011.1875%2021.9041%2011.1875%2020%2013.0958L18.1291%2014.9625M21.8666%2025.0333L20%2026.9C18.0916%2028.8083%2015%2028.8083%2013.0958%2026.9C11.1875%2024.9958%2011.1875%2021.9041%2013.0958%2020L14.9625%2018.1291'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='pah4'%20d='M18.125%2021.875L21.875%2018.125'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='path5'%20d='M25.8207%2019.2626L24.0457%2021.0376C23.7998%2021.2834%2023.6748%2021.5292%2023.6748%2021.7751C23.6748%2022.0209%2023.7998%2022.2667%2024.0457%2022.5126C24.1498%2022.6167%2024.2665%2022.6959%2024.3915%2022.7459C24.5123%2022.7917%2024.6415%2022.8167%2024.779%2022.8167C24.9207%2022.8167%2025.0498%2022.7917%2025.1665%2022.7459C25.2957%2022.6959%2025.4123%2022.6167%2025.5165%2022.5126L27.2915%2020.7334C27.8165%2020.2126%2028.2165%2019.6334%2028.4957%2019.0001C28.5082%2018.9667%2028.5248%2018.9334%2028.5373%2018.8959C28.554%2018.8626%2028.5665%2018.8292%2028.579%2018.7917C28.8332%2018.1501%2028.9582%2017.4584%2028.9582%2016.7209C28.9582%2015.9792%2028.8332%2015.2876%2028.579%2014.6459C28.5665%2014.6084%2028.554%2014.5751%2028.5373%2014.5417C28.5248%2014.5042%2028.5082%2014.4709%2028.4957%2014.4376C28.2165%2013.8042%2027.8165%2013.2292%2027.2915%2012.7042C26.7707%2012.1792%2026.1915%2011.7792%2025.5582%2011.5001C25.5248%2011.4876%2025.4915%2011.4709%2025.454%2011.4584C25.4207%2011.4417%2025.3873%2011.4292%2025.354%2011.4167C24.7082%2011.1667%2024.0165%2011.0417%2023.279%2011.0417C22.5373%2011.0417%2021.8457%2011.1667%2021.204%2011.4167C21.1665%2011.4292%2021.1332%2011.4417%2021.0998%2011.4584C21.0623%2011.4709%2021.029%2011.4876%2020.9957%2011.5001C20.3623%2011.7792%2019.7832%2012.1792%2019.2623%2012.7042L17.4832%2014.4792C17.379%2014.5834%2017.2998%2014.7001%2017.2498%2014.8292C17.204%2014.9501%2017.179%2015.0751%2017.179%2015.2167C17.179%2015.3542%2017.204%2015.4834%2017.2498%2015.6042C17.2998%2015.7292%2017.379%2015.8459%2017.4832%2015.9542C17.5915%2016.0584%2017.7082%2016.1376%2017.8332%2016.1876C17.954%2016.2334%2018.0832%2016.2584%2018.2207%2016.2584C18.3623%2016.2584%2018.4915%2016.2334%2018.6082%2016.1876C18.7373%2016.1376%2018.854%2016.0584%2018.9582%2015.9542L20.7332%2014.1751C21.0873%2013.8209%2021.4748%2013.5584%2021.8957%2013.3834C22.3165%2013.2084%2022.779%2013.1251%2023.279%2013.1251C23.7748%2013.1251%2024.2373%2013.2084%2024.6582%2013.3834C25.079%2013.5584%2025.4665%2013.8209%2025.8207%2014.1751C26.1748%2014.5292%2026.4373%2014.9167%2026.6123%2015.3376C26.7873%2015.7584%2026.8748%2016.2167%2026.8748%2016.7209C26.8748%2017.2209%2026.7873%2017.6792%2026.6123%2018.1001C26.4373%2018.5209%2026.1748%2018.9084%2025.8207%2019.2626ZM13.3832%2021.8959C13.5582%2021.4751%2013.8207%2021.0876%2014.1748%2020.7334L15.954%2018.9584C16.0582%2018.8542%2016.1373%2018.7376%2016.1873%2018.6084C16.2332%2018.4876%2016.2582%2018.3626%2016.2582%2018.2209C16.2582%2018.0834%2016.2332%2017.9542%2016.1873%2017.8334C16.1373%2017.7084%2016.0582%2017.5917%2015.954%2017.4834C15.7082%2017.2417%2015.4623%2017.1167%2015.2165%2017.1167C14.9707%2017.1167%2014.7248%2017.2417%2014.479%2017.4834L12.704%2019.2626C12.179%2019.7876%2011.779%2020.3626%2011.4998%2020.9959C11.4873%2021.0292%2011.4707%2021.0626%2011.4582%2021.1001C11.4415%2021.1334%2011.429%2021.1667%2011.4165%2021.2042C11.1665%2021.8459%2011.0415%2022.5376%2011.0415%2023.2792C11.0415%2024.0167%2011.1665%2024.7084%2011.4165%2025.3542C11.429%2025.3876%2011.4415%2025.4209%2011.4582%2025.4584C11.4707%2025.4917%2011.4873%2025.5251%2011.4998%2025.5584C11.779%2026.1917%2012.179%2026.7709%2012.704%2027.2917C13.2248%2027.8167%2013.804%2028.2167%2014.4373%2028.4959C14.4707%2028.5084%2014.504%2028.5251%2014.5415%2028.5376C14.5748%2028.5542%2014.6082%2028.5667%2014.6457%2028.5792C15.2873%2028.8292%2015.979%2028.9584%2016.7207%2028.9584C17.4582%2028.9584%2018.1498%2028.8292%2018.7915%2028.5792C18.829%2028.5667%2018.8623%2028.5542%2018.8957%2028.5376C18.9332%2028.5251%2018.9665%2028.5084%2018.9998%2028.4959C19.6332%2028.2167%2020.2123%2027.8167%2020.7332%2027.2917L22.5123%2025.5167C22.6165%2025.4126%2022.6957%2025.2959%2022.7457%2025.1667C22.7915%2025.0459%2022.8165%2024.9209%2022.8165%2024.7792C22.8165%2024.6417%2022.7915%2024.5126%2022.7457%2024.3917C22.6957%2024.2667%2022.6165%2024.1501%2022.5123%2024.0417C22.2665%2023.8001%2022.0207%2023.6751%2021.7748%2023.6751C21.529%2023.6751%2021.2832%2023.8001%2021.0373%2024.0417L19.2623%2025.8209C18.9082%2026.1751%2018.5207%2026.4376%2018.0998%2026.6126C17.679%2026.7876%2017.2165%2026.8751%2016.7207%2026.8751C16.2207%2026.8751%2015.7582%2026.7876%2015.3373%2026.6126C14.9165%2026.4376%2014.529%2026.1751%2014.1748%2025.8209C13.8207%2025.4667%2013.5582%2025.0792%2013.3832%2024.6584C13.2082%2024.2376%2013.1248%2023.7792%2013.1248%2023.2792C13.1248%2022.7751%2013.2082%2022.3167%2013.3832%2021.8959Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path6'%20d='M21.8127%2016.7458C21.746%2016.7874%2021.6877%2016.8374%2021.6293%2016.8916L16.8918%2021.6291C16.8377%2021.6874%2016.7877%2021.7499%2016.746%2021.8124C16.7127%2021.8624%2016.6877%2021.9166%2016.6627%2021.9749C16.6377%2022.0374%2016.6168%2022.1041%2016.6043%2022.1708C16.5918%2022.2333%2016.5835%2022.2999%2016.5835%2022.3666C16.5835%2022.4333%2016.5918%2022.4999%2016.6043%2022.5666C16.6168%2022.6333%2016.6377%2022.6999%2016.6627%2022.7624C16.6877%2022.8166%2016.7127%2022.8708%2016.746%2022.9208C16.7877%2022.9874%2016.8377%2023.0499%2016.8918%2023.1041C16.946%2023.1583%2017.0085%2023.2083%2017.0752%2023.2499C17.1252%2023.2833%2017.1793%2023.3083%2017.2335%2023.3333C17.3002%2023.3583%2017.3627%2023.3791%2017.4293%2023.3916C17.496%2023.4041%2017.5627%2023.4124%2017.6293%2023.4124C17.696%2023.4124%2017.7627%2023.4041%2017.8252%2023.3916C17.8918%2023.3791%2017.9585%2023.3583%2018.021%2023.3333C18.0793%2023.3083%2018.1335%2023.2833%2018.1835%2023.2499C18.246%2023.2083%2018.3085%2023.1583%2018.3668%2023.1041L23.1043%2018.3666C23.1585%2018.3083%2023.2085%2018.2499%2023.2502%2018.1833C23.2835%2018.1333%2023.3085%2018.0791%2023.3335%2018.0208C23.3585%2017.9583%2023.3793%2017.8916%2023.3918%2017.8249C23.4043%2017.7624%2023.4127%2017.6958%2023.4127%2017.6291C23.4127%2017.5624%2023.4043%2017.4958%2023.3918%2017.4291C23.3793%2017.3624%2023.3585%2017.2999%2023.3335%2017.2333C23.3085%2017.1791%2023.2835%2017.1249%2023.2502%2017.0749C23.2085%2017.0083%2023.1585%2016.9458%2023.1043%2016.8916C23.046%2016.8374%2022.9877%2016.7874%2022.921%2016.7458C22.871%2016.7124%2022.8168%2016.6874%2022.7627%2016.6624C22.696%2016.6374%2022.6335%2016.6166%2022.5668%2016.6041C22.5002%2016.5916%2022.4335%2016.5833%2022.3668%2016.5833C22.3002%2016.5833%2022.2335%2016.5916%2022.171%2016.6041C22.1043%2016.6166%2022.0377%2016.6374%2021.9752%2016.6624C21.9168%2016.6874%2021.8627%2016.7124%2021.8127%2016.7458Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",X2="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_0)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_0'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_1'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_2'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='1'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='车辆'%20clip-path='url(%23clipPath_1)'%20customFrame='url(%23clipPath_1)'%3e%3crect%20id='车辆'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='编组'%3e%3cg%20id='ic_public_qrcode'%20clip-path='url(%23clipPath_2)'%20customFrame='url(%23clipPath_2)'%3e%3crect%20id='ic_public_qrcode'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cg%20id='ic_public_qrcode_1_1'%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_1'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20opacity='0.200000003'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3ccircle%20id='ic_public_qrcode_2_2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='ic_public_qrcode_2_3'%20d='M17.5%2011.25C17.9602%2011.25%2018.3333%2011.6231%2018.3333%2012.0833L18.3333%2017.5C18.3333%2017.9602%2017.9602%2018.3333%2017.5%2018.3333L12.0833%2018.3333C11.6231%2018.3333%2011.25%2017.9602%2011.25%2017.5L11.25%2012.0833C11.25%2011.6231%2011.6231%2011.25%2012.0833%2011.25L17.5%2011.25ZM17.5%2021.6667C17.9602%2021.6667%2018.3333%2022.0398%2018.3333%2022.5L18.3333%2027.9167C18.3333%2028.3769%2017.9602%2028.75%2017.5%2028.75L12.0833%2028.75C11.6231%2028.75%2011.25%2028.3769%2011.25%2027.9167L11.25%2022.5C11.25%2022.0398%2011.6231%2021.6667%2012.0833%2021.6667L17.5%2021.6667ZM27.9167%2011.25C28.3769%2011.25%2028.75%2011.6231%2028.75%2012.0833L28.75%2017.5C28.75%2017.9602%2028.3769%2018.3333%2027.9167%2018.3333L22.5%2018.3333C22.0398%2018.3333%2021.6667%2017.9602%2021.6667%2017.5L21.6667%2012.0833C21.6667%2011.6231%2022.0398%2011.25%2022.5%2011.25L27.9167%2011.25Z'%20fill-rule='evenodd'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333ZM17.5002%2011.6666L12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666ZM17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499ZM17.5002%2022.0833L12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833ZM27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333ZM27.9168%2011.6666L22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M18.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833ZM12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666L12.0835%2011.6666ZM18.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999ZM12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833L12.0835%2022.0833ZM29.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833ZM22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666L22.5002%2011.6666Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2021.6667L27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667ZM24.5832%2021.6667L24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667ZM21.6665%2025.8334L21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334ZM27.9165%2027.9167L27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167ZM25.8332%2025.8334L25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667L27.9165%2024.5834ZM24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667L24.5832%2022.639ZM21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334L21.6665%2028.7501ZM27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167L27.9165%2028.7501ZM25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334L25.8332%2026.6667Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2014.375L14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375ZM14.375%2024.7917L14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917ZM24.7917%2014.375L24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375L14.375%2015.2083ZM14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917L14.375%2025.625ZM24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375L24.7917%2015.2083Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",t5="data:image/svg+xml,%3csvg%20viewBox='0%200%2012%2012'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='12.000000'%20height='12.000000'%20fill='none'%3e%3cdefs%3e%3cfilter%20id='pixso_custom_mask_type_luminance'%3e%3cfeColorMatrix%20type='matrix'%20values='1%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%20'%20/%3e%3c/filter%3e%3c/defs%3e%3cmask%20id='mask_0'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20maskUnits='userSpaceOnUse'%3e%3cg%20filter='url(%23pixso_custom_mask_type_luminance)'%3e%3cg%20id='mask401_19830'%3e%3cpath%20id='蒙版'%20d='M0%200L11.9999%200L11.9999%2011.9999L0%2011.9999L0%200ZM2.69992%201.34999L8.09977%201.34999C9.5082%201.34999%2010.6498%202.49167%2010.6498%203.89998L10.6498%209.2999C10.6498%2010.7082%209.5082%2011.8499%208.09977%2011.8499L2.69992%2011.8499C1.29149%2011.8499%200.149901%2010.7082%200.149901%209.2999L0.149901%203.89998C0.149901%202.49167%201.29149%201.34999%202.69992%201.34999Z'%20fill='rgb(196,196,196)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/mask%3e%3crect%20id='ic_public_copy'%20width='12.000000'%20height='12.000000'%20x='0.000000'%20y='0.000000'%20/%3e%3crect%20id='ic_public_copy-复制/base/ic_public_copy'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path1'%20d='M0.000134537%205.99497C0.000134537%205.05748%20-0.00236544%204.11999%200.000134537%203.1825C-0.00236544%202.72751%200.055134%202.27501%200.165133%201.83752C0.41263%200.907526%201.01762%200.355032%201.94761%200.140034C2.41261%200.040035%202.8901%20-0.00746449%203.3651%203.54269e-05C5.16258%203.54269e-05%206.96006%203.54269e-05%208.76004%203.54269e-05C9.21254%20-0.00246455%209.66503%200.0475349%2010.1075%200.155034C11.065%200.387531%2011.64%200.995025%2011.8575%201.95002C11.9575%202.40001%2012.005%202.86001%2011.9975%203.3225C11.9975%205.13998%2011.9975%206.95746%2011.9975%208.77244C12%209.22244%2011.95%209.67243%2011.845%2010.1099C11.61%2011.0674%2011%2011.6374%2010.0475%2011.8574C9.58003%2011.9574%209.10504%2012.0049%208.62754%2011.9974C6.83756%2011.9974%205.04758%2011.9974%203.2576%2011.9974C2.80011%2012.0024%202.34511%2011.9499%201.90011%2011.8449C0.937625%2011.6124%200.360131%2011.0024%200.142633%2010.0424C0.0301342%209.55494%200.000134537%209.06744%200.000134537%208.57495C0.000134537%207.71495%200.000134537%206.85496%200.000134537%205.99497Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='5.99993801'%20cy='5.99993801'%20r='5.99993801'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='mask'%20mask='url(%23mask_0)'%3e%3cg%20id='组合%208'%3e%3cpath%20id='path'%20d='M11.1%203.89993L11.1%206.8999C11.1%208.55488%209.75502%209.89737%208.10004%209.89737L5.10007%209.89737C3.44258%209.89737%202.1001%208.55488%202.1001%206.8999L2.1001%203.89993C2.1001%202.24245%203.44258%200.897461%205.10007%200.897461L8.10004%200.897461C9.75502%200.897461%2011.1%202.24245%2011.1%203.89993Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/g%3e%3c/g%3e%3cpath%20id='path4'%20d='M2.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path4'%20d='M9.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/svg%3e",r5="https://chat.opentiny.design",n5="https://ai.opentiny.design/next-remoter",o5="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",s5=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:X2},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:K2},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:Q2},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:Y2}]};class a5{constructor(t){this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new e5(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||n5,remoteUrl:t.remoteUrl||r5,logoUrl:t.logoUrl||o5},t.menuItems&&t.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){const r={"qr-code":X2,"ai-chat":K2,"remote-url":Q2,"remote-control":Y2};return t?t.map(n=>({...n,icon:n.icon??r[n.action]})):this.options.sessionId?s5(this.options):[]}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
100
+ `,document.head.appendChild(e)})();const X2="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2039.9692'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='39.969238'%20fill='none'%20customFrame='url(%23clipPath_3)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_3'%3e%3crect%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_4'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_5'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_6'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_7'%3e%3crect%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_8'%3e%3crect%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='2'%20width='40.000000'%20height='39.969238'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(239,246,255)'%20/%3e%3cg%20id='物业'%20clip-path='url(%23clipPath_4)'%20customFrame='url(%23clipPath_4)'%3e%3crect%20id='物业'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='7.984619'%20/%3e%3cg%20id='物业服务'%3e%3cg%20id='00公共/红点/图标+红点'%20customFrame='url(%23clipPath_5)'%3e%3crect%20id='00公共/红点/图标+红点'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cg%20id='common_chats_line'%20customFrame='url(%23clipPath_6)'%3e%3crect%20id='common_chats_line'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='9.984619'%20/%3e%3cpath%20id='形状'%20d='M28.3332%2019.9847C28.3332%2015.3823%2024.6022%2011.6514%2019.9998%2011.6514C15.3975%2011.6514%2011.6665%2015.3823%2011.6665%2019.9847C11.6665%2024.5871%2015.3975%2028.318%2019.9998%2028.318C21.0018%2028.318%2021.9624%2028.1412%2022.8522%2027.8171L26.581%2028.1578C26.7205%2028.1706%2026.8611%2028.1598%2026.9971%2028.1259C27.6669%2027.959%2028.0746%2027.2806%2027.9077%2026.6108L27.2716%2024.0578C27.9477%2022.8535%2028.3332%2021.4641%2028.3332%2019.9847ZM19.9998%2013.1514C16.2259%2013.1514%2013.1665%2016.2108%2013.1665%2019.9847C13.1665%2023.7586%2016.2259%2026.818%2019.9998%2026.818C20.8089%2026.818%2021.5967%2026.678%2022.3388%2026.4077C22.505%2026.3471%2022.6803%2026.3166%2022.8565%2026.3171L22.9887%2026.3233L26.3665%2026.6322L25.8161%2024.4205C25.7352%2024.0958%2025.7655%2023.7548%2025.8997%2023.4512L25.9636%2023.3236C26.5311%2022.3126%2026.8332%2021.1723%2026.8332%2019.9847C26.8332%2016.2108%2023.7738%2013.1514%2019.9998%2013.1514ZM23.1152%2021.2468C23.352%2020.9069%2023.2684%2020.4394%2022.9286%2020.2026C22.5887%2019.9659%2022.1212%2020.0494%2021.8845%2020.3893C21.2894%2021.2433%2020.4268%2021.7347%2019.5102%2021.7347C18.9513%2021.7347%2018.4132%2021.554%2017.9375%2021.2122C17.6011%2020.9705%2017.1325%2021.0472%2016.8908%2021.3836C16.6491%2021.7199%2016.7258%2022.1886%2017.0622%2022.4303C17.7879%2022.9518%2018.6305%2023.2347%2019.5102%2023.2347C20.9394%2023.2347%2022.2505%2022.4878%2023.1152%2021.2468Z'%20fill='rgb(65,142,255)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3cg%20id='00公共/3位数红点'%20opacity='0'%20customFrame='url(%23clipPath_7)'%3e%3crect%20id='00公共/3位数红点'%20width='21.666666'%20height='13.333333'%20x='20.000000'%20y='9.984619'%20rx='6.666667'%20opacity='0'%20fill='rgb(243,111,100)'%20/%3e%3cpath%20id='文本'%20d='M26.0421%2013.4421C26.4259%2013.4421%2026.7677%2013.5255%2027.0675%2013.6923C27.3672%2013.8591%2027.6005%2014.0931%2027.7673%2014.3942C27.9342%2014.694%2028.0176%2015.0351%2028.0176%2015.4176C28.0176%2015.7173%2027.9633%2015.994%2027.8548%2016.2476C27.7463%2016.4999%2027.5673%2016.8315%2027.3177%2017.2425L25.859%2019.6432L25.0167%2019.6432L26.276%2017.5924C26.3534%2017.4704%2026.4307%2017.3564%2026.508%2017.2507C26.3357%2017.3063%2026.1445%2017.3341%2025.9342%2017.3341C25.5721%2017.3341%2025.2493%2017.2479%2024.9658%2017.0757C24.6837%2016.9034%2024.4633%2016.6701%2024.3046%2016.3758C24.1459%2016.0815%2024.0666%2015.7566%2024.0666%2015.4013C24.0666%2015.0351%2024.1513%2014.7021%2024.3209%2014.4023C24.4904%2014.1012%2024.7264%2013.8659%2025.0289%2013.6964C25.3314%2013.5268%2025.6691%2013.4421%2026.0421%2013.4421ZM26.0421%2016.6505C26.4029%2016.6505%2026.6904%2016.5325%2026.9047%2016.2965C27.119%2016.0605%2027.2262%2015.7539%2027.2262%2015.3769C27.2262%2014.9985%2027.119%2014.694%2026.9047%2014.4634C26.6904%2014.2328%2026.4029%2014.1175%2026.0421%2014.1175C25.6867%2014.1175%2025.4019%2014.2342%2025.1876%2014.4674C24.9733%2014.7007%2024.8661%2015.0039%2024.8661%2015.3769C24.8661%2015.7539%2024.9719%2016.0605%2025.1835%2016.2965C25.3951%2016.5325%2025.6813%2016.6505%2026.0421%2016.6505ZM30.7921%2013.4421C31.1759%2013.4421%2031.5177%2013.5255%2031.8175%2013.6923C32.1172%2013.8591%2032.3505%2014.0931%2032.5173%2014.3942C32.6842%2014.694%2032.7676%2015.0351%2032.7676%2015.4176C32.7676%2015.7173%2032.7133%2015.994%2032.6048%2016.2476C32.4963%2016.4999%2032.3173%2016.8315%2032.0677%2017.2425L30.609%2019.6432L29.7667%2019.6432L31.026%2017.5924C31.1034%2017.4704%2031.1807%2017.3564%2031.258%2017.2507C31.0857%2017.3063%2030.8945%2017.3341%2030.6842%2017.3341C30.3221%2017.3341%2029.9993%2017.2479%2029.7158%2017.0757C29.4337%2016.9034%2029.2133%2016.6701%2029.0546%2016.3758C28.8959%2016.0815%2028.8166%2015.7566%2028.8166%2015.4013C28.8166%2015.0351%2028.9013%2014.7021%2029.0709%2014.4023C29.2404%2014.1012%2029.4764%2013.8659%2029.7789%2013.6964C30.0814%2013.5268%2030.4191%2013.4421%2030.7921%2013.4421ZM30.7921%2016.6505C31.1529%2016.6505%2031.4404%2016.5325%2031.6547%2016.2965C31.869%2016.0605%2031.9762%2015.7539%2031.9762%2015.3769C31.9762%2014.9985%2031.869%2014.694%2031.6547%2014.4634C31.4404%2014.2328%2031.1529%2014.1175%2030.7921%2014.1175C30.4367%2014.1175%2030.1519%2014.2342%2029.9376%2014.4674C29.7233%2014.7007%2029.6161%2015.0039%2029.6161%2015.3769C29.6161%2015.7539%2029.7219%2016.0605%2029.9335%2016.2965C30.1451%2016.5325%2030.4313%2016.6505%2030.7921%2016.6505ZM35.2674%2014.6851L35.9001%2014.6851L35.9001%2016.3188L37.5339%2016.3188L37.5339%2016.9516L35.9001%2016.9516L35.9001%2018.5853L35.2674%2018.5853L35.2674%2016.9516L33.6337%2016.9516L33.6337%2016.3188L35.2674%2016.3188L35.2674%2014.6851Z'%20fill='rgb(255,255,255)'%20fill-rule='nonzero'%20/%3e%3c/g%3e%3cg%20id='00公共/单红点'%20opacity='0'%20customFrame='url(%23clipPath_8)'%3e%3crect%20id='00公共/单红点'%20width='6.666667'%20height='6.666667'%20x='23.333496'%20y='9.984619'%20opacity='0'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3ccircle%20id='红点'%20cx='26.6668301'%20cy='13.3179522'%20r='3.33333325'%20fill='rgb(243,111,100)'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",eg="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_12)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_12'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_13'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_14'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='4'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(234,255,244)'%20/%3e%3cg%20id='我的信息'%20clip-path='url(%23clipPath_13)'%20customFrame='url(%23clipPath_13)'%3e%3crect%20id='我的信息'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='组合%208'%20customFrame='url(%23clipPath_14)'%3e%3crect%20id='组合%208'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='合并'%20d='M28.4994%2012.3142C28.4994%2012.2578%2028.4937%2012.2018%2028.4825%2012.1465C28.4713%2012.0911%2028.4547%2012.0373%2028.4327%2011.9851C28.4107%2011.933%2028.3836%2011.8835%2028.3516%2011.8365C28.3197%2011.7896%2028.2834%2011.7461%2028.2427%2011.7062C28.202%2011.6663%2028.1579%2011.6307%2028.1101%2011.5993C28.0622%2011.568%2028.0117%2011.5415%2027.9585%2011.5199C27.9054%2011.4983%2027.8506%2011.4819%2027.7942%2011.4709C27.7378%2011.4599%2027.6806%2011.4544%2027.6231%2011.4544L24.1832%2011.5199L24.1832%2010L29.0796%2010C29.1472%2010%2029.2143%2010.0065%2029.2806%2010.0194C29.347%2010.0324%2029.4114%2010.0516%2029.4739%2010.077C29.5364%2010.1024%2029.5961%2010.1336%2029.6523%2010.1705C29.7086%2010.2074%2029.7605%2010.2493%2029.8084%2010.2963C29.8562%2010.3433%2029.8991%2010.3944%2029.9367%2010.4496C29.9743%2010.5048%2030.006%2010.5631%2030.0319%2010.6244C30.0578%2010.6858%2030.0773%2010.7491%2030.0905%2010.8142C30.1037%2010.8794%2030.1104%2010.9451%2030.1104%2011.0115L30.1832%2014.4522L28.4992%2014.5L28.4994%2012.3142ZM11.6995%2012.3143C11.6995%2012.2579%2011.7051%2012.2019%2011.7163%2012.1466C11.7275%2012.0912%2011.7441%2012.0374%2011.7661%2011.9852C11.7882%2011.9331%2011.8152%2011.8836%2011.8472%2011.8366C11.8791%2011.7897%2011.9155%2011.7462%2011.9562%2011.7063C11.9968%2011.6664%2012.0409%2011.6308%2012.0888%2011.5994C12.1366%2011.5681%2012.1871%2011.5416%2012.2403%2011.52C12.2934%2011.4984%2012.3482%2011.482%2012.4046%2011.471C12.4611%2011.46%2012.5182%2011.4545%2012.5758%2011.4545L16.0157%2011.52L16.0157%2010.0001L11.1193%2010.0001C11.0516%2010.0001%2010.9846%2010.0066%2010.9182%2010.0196C10.8518%2010.0325%2010.7874%2010.0517%2010.7249%2010.0771C10.6624%2010.1025%2010.6028%2010.1337%2010.5465%2010.1706C10.4902%2010.2075%2010.4383%2010.2494%2010.3904%2010.2964C10.3426%2010.3434%2010.2997%2010.3945%2010.2621%2010.4497C10.2245%2010.5049%2010.1929%2010.5632%2010.167%2010.6245C10.1411%2010.6859%2010.1215%2010.7492%2010.1083%2010.8143C10.0951%2010.8795%2010.0885%2010.9452%2010.0884%2011.0116L10.0157%2014.4523L11.6997%2014.5L11.6995%2012.3143ZM25.3135%2021.8051L25.3135%2022.8167C25.7656%2022.8929%2026.2209%2022.9249%2026.6792%2022.9127C28.3381%2022.9127%2029.1675%2022.326%2029.1675%2021.1527C29.1733%2020.9869%2029.151%2020.825%2029.1006%2020.667C29.0503%2020.509%2028.9747%2020.3641%2028.8742%2020.2322C28.767%2020.1025%2028.6403%2019.9963%2028.4938%2019.9134C28.3474%2019.8306%2028.191%2019.7767%2028.0246%2019.7517L28.0246%2019.7011C28.0971%2019.6839%2028.1676%2019.6606%2028.236%2019.6311C28.3044%2019.6016%2028.3698%2019.5665%2028.4321%2019.5257C28.4944%2019.4848%2028.5526%2019.4389%2028.6069%2019.3879C28.6613%2019.3369%2028.7109%2019.2816%2028.7556%2019.222C28.8003%2019.1624%2028.8394%2019.0994%2028.8732%2019.033C28.9069%2018.9665%2028.9346%2018.8977%2028.9564%2018.8265C28.9782%2018.7552%2028.9937%2018.6826%2029.0028%2018.6086C29.0119%2018.5347%2029.0145%2018.4605%2029.0107%2018.3861C29.0217%2018.2675%2029.0176%2018.1495%2028.9984%2018.0319C28.9791%2017.9144%2028.9454%2017.8012%2028.8971%2017.6923C28.8489%2017.5834%2028.7875%2017.4823%2028.7134%2017.3891C28.6393%2017.2959%2028.5547%2017.2135%2028.4595%2017.1419C28.219%2017.0003%2027.963%2016.8972%2027.6915%2016.8326C27.4199%2016.7679%2027.1449%2016.7446%2026.8664%2016.7626C26.6258%2016.7621%2026.3864%2016.7791%2026.1482%2016.8132C25.9479%2016.8386%2025.7504%2016.8791%2025.5563%2016.9346L25.5563%2017.8854C25.743%2017.8264%2025.9337%2017.7842%2026.128%2017.759C26.3276%2017.73%2026.5282%2017.7148%2026.7298%2017.7134C27.0252%2017.6949%2027.3049%2017.7523%2027.5692%2017.8854C27.6168%2017.9161%2027.6595%2017.9525%2027.6972%2017.9947C27.7348%2018.037%2027.766%2018.0835%2027.791%2018.1343C27.816%2018.1851%2027.8337%2018.2383%2027.8441%2018.294C27.8545%2018.3496%2027.8573%2018.4056%2027.8525%2018.462C27.8566%2018.5278%2027.8514%2018.5927%2027.8367%2018.657C27.822%2018.7212%2027.7986%2018.7821%2027.7663%2018.8395C27.734%2018.897%2027.694%2018.9487%2027.6468%2018.9946C27.5995%2019.0405%2027.5468%2019.0787%2027.4885%2019.1093C27.1544%2019.2631%2026.8037%2019.3306%2026.4364%2019.3117L25.9862%2019.3117L25.9862%2020.1917L26.4466%2020.1917C26.8409%2020.1669%2027.2202%2020.2309%2027.5845%2020.3839C27.6459%2020.4167%2027.7011%2020.4576%2027.7505%2020.5066C27.7999%2020.5556%2027.8412%2020.6107%2027.8745%2020.6718C27.9077%2020.733%2027.9315%2020.7976%2027.9458%2020.8656C27.9602%2020.9337%2027.9644%2021.0024%2027.9587%2021.0717C27.9648%2021.1402%2027.9612%2021.2083%2027.9478%2021.2757C27.9344%2021.3432%2027.912%2021.4074%2027.8801%2021.4683C27.8483%2021.5293%2027.8086%2021.5846%2027.7609%2021.6341C27.7132%2021.6837%2027.6593%2021.7254%2027.5996%2021.7596C27.2884%2021.9045%2026.9613%2021.9685%2026.6184%2021.9518C26.1786%2021.9465%2025.7436%2021.8977%2025.3135%2021.8051ZM21.3382%2018.6238C21.3445%2018.5593%2021.343%2018.495%2021.3335%2018.4308C21.3241%2018.3667%2021.3069%2018.3046%2021.2822%2018.2447C21.2575%2018.1847%2021.226%2018.1287%2021.1876%2018.0765C21.1492%2018.0242%2021.1049%2017.9774%2021.055%2017.936C20.9359%2017.8608%2020.808%2017.806%2020.6714%2017.7714C20.5349%2017.7368%2020.3964%2017.7242%2020.2558%2017.7337C19.8009%2017.7395%2019.356%2017.8087%2018.9208%2017.9411L18.9208%2016.9598C19.4252%2016.8181%2019.9393%2016.7524%2020.4633%2016.7626C20.7322%2016.7484%2020.9964%2016.7773%2021.256%2016.8491C21.5156%2016.9209%2021.7571%2017.032%2021.9806%2017.1824C22.0729%2017.2601%2022.1548%2017.3474%2022.2263%2017.4446C22.2978%2017.5418%2022.3567%2017.646%2022.4034%2017.7573C22.45%2017.8686%2022.483%2017.9838%2022.5021%2018.1029C22.5213%2018.222%2022.5261%2018.3417%2022.5167%2018.462C22.5245%2018.7882%2022.4655%2019.1017%2022.3396%2019.4027C22.1879%2019.7384%2021.984%2020.0384%2021.7277%2020.3029C21.3021%2020.7337%2020.8502%2021.135%2020.3721%2021.5067L19.9928%2021.8051L19.9928%2021.8759L22.6938%2021.8759L22.6938%2022.8419L18.5464%2022.8419L18.5464%2021.7697C19.2882%2021.1796%2019.8579%2020.6975%2020.2558%2020.3232C20.574%2020.0432%2020.8523%2019.728%2021.0905%2019.3774C21.1675%2019.2665%2021.2269%2019.1469%2021.2691%2019.0187C21.3113%2018.8904%2021.3344%2018.7588%2021.3382%2018.6238ZM12.3102%2017.2127L12.3102%2018.1939L13.7769%2017.9107L13.7769%2022.8419L14.9605%2022.8419L14.9605%2016.8486L14.0957%2016.8486L12.3102%2017.2127ZM28.5524%2028.0475C28.5524%2028.104%2028.5467%2028.1599%2028.5353%2028.2152C28.5239%2028.2706%2028.5071%2028.3244%2028.4849%2028.3766C28.4626%2028.4287%2028.4352%2028.4782%2028.4028%2028.5252C28.3705%2028.5721%2028.3337%2028.6156%2028.2925%2028.6555C28.2513%2028.6954%2028.2067%2028.731%2028.1583%2028.7624C28.1098%2028.7937%2028.0587%2028.8202%2028.0049%2028.8418C27.9511%2028.8634%2027.8957%2028.8798%2027.8385%2028.8908C27.7814%2028.9018%2027.7235%2028.9073%2027.6653%2028.9073L24.1832%2028.8418L24.1832%2030.3617L29.1397%2030.3617C29.2082%2030.3617%2029.276%2030.3552%2029.3432%2030.3423C29.4104%2030.3293%2029.4756%2030.3101%2029.5389%2030.2847C29.6022%2030.2593%2029.6625%2030.2281%2029.7195%2030.1912C29.7765%2030.1543%2029.829%2030.1124%2029.8774%2030.0654C29.9259%2030.0184%2029.9693%2029.9673%2030.0074%2029.9121C30.0454%2029.8569%2030.0774%2029.7986%2030.1037%2029.7373C30.1299%2029.6759%2030.1497%2029.6126%2030.163%2029.5475C30.1764%2029.4823%2030.1831%2029.4166%2030.1832%2029.3502L30.1832%2026.0478L28.4785%2026L28.5524%2028.0475ZM11.6308%2028.0099C11.6308%2028.0664%2011.6365%2028.1223%2011.6479%2028.1777C11.6592%2028.233%2011.676%2028.2868%2011.6983%2028.339C11.7206%2028.3911%2011.748%2028.4406%2011.7803%2028.4876C11.8127%2028.5345%2011.8495%2028.578%2011.8906%2028.6179C11.9318%2028.6578%2011.9765%2028.6934%2012.0249%2028.7248C12.0733%2028.7562%2012.1244%2028.7826%2012.1783%2028.8042C12.2321%2028.8259%2012.2875%2028.8422%2012.3446%2028.8532C12.4017%2028.8642%2012.4596%2028.8697%2012.5178%2028.8698L16%2028.8042L16%2030.3241L11.0435%2030.3241C10.975%2030.3241%2010.9071%2030.3176%2010.8399%2030.3047C10.7727%2030.2917%2010.7076%2030.2725%2010.6443%2030.2471C10.581%2030.2217%2010.5206%2030.1906%2010.4637%2030.1537C10.4067%2030.1168%2010.3542%2030.0748%2010.3057%2030.0278C10.2573%2029.9809%2010.2138%2029.9298%2010.1758%2029.8745C10.1377%2029.8193%2010.1057%2029.7611%2010.0795%2029.6997C10.0533%2029.6383%2010.0335%2029.575%2010.0201%2029.5099C10.0068%2029.4448%2010%2029.379%2010%2029.3126L10%2026.0478L11.7047%2026L11.6308%2028.0099Z'%20fill='rgb(14,191,241)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/svg%3e",tg="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_9)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_9'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_10'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_11'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='3'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='画板%202310'%20customFrame='url(%23clipPath_10)'%3e%3crect%20id='画板%202310'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='人事服务'%3e%3cg%20id='ic_public_link'%20clip-path='url(%23clipPath_11)'%20customFrame='url(%23clipPath_11)'%3e%3crect%20id='ic_public_link'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cpath%20id='path1'%20d='M9.9999%2019.9917C9.9999%2018.4292%209.99573%2016.8667%209.9999%2015.3042C9.99573%2014.5459%2010.0916%2013.7917%2010.2749%2013.0626C10.6874%2011.5126%2011.6957%2010.5917%2013.2457%2010.2334C14.0207%2010.0667%2014.8166%209.98756%2015.6082%2010.0001C18.6041%2010.0001%2021.5999%2010.0001%2024.5999%2010.0001C25.3541%209.99589%2026.1082%2010.0792%2026.8457%2010.2584C28.4416%2010.6459%2029.3999%2011.6584%2029.7624%2013.2501C29.9291%2014.0001%2030.0041%2014.7667%2029.9957%2015.5376C29.9957%2018.5667%2029.9957%2021.5959%2029.9957%2024.6209C29.9999%2025.3709%2029.9166%2026.1209%2029.7416%2026.8459C29.3499%2028.4459%2028.3332%2029.3959%2026.7457%2029.7626C25.9666%2029.9292%2025.1749%2030.0084%2024.3791%2029.9959C21.3957%2029.9959%2018.4124%2029.9959%2015.4291%2029.9959C14.6666%2030.0042%2013.9082%2029.9167%2013.1666%2029.7417C11.5624%2029.3542%2010.5999%2028.3376%2010.2374%2026.7376C10.0499%2025.9251%209.9999%2025.1126%209.9999%2024.2917C9.9999%2022.8584%209.9999%2021.4251%209.9999%2019.9917Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path3'%20d='M25.0333%2021.8666L26.9%2020C28.8083%2018.0916%2028.8083%2015%2026.9%2013.0958C24.9958%2011.1875%2021.9041%2011.1875%2020%2013.0958L18.1291%2014.9625M21.8666%2025.0333L20%2026.9C18.0916%2028.8083%2015%2028.8083%2013.0958%2026.9C11.1875%2024.9958%2011.1875%2021.9041%2013.0958%2020L14.9625%2018.1291'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='pah4'%20d='M18.125%2021.875L21.875%2018.125'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='path5'%20d='M25.8207%2019.2626L24.0457%2021.0376C23.7998%2021.2834%2023.6748%2021.5292%2023.6748%2021.7751C23.6748%2022.0209%2023.7998%2022.2667%2024.0457%2022.5126C24.1498%2022.6167%2024.2665%2022.6959%2024.3915%2022.7459C24.5123%2022.7917%2024.6415%2022.8167%2024.779%2022.8167C24.9207%2022.8167%2025.0498%2022.7917%2025.1665%2022.7459C25.2957%2022.6959%2025.4123%2022.6167%2025.5165%2022.5126L27.2915%2020.7334C27.8165%2020.2126%2028.2165%2019.6334%2028.4957%2019.0001C28.5082%2018.9667%2028.5248%2018.9334%2028.5373%2018.8959C28.554%2018.8626%2028.5665%2018.8292%2028.579%2018.7917C28.8332%2018.1501%2028.9582%2017.4584%2028.9582%2016.7209C28.9582%2015.9792%2028.8332%2015.2876%2028.579%2014.6459C28.5665%2014.6084%2028.554%2014.5751%2028.5373%2014.5417C28.5248%2014.5042%2028.5082%2014.4709%2028.4957%2014.4376C28.2165%2013.8042%2027.8165%2013.2292%2027.2915%2012.7042C26.7707%2012.1792%2026.1915%2011.7792%2025.5582%2011.5001C25.5248%2011.4876%2025.4915%2011.4709%2025.454%2011.4584C25.4207%2011.4417%2025.3873%2011.4292%2025.354%2011.4167C24.7082%2011.1667%2024.0165%2011.0417%2023.279%2011.0417C22.5373%2011.0417%2021.8457%2011.1667%2021.204%2011.4167C21.1665%2011.4292%2021.1332%2011.4417%2021.0998%2011.4584C21.0623%2011.4709%2021.029%2011.4876%2020.9957%2011.5001C20.3623%2011.7792%2019.7832%2012.1792%2019.2623%2012.7042L17.4832%2014.4792C17.379%2014.5834%2017.2998%2014.7001%2017.2498%2014.8292C17.204%2014.9501%2017.179%2015.0751%2017.179%2015.2167C17.179%2015.3542%2017.204%2015.4834%2017.2498%2015.6042C17.2998%2015.7292%2017.379%2015.8459%2017.4832%2015.9542C17.5915%2016.0584%2017.7082%2016.1376%2017.8332%2016.1876C17.954%2016.2334%2018.0832%2016.2584%2018.2207%2016.2584C18.3623%2016.2584%2018.4915%2016.2334%2018.6082%2016.1876C18.7373%2016.1376%2018.854%2016.0584%2018.9582%2015.9542L20.7332%2014.1751C21.0873%2013.8209%2021.4748%2013.5584%2021.8957%2013.3834C22.3165%2013.2084%2022.779%2013.1251%2023.279%2013.1251C23.7748%2013.1251%2024.2373%2013.2084%2024.6582%2013.3834C25.079%2013.5584%2025.4665%2013.8209%2025.8207%2014.1751C26.1748%2014.5292%2026.4373%2014.9167%2026.6123%2015.3376C26.7873%2015.7584%2026.8748%2016.2167%2026.8748%2016.7209C26.8748%2017.2209%2026.7873%2017.6792%2026.6123%2018.1001C26.4373%2018.5209%2026.1748%2018.9084%2025.8207%2019.2626ZM13.3832%2021.8959C13.5582%2021.4751%2013.8207%2021.0876%2014.1748%2020.7334L15.954%2018.9584C16.0582%2018.8542%2016.1373%2018.7376%2016.1873%2018.6084C16.2332%2018.4876%2016.2582%2018.3626%2016.2582%2018.2209C16.2582%2018.0834%2016.2332%2017.9542%2016.1873%2017.8334C16.1373%2017.7084%2016.0582%2017.5917%2015.954%2017.4834C15.7082%2017.2417%2015.4623%2017.1167%2015.2165%2017.1167C14.9707%2017.1167%2014.7248%2017.2417%2014.479%2017.4834L12.704%2019.2626C12.179%2019.7876%2011.779%2020.3626%2011.4998%2020.9959C11.4873%2021.0292%2011.4707%2021.0626%2011.4582%2021.1001C11.4415%2021.1334%2011.429%2021.1667%2011.4165%2021.2042C11.1665%2021.8459%2011.0415%2022.5376%2011.0415%2023.2792C11.0415%2024.0167%2011.1665%2024.7084%2011.4165%2025.3542C11.429%2025.3876%2011.4415%2025.4209%2011.4582%2025.4584C11.4707%2025.4917%2011.4873%2025.5251%2011.4998%2025.5584C11.779%2026.1917%2012.179%2026.7709%2012.704%2027.2917C13.2248%2027.8167%2013.804%2028.2167%2014.4373%2028.4959C14.4707%2028.5084%2014.504%2028.5251%2014.5415%2028.5376C14.5748%2028.5542%2014.6082%2028.5667%2014.6457%2028.5792C15.2873%2028.8292%2015.979%2028.9584%2016.7207%2028.9584C17.4582%2028.9584%2018.1498%2028.8292%2018.7915%2028.5792C18.829%2028.5667%2018.8623%2028.5542%2018.8957%2028.5376C18.9332%2028.5251%2018.9665%2028.5084%2018.9998%2028.4959C19.6332%2028.2167%2020.2123%2027.8167%2020.7332%2027.2917L22.5123%2025.5167C22.6165%2025.4126%2022.6957%2025.2959%2022.7457%2025.1667C22.7915%2025.0459%2022.8165%2024.9209%2022.8165%2024.7792C22.8165%2024.6417%2022.7915%2024.5126%2022.7457%2024.3917C22.6957%2024.2667%2022.6165%2024.1501%2022.5123%2024.0417C22.2665%2023.8001%2022.0207%2023.6751%2021.7748%2023.6751C21.529%2023.6751%2021.2832%2023.8001%2021.0373%2024.0417L19.2623%2025.8209C18.9082%2026.1751%2018.5207%2026.4376%2018.0998%2026.6126C17.679%2026.7876%2017.2165%2026.8751%2016.7207%2026.8751C16.2207%2026.8751%2015.7582%2026.7876%2015.3373%2026.6126C14.9165%2026.4376%2014.529%2026.1751%2014.1748%2025.8209C13.8207%2025.4667%2013.5582%2025.0792%2013.3832%2024.6584C13.2082%2024.2376%2013.1248%2023.7792%2013.1248%2023.2792C13.1248%2022.7751%2013.2082%2022.3167%2013.3832%2021.8959Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path6'%20d='M21.8127%2016.7458C21.746%2016.7874%2021.6877%2016.8374%2021.6293%2016.8916L16.8918%2021.6291C16.8377%2021.6874%2016.7877%2021.7499%2016.746%2021.8124C16.7127%2021.8624%2016.6877%2021.9166%2016.6627%2021.9749C16.6377%2022.0374%2016.6168%2022.1041%2016.6043%2022.1708C16.5918%2022.2333%2016.5835%2022.2999%2016.5835%2022.3666C16.5835%2022.4333%2016.5918%2022.4999%2016.6043%2022.5666C16.6168%2022.6333%2016.6377%2022.6999%2016.6627%2022.7624C16.6877%2022.8166%2016.7127%2022.8708%2016.746%2022.9208C16.7877%2022.9874%2016.8377%2023.0499%2016.8918%2023.1041C16.946%2023.1583%2017.0085%2023.2083%2017.0752%2023.2499C17.1252%2023.2833%2017.1793%2023.3083%2017.2335%2023.3333C17.3002%2023.3583%2017.3627%2023.3791%2017.4293%2023.3916C17.496%2023.4041%2017.5627%2023.4124%2017.6293%2023.4124C17.696%2023.4124%2017.7627%2023.4041%2017.8252%2023.3916C17.8918%2023.3791%2017.9585%2023.3583%2018.021%2023.3333C18.0793%2023.3083%2018.1335%2023.2833%2018.1835%2023.2499C18.246%2023.2083%2018.3085%2023.1583%2018.3668%2023.1041L23.1043%2018.3666C23.1585%2018.3083%2023.2085%2018.2499%2023.2502%2018.1833C23.2835%2018.1333%2023.3085%2018.0791%2023.3335%2018.0208C23.3585%2017.9583%2023.3793%2017.8916%2023.3918%2017.8249C23.4043%2017.7624%2023.4127%2017.6958%2023.4127%2017.6291C23.4127%2017.5624%2023.4043%2017.4958%2023.3918%2017.4291C23.3793%2017.3624%2023.3585%2017.2999%2023.3335%2017.2333C23.3085%2017.1791%2023.2835%2017.1249%2023.2502%2017.0749C23.2085%2017.0083%2023.1585%2016.9458%2023.1043%2016.8916C23.046%2016.8374%2022.9877%2016.7874%2022.921%2016.7458C22.871%2016.7124%2022.8168%2016.6874%2022.7627%2016.6624C22.696%2016.6374%2022.6335%2016.6166%2022.5668%2016.6041C22.5002%2016.5916%2022.4335%2016.5833%2022.3668%2016.5833C22.3002%2016.5833%2022.2335%2016.5916%2022.171%2016.6041C22.1043%2016.6166%2022.0377%2016.6374%2021.9752%2016.6624C21.9168%2016.6874%2021.8627%2016.7124%2021.8127%2016.7458Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",rg="data:image/svg+xml,%3csvg%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='40.000000'%20height='40.000000'%20fill='none'%20customFrame='url(%23clipPath_0)'%3e%3cdefs%3e%3cclipPath%20id='clipPath_0'%3e%3crect%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_1'%3e%3crect%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3cclipPath%20id='clipPath_2'%3e%3crect%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20fill='rgb(255,255,255)'%20/%3e%3c/clipPath%3e%3c/defs%3e%3crect%20id='1'%20width='40.000000'%20height='40.000000'%20x='0.000000'%20y='0.000000'%20rx='12.000000'%20fill='rgb(236,250,254)'%20/%3e%3cg%20id='车辆'%20clip-path='url(%23clipPath_1)'%20customFrame='url(%23clipPath_1)'%3e%3crect%20id='车辆'%20width='24.000000'%20height='24.000000'%20x='8.000000'%20y='8.000000'%20/%3e%3cg%20id='编组'%3e%3cg%20id='ic_public_qrcode'%20clip-path='url(%23clipPath_2)'%20customFrame='url(%23clipPath_2)'%3e%3crect%20id='ic_public_qrcode'%20width='20.000000'%20height='20.000000'%20x='10.000000'%20y='10.000000'%20/%3e%3cg%20id='ic_public_qrcode_1_1'%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_0'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_1'%20d='M10.6273%2015.5985C10.6243%2014.8898%2010.7114%2014.1836%2010.8865%2013.4968C11.2702%2012.0432%2012.2171%2011.1805%2013.6693%2010.8458C14.3974%2010.6885%2015.1411%2010.6148%2015.886%2010.6261C18.6946%2010.6261%2021.5035%2010.6261%2024.3127%2010.6261C25.0221%2010.6217%2025.7295%2010.7029%2026.4195%2010.8678C27.9156%2011.2339%2028.8134%2012.1816%2029.1554%2013.6725C29.3092%2014.3772%2029.3826%2015.097%2029.3744%2015.8182C29.3744%2018.6571%2029.3744%2021.4963%2029.3744%2024.3357C29.3782%2025.0383%2029.2973%2025.7388%2029.1334%2026.422C28.7673%2027.9189%2027.8153%2028.8123%2026.3243%2029.1543C25.5961%2029.311%2024.8524%2029.3847%2024.1076%2029.374C21.3107%2029.374%2018.514%2029.374%2015.7176%2029.374C15.0027%2029.3798%2014.2897%2029.2999%2013.5939%2029.136C12.0912%2028.7698%2011.189%2027.8178%2010.8477%2026.3195C10.6734%2025.5579%2010.6273%2024.7941%2010.6273%2024.0237C10.6273%2022.6802%2010.6273%2021.3364%2010.6273%2019.9924C10.6273%2018.5277%2010.6222%2017.0631%2010.6273%2015.5985Z'%20opacity='0.200000003'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-width='1.25'%20/%3e%3ccircle%20id='ic_public_qrcode_2_2'%20cx='20'%20cy='20'%20r='10'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='ic_public_qrcode_2_3'%20d='M17.5%2011.25C17.9602%2011.25%2018.3333%2011.6231%2018.3333%2012.0833L18.3333%2017.5C18.3333%2017.9602%2017.9602%2018.3333%2017.5%2018.3333L12.0833%2018.3333C11.6231%2018.3333%2011.25%2017.9602%2011.25%2017.5L11.25%2012.0833C11.25%2011.6231%2011.6231%2011.25%2012.0833%2011.25L17.5%2011.25ZM17.5%2021.6667C17.9602%2021.6667%2018.3333%2022.0398%2018.3333%2022.5L18.3333%2027.9167C18.3333%2028.3769%2017.9602%2028.75%2017.5%2028.75L12.0833%2028.75C11.6231%2028.75%2011.25%2028.3769%2011.25%2027.9167L11.25%2022.5C11.25%2022.0398%2011.6231%2021.6667%2012.0833%2021.6667L17.5%2021.6667ZM27.9167%2011.25C28.3769%2011.25%2028.75%2011.6231%2028.75%2012.0833L28.75%2017.5C28.75%2017.9602%2028.3769%2018.3333%2027.9167%2018.3333L22.5%2018.3333C22.0398%2018.3333%2021.6667%2017.9602%2021.6667%2017.5L21.6667%2012.0833C21.6667%2011.6231%2022.0398%2011.25%2022.5%2011.25L27.9167%2011.25Z'%20fill-rule='evenodd'%20stroke='rgb(14,191,241)'%20stroke-linecap='round'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333ZM17.5002%2011.6666L12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666ZM17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499ZM17.5002%2022.0833L12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833ZM27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333ZM27.9168%2011.6666L22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_4'%20d='M18.7502%2012.0833L18.7502%2017.4999C18.7502%2018.1903%2018.1905%2018.7499%2017.5002%2018.7499L12.0835%2018.7499C11.3931%2018.7499%2010.8335%2018.1903%2010.8335%2017.4999L10.8335%2012.0833C10.8335%2011.3929%2011.3931%2010.8333%2012.0835%2010.8333L17.5002%2010.8333C18.1905%2010.8333%2018.7502%2011.3929%2018.7502%2012.0833ZM12.0835%2011.6666C11.8534%2011.6666%2011.6668%2011.8531%2011.6668%2012.0833L11.6668%2017.4999C11.6668%2017.73%2011.8534%2017.9166%2012.0835%2017.9166L17.5002%2017.9166C17.7303%2017.9166%2017.9168%2017.73%2017.9168%2017.4999L17.9168%2012.0833C17.9168%2011.8531%2017.7303%2011.6666%2017.5002%2011.6666L12.0835%2011.6666ZM18.7502%2022.4999L18.7502%2027.9166C18.7502%2028.6069%2018.1905%2029.1666%2017.5002%2029.1666L12.0835%2029.1666C11.3931%2029.1666%2010.8335%2028.6069%2010.8335%2027.9166L10.8335%2022.4999C10.8335%2021.8096%2011.3931%2021.2499%2012.0835%2021.2499L17.5002%2021.2499C18.1905%2021.2499%2018.7502%2021.8096%2018.7502%2022.4999ZM12.0835%2022.0833C11.8534%2022.0833%2011.6668%2022.2698%2011.6668%2022.4999L11.6668%2027.9166C11.6668%2028.1467%2011.8534%2028.3333%2012.0835%2028.3333L17.5002%2028.3333C17.7303%2028.3333%2017.9168%2028.1467%2017.9168%2027.9166L17.9168%2022.4999C17.9168%2022.2698%2017.7303%2022.0833%2017.5002%2022.0833L12.0835%2022.0833ZM29.1668%2012.0833L29.1668%2017.4999C29.1668%2018.1903%2028.6072%2018.7499%2027.9168%2018.7499L22.5002%2018.7499C21.8098%2018.7499%2021.2502%2018.1903%2021.2502%2017.4999L21.2502%2012.0833C21.2502%2011.3929%2021.8098%2010.8333%2022.5002%2010.8333L27.9168%2010.8333C28.6072%2010.8333%2029.1668%2011.3929%2029.1668%2012.0833ZM22.5002%2011.6666C22.27%2011.6666%2022.0835%2011.8531%2022.0835%2012.0833L22.0835%2017.4999C22.0835%2017.73%2022.27%2017.9166%2022.5002%2017.9166L27.9168%2017.9166C28.1469%2017.9166%2028.3335%2017.73%2028.3335%2017.4999L28.3335%2012.0833C28.3335%2011.8531%2028.1469%2011.6666%2027.9168%2011.6666L22.5002%2011.6666Z'%20fill-rule='nonzero'%20stroke='rgb(255,255,255)'%20stroke-opacity='0'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2021.6667L27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667ZM24.5832%2021.6667L24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667ZM21.6665%2025.8334L21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334ZM27.9165%2027.9167L27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167ZM25.8332%2025.8334L25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_5'%20d='M27.9165%2024.5834L28.7498%2024.5834L28.7498%2021.6667L27.9165%2021.6667L27.9165%2024.5834ZM24.5832%2022.639L24.5828%2022.6388L24.5832%2024.5834L23.6109%2024.5834L23.6107%2022.6388L21.6665%2022.639L21.6665%2021.6667L24.5832%2021.6667L24.5832%2022.639ZM21.6665%2028.7501L22.4998%2028.7501L22.4998%2025.8334L21.6665%2025.8334L21.6665%2028.7501ZM27.9165%2028.7501L28.7498%2028.7501L28.7498%2027.9167L27.9165%2027.9167L27.9165%2028.7501ZM25.8332%2026.6667L26.6665%2026.6667L26.6665%2025.8334L25.8332%2025.8334L25.8332%2026.6667Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2014.375L14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375ZM14.375%2024.7917L14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917ZM24.7917%2014.375L24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375Z'%20fill='rgb(14,191,241)'%20fill-rule='nonzero'%20/%3e%3cpath%20id='ic_public_qrcode_2_6'%20d='M14.375%2015.2083L15.2083%2015.2083L15.2083%2014.375L14.375%2014.375L14.375%2015.2083ZM14.375%2025.625L15.2083%2025.625L15.2083%2024.7917L14.375%2024.7917L14.375%2025.625ZM24.7917%2015.2083L25.625%2015.2083L25.625%2014.375L24.7917%2014.375L24.7917%2015.2083Z'%20fill-rule='nonzero'%20stroke='rgb(14,191,241)'%20stroke-linejoin='round'%20stroke-width='1.25'%20/%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",d6="data:image/svg+xml,%3csvg%20viewBox='0%200%2012%2012'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20width='12.000000'%20height='12.000000'%20fill='none'%3e%3cdefs%3e%3cfilter%20id='pixso_custom_mask_type_luminance'%3e%3cfeColorMatrix%20type='matrix'%20values='1%200%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%20'%20/%3e%3c/filter%3e%3c/defs%3e%3cmask%20id='mask_0'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20maskUnits='userSpaceOnUse'%3e%3cg%20filter='url(%23pixso_custom_mask_type_luminance)'%3e%3cg%20id='mask401_19830'%3e%3cpath%20id='蒙版'%20d='M0%200L11.9999%200L11.9999%2011.9999L0%2011.9999L0%200ZM2.69992%201.34999L8.09977%201.34999C9.5082%201.34999%2010.6498%202.49167%2010.6498%203.89998L10.6498%209.2999C10.6498%2010.7082%209.5082%2011.8499%208.09977%2011.8499L2.69992%2011.8499C1.29149%2011.8499%200.149901%2010.7082%200.149901%209.2999L0.149901%203.89998C0.149901%202.49167%201.29149%201.34999%202.69992%201.34999Z'%20fill='rgb(196,196,196)'%20fill-rule='evenodd'%20/%3e%3c/g%3e%3c/g%3e%3c/mask%3e%3crect%20id='ic_public_copy'%20width='12.000000'%20height='12.000000'%20x='0.000000'%20y='0.000000'%20/%3e%3crect%20id='ic_public_copy-复制/base/ic_public_copy'%20width='11.999876'%20height='11.999876'%20x='0.000000'%20y='0.000000'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cpath%20id='path1'%20d='M0.000134537%205.99497C0.000134537%205.05748%20-0.00236544%204.11999%200.000134537%203.1825C-0.00236544%202.72751%200.055134%202.27501%200.165133%201.83752C0.41263%200.907526%201.01762%200.355032%201.94761%200.140034C2.41261%200.040035%202.8901%20-0.00746449%203.3651%203.54269e-05C5.16258%203.54269e-05%206.96006%203.54269e-05%208.76004%203.54269e-05C9.21254%20-0.00246455%209.66503%200.0475349%2010.1075%200.155034C11.065%200.387531%2011.64%200.995025%2011.8575%201.95002C11.9575%202.40001%2012.005%202.86001%2011.9975%203.3225C11.9975%205.13998%2011.9975%206.95746%2011.9975%208.77244C12%209.22244%2011.95%209.67243%2011.845%2010.1099C11.61%2011.0674%2011%2011.6374%2010.0475%2011.8574C9.58003%2011.9574%209.10504%2012.0049%208.62754%2011.9974C6.83756%2011.9974%205.04758%2011.9974%203.2576%2011.9974C2.80011%2012.0024%202.34511%2011.9499%201.90011%2011.8449C0.937625%2011.6124%200.360131%2011.0024%200.142633%2010.0424C0.0301342%209.55494%200.000134537%209.06744%200.000134537%208.57495C0.000134537%207.71495%200.000134537%206.85496%200.000134537%205.99497Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3ccircle%20id='path2'%20cx='5.99993801'%20cy='5.99993801'%20r='5.99993801'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20/%3e%3cg%20id='mask'%20mask='url(%23mask_0)'%3e%3cg%20id='组合%208'%3e%3cpath%20id='path'%20d='M11.1%203.89993L11.1%206.8999C11.1%208.55488%209.75502%209.89737%208.10004%209.89737L5.10007%209.89737C3.44258%209.89737%202.1001%208.55488%202.1001%206.8999L2.1001%203.89993C2.1001%202.24245%203.44258%200.897461%205.10007%200.897461L8.10004%200.897461C9.75502%200.897461%2011.1%202.24245%2011.1%203.89993Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/g%3e%3c/g%3e%3cpath%20id='path4'%20d='M2.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746Z'%20fill='rgb(255,255,255)'%20fill-opacity='0'%20fill-rule='evenodd'%20/%3e%3cpath%20id='path4'%20d='M9.6%203.89995L9.6%209.89738C9.6%2010.7274%208.92751%2011.3999%208.10002%2011.3999L2.10008%2011.3999C1.27009%2011.3999%200.600098%2010.7274%200.600098%209.89738L0.600098%203.89995C0.600098%203.06995%201.27009%202.39746%202.10008%202.39746L8.10002%202.39746C8.92751%202.39746%209.6%203.06995%209.6%203.89995Z'%20fill-rule='nonzero'%20stroke='rgb(25,25,25)'%20stroke-linejoin='round'%20stroke-width='0.749992251'%20/%3e%3c/svg%3e",p6="https://chat.opentiny.design",f6="https://ai.opentiny.design/next-remoter",h6="https://ai.opentiny.design/next-remoter/svgs/logo-next-no-bg-left.svg",m6=e=>{const t=!!e.sessionId;return[{action:"qr-code",show:t,text:"扫码登录",desc:"使用手机遥控页面",icon:rg},{action:"ai-chat",show:!0,text:"打开对话框",desc:"支持在网页端操作AI",icon:X2},{action:"remote-url",show:t,text:"遥控器链接",desc:`${e.remoteUrl}`,active:!0,tip:e.remoteUrl,showCopyIcon:!0,icon:tg},{action:"remote-control",show:t,text:"识别码",desc:t?`${e.sessionId.slice(-6)}`:"",know:!0,showCopyIcon:!0,icon:eg}]};class g6{constructor(t){this.isExpanded=!1,this.closingTimer=0,this.getImageUrl=r=>{if(!r)return;const n=new Image;return n.src=r,n},this.renderItem=()=>{this.menuItems.filter(r=>r.show!==!1).map(r=>{const n=document.getElementById(`tiny-remoter-icon-item-${r.action}`);if(!n)return;n.innerHTML="";const o=this.getImageUrl(r.icon);o&&n.appendChild(o)})},this.readyTips=r=>{const n=document.getElementById(r);n&&new u6(n,{content:"复制",placement:"top",trigger:"hover"})},this.options={...t,qrCodeUrl:t.qrCodeUrl||f6,remoteUrl:t.remoteUrl||p6,logoUrl:t.logoUrl||h6},t.menuItems&&t.menuItems.length===0?this.menuItems=[]:this.menuItems=this.mergeMenuItems(t.menuItems),this.init()}get sessionPrefix(){return this.options.qrCodeUrl?.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(t){const r={"qr-code":rg,"ai-chat":X2,"remote-url":tg,"remote-control":eg};return t?t.map(n=>({...n,icon:n.icon??r[n.action]})):this.options.sessionId?m6(this.options):[]}init(){this.createFloatingBlock(),this.createDropdownMenu(),this.bindEvents(),this.addStyles()}createFloatingBlock(){this.floatingBlock=document.createElement("div"),this.floatingBlock.className="tiny-remoter-floating-block",this.floatingBlock.innerHTML=`
101
101
  <div class="tiny-remoter-floating-block__icon">
102
102
  <img style="display: block; width: 56px;" src="${this.options.logoUrl}" alt="icon" />
103
103
  </div>
@@ -112,14 +112,14 @@ Minimum version required to store current data is: `+N+`.
112
112
  <div>
113
113
  ${r.showCopyIcon?`
114
114
  <div class="tiny-remoter-copy-icon" id="${r.action}" data-action="${r.action}">
115
- <img src="${t5}"/>
115
+ <img src="${d6}"/>
116
116
  </div>
117
117
  `:""}
118
118
  </div>
119
119
  </div>
120
120
  </div>
121
121
  </div>
122
- `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){const t=this.menuItems.find(n=>n.action==="remote-control"),r=t?.desc||t?.text||(this.options.sessionId?this.options.sessionId.slice(-6):"");r&&this.copyToClipboard(r)}copyRemoteURL(){const t=this.menuItems.find(s=>s.action==="remote-url"),r=this.options.sessionId?this.options.remoteUrl+this.sessionPrefix+this.options.sessionId:"",o=(t?.desc&&t.desc!==this.options.remoteUrl?t.desc:void 0)||r||t?.text||"";o&&this.copyToClipboard(o)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){if(!this.options.sessionId)return;const r=await new G2((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
122
+ `).join("");this.dropdownMenu.innerHTML=t,document.body.appendChild(this.dropdownMenu),this.renderItem(),this.readyTips("remote-control"),this.readyTips("remote-url")}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.showAIChat()}),this.floatingBlock.addEventListener("mouseenter",()=>{this.openDropdown(),this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.floatingBlock.addEventListener("mouseleave",()=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("mouseenter",t=>{this.closingTimer&&(window.clearTimeout(this.closingTimer),this.closingTimer=0)}),this.dropdownMenu.addEventListener("mouseleave",t=>{this.shouldCloseDropdown()}),this.dropdownMenu.addEventListener("click",t=>{const r=t.target,n=r.closest(".tiny-remoter-copy-icon");if(n){t.stopPropagation();const a=n.dataset.action;a&&this.handleAction(a);return}const s=r.closest(".tiny-remoter-dropdown-item")?.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",t=>{const r=t.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.closeDropdown()})}openDropdown(){!this.menuItems||this.menuItems&&this.menuItems.length===0||(this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show"))}shouldCloseDropdown(){this.closingTimer=window.setTimeout(()=>{this.closeDropdown()},300)}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(t){switch(t){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){const t=this.menuItems.find(n=>n.action==="remote-control"),r=t?.desc||t?.text||(this.options.sessionId?this.options.sessionId.slice(-6):"");r&&this.copyToClipboard(r)}copyRemoteURL(){const t=this.menuItems.find(s=>s.action==="remote-url"),r=this.options.sessionId?this.options.remoteUrl+this.sessionPrefix+this.options.sessionId:"",o=(t?.desc&&t.desc!==this.options.remoteUrl?t.desc:void 0)||r||t?.text||"";o&&this.copyToClipboard(o)}async copyToClipboard(t){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(t),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const n=document.execCommand("copy");document.body.removeChild(r),n?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(t){const r=t?"复制成功!":"复制失败,请手动复制",n=document.createElement("div");n.className=`tiny-remoter-copy-feedback ${t?"success":"error"}`,n.textContent=r,document.body.appendChild(n),setTimeout(()=>n.classList.add("show"),10),setTimeout(()=>{n.classList.remove("show"),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},300)},1500)}async showQRCode(){if(!this.options.sessionId)return;const r=await new Y2((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),n=this.createModal("扫码前往智能遥控器",`
123
123
  <div style="text-align: center; padding: 32px;">
124
124
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
125
125
  <div style="
@@ -545,13 +545,13 @@ Minimum version required to store current data is: `+N+`.
545
545
  color: white;
546
546
  }
547
547
  }
548
- `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}hide(){this.floatingBlock&&(this.floatingBlock.style.display="none"),this.closeDropdown()}show(){this.floatingBlock&&(this.floatingBlock.style.display="flex")}}const i5=(e={})=>new a5(e);var eg="vercel.ai.error",l5=Symbol.for(eg),tg,rg,ke=class Ww extends(rg=Error,tg=l5,rg){constructor({name:t,message:r,cause:n}){super(r),this[tg]=!0,this.name=t,this.cause=n}static isInstance(t){return Ww.hasMarker(t,eg)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},ng="AI_APICallError",og=`vercel.ai.error.${ng}`,c5=Symbol.for(og),sg,ag,ht=class extends(ag=ke,sg=c5,ag){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:a,cause:i,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:ng,message:t,cause:i}),this[sg]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return ke.hasMarker(t,og)}},ig="AI_EmptyResponseBodyError",lg=`vercel.ai.error.${ig}`,u5=Symbol.for(lg),cg,ug,d5=class extends(ug=ke,cg=u5,ug){constructor({message:t="Empty response body"}={}){super({name:ig,message:t}),this[cg]=!0}static isInstance(t){return ke.hasMarker(t,lg)}};function ao(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var dg="AI_InvalidArgumentError",pg=`vercel.ai.error.${dg}`,p5=Symbol.for(pg),fg,hg,mg=class extends(hg=ke,fg=p5,hg){constructor({message:t,cause:r,argument:n}){super({name:dg,message:t,cause:r}),this[fg]=!0,this.argument=n}static isInstance(t){return ke.hasMarker(t,pg)}},gg="AI_InvalidPromptError",yg=`vercel.ai.error.${gg}`,f5=Symbol.for(yg),vg,_g,io=class extends(_g=ke,vg=f5,_g){constructor({prompt:e,message:t,cause:r}){super({name:gg,message:`Invalid prompt: ${t}`,cause:r}),this[vg]=!0,this.prompt=e}static isInstance(e){return ke.hasMarker(e,yg)}},wg="AI_InvalidResponseDataError",bg=`vercel.ai.error.${wg}`,h5=Symbol.for(bg),Tg,kg,jd=class extends(kg=ke,Tg=h5,kg){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:wg,message:r}),this[Tg]=!0,this.data=t}static isInstance(t){return ke.hasMarker(t,bg)}},Sg="AI_JSONParseError",Cg=`vercel.ai.error.${Sg}`,m5=Symbol.for(Cg),Ig,xg,Cl=class extends(xg=ke,Ig=m5,xg){constructor({text:t,cause:r}){super({name:Sg,message:`JSON parsing failed: Text: ${t}.
549
- Error message: ${ao(r)}`,cause:r}),this[Ig]=!0,this.text=t}static isInstance(t){return ke.hasMarker(t,Cg)}},Eg="AI_LoadAPIKeyError",$g=`vercel.ai.error.${Eg}`,g5=Symbol.for($g),Rg,Pg,Il=class extends(Pg=ke,Rg=g5,Pg){constructor({message:t}){super({name:Eg,message:t}),this[Rg]=!0}static isInstance(t){return ke.hasMarker(t,$g)}},Mg="AI_TooManyEmbeddingValuesForCallError",Ng=`vercel.ai.error.${Mg}`,y5=Symbol.for(Ng),Og,Ag,v5=class extends(Ag=ke,Og=y5,Ag){constructor(e){super({name:Mg,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[Og]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return ke.hasMarker(e,Ng)}},qg="AI_TypeValidationError",Lg=`vercel.ai.error.${qg}`,_5=Symbol.for(Lg),jg,Dg,lo=class tf extends(Dg=ke,jg=_5,Dg){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const s=[];n.entityName&&s.push(n.entityName),n.entityId&&s.push(`id: "${n.entityId}"`),o+=s.join(", "),o+=")"}super({name:qg,message:`${o}: Value: ${JSON.stringify(t)}.
550
- Error message: ${ao(r)}`,cause:r}),this[jg]=!0,this.value=t,this.context=n}static isInstance(t){return ke.hasMarker(t,Lg)}static wrap({value:t,cause:r,context:n}){var o,s,a;return tf.isInstance(r)&&r.value===t&&((o=r.context)==null?void 0:o.field)===n?.field&&((s=r.context)==null?void 0:s.entityName)===n?.entityName&&((a=r.context)==null?void 0:a.entityId)===n?.entityId?r:new tf({value:t,cause:r,context:n})}},Ug="AI_UnsupportedFunctionalityError",zg=`vercel.ai.error.${Ug}`,w5=Symbol.for(zg),Zg,Fg,Qr=class extends(Fg=ke,Zg=w5,Fg){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:Ug,message:r}),this[Zg]=!0,this.functionality=t}static isInstance(t){return ke.hasMarker(t,zg)}};function Dt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function b5({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},s={};for(const a of e)if(a.type==="provider"){const i=(n=r?.(a))!=null?n:a.id in t?t[a.id]:void 0;if(i==null)continue;o[a.name]=i,s[i]=a.name}return{toProviderToolName:a=>{var i;return(i=o[a])!=null?i:a},toCustomToolName:a=>{var i;return(i=s[a])!=null?i:a}}}async function T5(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(Vg());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(Vg())};r?.addEventListener("abort",i)})}function Vg(){return new DOMException("Delay was aborted","AbortError")}var aa=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function Wo(e){return Object.fromEntries([...e.headers])}var{btoa:k5,atob:S5}=globalThis;function Go(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=S5(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function Jo(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return k5(t)}function Ko(e){return e instanceof Uint8Array?Jo(e):e}function C5(e,t={}){const{useArrayBrackets:r=!0}=t,n=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){n.append(o,s[0]);continue}const a=r?`${o}[]`:o;for(const i of s)n.append(a,i);continue}n.append(o,s)}return n}var Hg="AI_DownloadError",Bg=`vercel.ai.error.${Hg}`,I5=Symbol.for(Bg),Wg,Gg,rr=class extends(Gg=ke,Wg=I5,Gg){constructor({url:e,statusCode:t,statusText:r,cause:n,message:o=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:Hg,message:o,cause:n}),this[Wg]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return ke.hasMarker(e,Bg)}},Dd=2*1024*1024*1024;async function Jg({response:e,url:t,maxBytes:r=Dd}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new rr({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${u}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let i=0;try{for(;;){const{done:u,value:f}=await s.read();if(u)break;if(i+=f.length,i>r)throw new rr({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});a.push(f)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(i);let c=0;for(const u of a)l.set(u,c),c+=u.length;return l}function xl(e){let t;try{t=new URL(e)}catch{throw new rr({url:e,message:`Invalid URL: ${e}`})}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new rr({url:e,message:`URL scheme must be http or https, got ${t.protocol}`});const r=t.hostname;if(!r)throw new rr({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new rr({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(x5(n))throw new rr({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(Kg(r)){if(Ud(r))throw new rr({url:e,message:`URL with IP address ${r} is not allowed`});return}}function Kg(e){const t=e.split(".");return t.length!==4?!1:t.every(r=>{const n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}function Ud(e){const t=e.split(".").map(Number),[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function x5(e){const t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){const r=t.slice(7);if(Kg(r))return Ud(r);const n=r.split(":");if(n.length===2){const o=parseInt(n[0],16),s=parseInt(n[1],16);if(!isNaN(o)&&!isNaN(s)){const a=o>>8&255,i=o&255,l=s>>8&255,c=s&255;return Ud(`${a}.${i}.${l}.${c}`)}}}return!!(t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80"))}async function Yg(e,t){var r,n;xl(e);try{const o=await fetch(e,{signal:t?.abortSignal});if(o.redirected&&xl(o.url),!o.ok)throw new rr({url:e,statusCode:o.status,statusText:o.statusText});const s=await Jg({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:Dd}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw rr.isInstance(o)?o:new rr({url:e,cause:o})}}var ia=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new mg({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Wt=ia();function zd(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function co(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var E5=["fetch failed","failed to fetch"],$5=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function R5(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&$5.includes(t))}function Qg({error:e,url:t,requestBodyValues:r}){if(co(e))return e;if(e instanceof TypeError&&E5.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new ht({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return R5(e)?new ht({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function la(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function P5(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function qn(e,...t){const r=new Headers(P5(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var Xg="4.0.21",M5=()=>globalThis.fetch,El=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=M5()})=>{try{const a=await s(e,{method:"GET",headers:qn(t,`ai-sdk/provider-utils/${Xg}`,la()),signal:o}),i=Wo(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw co(c)||ht.isInstance(c)?c:new ht({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(co(l)||ht.isInstance(l))?l:new ht({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw Qg({error:a,url:e,requestBodyValues:{}})}};function ey(e){return e!=null}function N5({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const s=n.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function O5({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Il({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Il({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new Il({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Il({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Yo({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function A5(e){var t;const[r,n=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?t:n}var q5=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,L5=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function ty(e){const t=JSON.parse(e);return t===null||typeof t!="object"||q5.test(e)===!1&&L5.test(e)===!1?t:j5(t)}function j5(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&n.constructor!==null&&typeof n.constructor=="object"&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Zd(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return ty(e)}try{return ty(e)}finally{Error.stackTraceLimit=t}}function Fd(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:r}=e;if(r!=null)for(const n of Object.keys(r))r[n]=uo(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(uo):uo(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(uo)),e.allOf!=null&&(e.allOf=e.allOf.map(uo)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(uo));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=uo(t[r]);return e}function uo(e){return typeof e=="boolean"?e:Fd(e)}var D5=Symbol("Let zodToJsonSchema decide on which parser to use"),ry={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"},U5=e=>typeof e=="string"?{...ry,name:e}:{...ry,...e};function pr(){return{}}function z5(e,t){var r,n,o;const s={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==B.ZodAny&&(s.items=Qe(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function Z5(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function F5(){return{type:"boolean"}}function ny(e,t){return Qe(e.type._def,t)}var V5=(e,t)=>Qe(e.innerType._def,t);function oy(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>oy(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return H5(e)}}var H5=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function B5(e,t){return{...Qe(e.innerType._def,t),default:e.defaultValue()}}function W5(e,t){return t.effectStrategy==="input"?Qe(e.schema._def,t):pr()}function G5(e){return{type:"string",enum:Array.from(e.values)}}var J5=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function K5(e,t){const r=[Qe(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Qe(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(J5(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}n.push(s)}}),n.length?{allOf:n}:void 0}function Y5(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Vd=void 0,zr={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:()=>(Vd===void 0&&(Vd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Vd),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 sy(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":Zr(r,"email",n.message,t);break;case"format:idn-email":Zr(r,"idn-email",n.message,t);break;case"pattern:zod":Gt(r,zr.email,n.message,t);break}break;case"url":Zr(r,"uri",n.message,t);break;case"uuid":Zr(r,"uuid",n.message,t);break;case"regex":Gt(r,n.regex,n.message,t);break;case"cuid":Gt(r,zr.cuid,n.message,t);break;case"cuid2":Gt(r,zr.cuid2,n.message,t);break;case"startsWith":Gt(r,RegExp(`^${Hd(n.value,t)}`),n.message,t);break;case"endsWith":Gt(r,RegExp(`${Hd(n.value,t)}$`),n.message,t);break;case"datetime":Zr(r,"date-time",n.message,t);break;case"date":Zr(r,"date",n.message,t);break;case"time":Zr(r,"time",n.message,t);break;case"duration":Zr(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{Gt(r,RegExp(Hd(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Zr(r,"ipv4",n.message,t),n.version!=="v4"&&Zr(r,"ipv6",n.message,t);break}case"base64url":Gt(r,zr.base64url,n.message,t);break;case"jwt":Gt(r,zr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Gt(r,zr.ipv4Cidr,n.message,t),n.version!=="v4"&&Gt(r,zr.ipv6Cidr,n.message,t);break}case"emoji":Gt(r,zr.emoji(),n.message,t);break;case"ulid":{Gt(r,zr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Zr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Gt(r,zr.base64,n.message,t);break}}break}case"nanoid":Gt(r,zr.nanoid,n.message,t)}return r}function Hd(e,t){return t.patternStrategy==="escape"?X5(e):e}var Q5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function X5(e){let t="";for(let r=0;r<e.length;r++)Q5.has(e[r])||(t+="\\"),t+=e[r];return t}function Zr(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function Gt(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:ay(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=ay(t,n)}function ay(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(n.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
548
+ `,document.head.appendChild(t)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}hide(){this.floatingBlock&&(this.floatingBlock.style.display="none"),this.closeDropdown()}show(){this.floatingBlock&&(this.floatingBlock.style.display="flex")}}const y6=(e={})=>new g6(e);var ng="vercel.ai.error",v6=Symbol.for(ng),og,sg,Re=class rb extends(sg=Error,og=v6,sg){constructor({name:t,message:r,cause:n}){super(r),this[og]=!0,this.name=t,this.cause=n}static isInstance(t){return rb.hasMarker(t,ng)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}},ag="AI_APICallError",ig=`vercel.ai.error.${ag}`,_6=Symbol.for(ig),lg,cg,_t=class extends(cg=Re,lg=_6,cg){constructor({message:t,url:r,requestBodyValues:n,statusCode:o,responseHeaders:s,responseBody:a,cause:i,isRetryable:l=o!=null&&(o===408||o===409||o===429||o>=500),data:c}){super({name:ag,message:t,cause:i}),this[lg]=!0,this.url=r,this.requestBodyValues=n,this.statusCode=o,this.responseHeaders=s,this.responseBody=a,this.isRetryable=l,this.data=c}static isInstance(t){return Re.hasMarker(t,ig)}},ug="AI_EmptyResponseBodyError",dg=`vercel.ai.error.${ug}`,w6=Symbol.for(dg),pg,fg,b6=class extends(fg=Re,pg=w6,fg){constructor({message:t="Empty response body"}={}){super({name:ug,message:t}),this[pg]=!0}static isInstance(t){return Re.hasMarker(t,dg)}};function uo(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var hg="AI_InvalidArgumentError",mg=`vercel.ai.error.${hg}`,k6=Symbol.for(mg),gg,yg,vg=class extends(yg=Re,gg=k6,yg){constructor({message:t,cause:r,argument:n}){super({name:hg,message:t,cause:r}),this[gg]=!0,this.argument=n}static isInstance(t){return Re.hasMarker(t,mg)}},_g="AI_InvalidPromptError",wg=`vercel.ai.error.${_g}`,T6=Symbol.for(wg),bg,kg,po=class extends(kg=Re,bg=T6,kg){constructor({prompt:e,message:t,cause:r}){super({name:_g,message:`Invalid prompt: ${t}`,cause:r}),this[bg]=!0,this.prompt=e}static isInstance(e){return Re.hasMarker(e,wg)}},Tg="AI_InvalidResponseDataError",Sg=`vercel.ai.error.${Tg}`,S6=Symbol.for(Sg),Cg,xg,Zd=class extends(xg=Re,Cg=S6,xg){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Tg,message:r}),this[Cg]=!0,this.data=t}static isInstance(t){return Re.hasMarker(t,Sg)}},Ig="AI_JSONParseError",$g=`vercel.ai.error.${Ig}`,C6=Symbol.for($g),Eg,Rg,Rl=class extends(Rg=Re,Eg=C6,Rg){constructor({text:t,cause:r}){super({name:Ig,message:`JSON parsing failed: Text: ${t}.
549
+ Error message: ${uo(r)}`,cause:r}),this[Eg]=!0,this.text=t}static isInstance(t){return Re.hasMarker(t,$g)}},Pg="AI_LoadAPIKeyError",Mg=`vercel.ai.error.${Pg}`,x6=Symbol.for(Mg),Og,Ng,Pl=class extends(Ng=Re,Og=x6,Ng){constructor({message:t}){super({name:Pg,message:t}),this[Og]=!0}static isInstance(t){return Re.hasMarker(t,Mg)}},Ag="AI_TooManyEmbeddingValuesForCallError",qg=`vercel.ai.error.${Ag}`,I6=Symbol.for(qg),jg,Lg,$6=class extends(Lg=Re,jg=I6,Lg){constructor(e){super({name:Ag,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[jg]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return Re.hasMarker(e,qg)}},Dg="AI_TypeValidationError",Ug=`vercel.ai.error.${Dg}`,E6=Symbol.for(Ug),zg,Zg,fo=class of extends(Zg=Re,zg=E6,Zg){constructor({value:t,cause:r,context:n}){let o="Type validation failed";if(n?.field&&(o+=` for ${n.field}`),n?.entityName||n?.entityId){o+=" (";const s=[];n.entityName&&s.push(n.entityName),n.entityId&&s.push(`id: "${n.entityId}"`),o+=s.join(", "),o+=")"}super({name:Dg,message:`${o}: Value: ${JSON.stringify(t)}.
550
+ Error message: ${uo(r)}`,cause:r}),this[zg]=!0,this.value=t,this.context=n}static isInstance(t){return Re.hasMarker(t,Ug)}static wrap({value:t,cause:r,context:n}){var o,s,a;return of.isInstance(r)&&r.value===t&&((o=r.context)==null?void 0:o.field)===n?.field&&((s=r.context)==null?void 0:s.entityName)===n?.entityName&&((a=r.context)==null?void 0:a.entityId)===n?.entityId?r:new of({value:t,cause:r,context:n})}},Fg="AI_UnsupportedFunctionalityError",Vg=`vercel.ai.error.${Fg}`,R6=Symbol.for(Vg),Hg,Bg,Qr=class extends(Bg=Re,Hg=R6,Bg){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:Fg,message:r}),this[Hg]=!0,this.functionality=t}static isInstance(t){return Re.hasMarker(t,Vg)}};function Vt(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function P6({tools:e=[],providerToolNames:t,resolveProviderToolName:r}){var n;const o={},s={};for(const a of e)if(a.type==="provider"){const i=(n=r?.(a))!=null?n:a.id in t?t[a.id]:void 0;if(i==null)continue;o[a.name]=i,s[i]=a.name}return{toProviderToolName:a=>{var i;return(i=o[a])!=null?i:a},toCustomToolName:a=>{var i;return(i=s[a])!=null?i:a}}}async function M6(e,t){if(e==null)return Promise.resolve();const r=t?.abortSignal;return new Promise((n,o)=>{if(r?.aborted){o(Jg());return}const s=setTimeout(()=>{a(),n()},e),a=()=>{clearTimeout(s),r?.removeEventListener("abort",i)},i=()=>{a(),o(Jg())};r?.addEventListener("abort",i)})}function Jg(){return new DOMException("Delay was aborted","AbortError")}var da=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((e,t)=>{this.status.type==="resolved"?e(this.status.value):this.status.type==="rejected"&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise)}resolve(e){var t;this.status={type:"resolved",value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:"rejected",error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function ts(e){return Object.fromEntries([...e.headers])}var{btoa:O6,atob:N6}=globalThis;function rs(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=N6(t);return Uint8Array.from(r,n=>n.codePointAt(0))}function ns(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return O6(t)}function os(e){return e instanceof Uint8Array?ns(e):e}function A6(e,t={}){const{useArrayBrackets:r=!0}=t,n=new FormData;for(const[o,s]of Object.entries(e))if(s!=null){if(Array.isArray(s)){if(s.length===1){n.append(o,s[0]);continue}const a=r?`${o}[]`:o;for(const i of s)n.append(a,i);continue}n.append(o,s)}return n}var Wg="AI_DownloadError",Gg=`vercel.ai.error.${Wg}`,q6=Symbol.for(Gg),Kg,Yg,sr=class extends(Yg=Re,Kg=q6,Yg){constructor({url:e,statusCode:t,statusText:r,cause:n,message:o=n==null?`Failed to download ${e}: ${t} ${r}`:`Failed to download ${e}: ${n}`}){super({name:Wg,message:o,cause:n}),this[Kg]=!0,this.url=e,this.statusCode=t,this.statusText=r}static isInstance(e){return Re.hasMarker(e,Gg)}},Fd=2*1024*1024*1024;async function Qg({response:e,url:t,maxBytes:r=Fd}){const n=e.headers.get("content-length");if(n!=null){const u=parseInt(n,10);if(!isNaN(u)&&u>r)throw new sr({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes (Content-Length: ${u}).`})}const o=e.body;if(o==null)return new Uint8Array(0);const s=o.getReader(),a=[];let i=0;try{for(;;){const{done:u,value:f}=await s.read();if(u)break;if(i+=f.length,i>r)throw new sr({url:t,message:`Download of ${t} exceeded maximum size of ${r} bytes.`});a.push(f)}}finally{try{await s.cancel()}finally{s.releaseLock()}}const l=new Uint8Array(i);let c=0;for(const u of a)l.set(u,c),c+=u.length;return l}function Ml(e){let t;try{t=new URL(e)}catch{throw new sr({url:e,message:`Invalid URL: ${e}`})}if(t.protocol==="data:")return;if(t.protocol!=="http:"&&t.protocol!=="https:")throw new sr({url:e,message:`URL scheme must be http, https, or data, got ${t.protocol}`});const r=t.hostname;if(!r)throw new sr({url:e,message:"URL must have a hostname"});if(r==="localhost"||r.endsWith(".local")||r.endsWith(".localhost"))throw new sr({url:e,message:`URL with hostname ${r} is not allowed`});if(r.startsWith("[")&&r.endsWith("]")){const n=r.slice(1,-1);if(j6(n))throw new sr({url:e,message:`URL with IPv6 address ${r} is not allowed`});return}if(Xg(r)){if(Vd(r))throw new sr({url:e,message:`URL with IP address ${r} is not allowed`});return}}function Xg(e){const t=e.split(".");return t.length!==4?!1:t.every(r=>{const n=Number(r);return Number.isInteger(n)&&n>=0&&n<=255&&String(n)===r})}function Vd(e){const t=e.split(".").map(Number),[r,n]=t;return r===0||r===10||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===168}function j6(e){const t=e.toLowerCase();if(t==="::1"||t==="::")return!0;if(t.startsWith("::ffff:")){const r=t.slice(7);if(Xg(r))return Vd(r);const n=r.split(":");if(n.length===2){const o=parseInt(n[0],16),s=parseInt(n[1],16);if(!isNaN(o)&&!isNaN(s)){const a=o>>8&255,i=o&255,l=s>>8&255,c=s&255;return Vd(`${a}.${i}.${l}.${c}`)}}}return!!(t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe80"))}async function ey(e,t){var r,n;Ml(e);try{const o=await fetch(e,{signal:t?.abortSignal});if(o.redirected&&Ml(o.url),!o.ok)throw new sr({url:e,statusCode:o.status,statusText:o.statusText});const s=await Qg({response:o,url:e,maxBytes:(r=t?.maxBytes)!=null?r:Fd}),a=(n=o.headers.get("content-type"))!=null?n:void 0;return new Blob([s],a?{type:a}:void 0)}catch(o){throw sr.isInstance(o)?o:new sr({url:e,cause:o})}}var pa=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new vg({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Yt=pa();function Hd(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}function ho(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var L6=["fetch failed","failed to fetch"],D6=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function U6(e){if(!(e instanceof Error))return!1;const t=e.code;return!!(typeof t=="string"&&D6.includes(t))}function ty({error:e,url:t,requestBodyValues:r}){if(ho(e))return e;if(e instanceof TypeError&&L6.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new _t({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return U6(e)?new _t({message:`Cannot connect to API: ${e.message}`,cause:e,url:t,requestBodyValues:r,isRetryable:!0}):e}function fa(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function z6(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function Dn(e,...t){const r=new Headers(z6(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var ry="4.0.22",Z6=()=>globalThis.fetch,Ol=async({url:e,headers:t={},successfulResponseHandler:r,failedResponseHandler:n,abortSignal:o,fetch:s=Z6()})=>{try{const a=await s(e,{method:"GET",headers:Dn(t,`ai-sdk/provider-utils/${ry}`,fa()),signal:o}),i=ts(a);if(!a.ok){let l;try{l=await n({response:a,url:e,requestBodyValues:{}})}catch(c){throw ho(c)||_t.isInstance(c)?c:new _t({message:"Failed to process error response",cause:c,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:a,url:e,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(ho(l)||_t.isInstance(l))?l:new _t({message:"Failed to process successful response",cause:l,statusCode:a.status,url:e,responseHeaders:i,requestBodyValues:{}})}}catch(a){throw ty({error:a,url:e,requestBodyValues:{}})}};function ny(e){return e!=null}function F6({mediaType:e,url:t,supportedUrls:r}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(r).map(([n,o])=>{const s=n.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:o}:{mediaTypePrefix:s.replace(/\*/,""),regexes:o}}).filter(({mediaTypePrefix:n})=>e.startsWith(n)).flatMap(({regexes:n})=>n).some(n=>n.test(t))}function V6({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Pl({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Pl({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new Pl({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Pl({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function ss({settingValue:e,environmentVariableName:t}){if(typeof e=="string")return e;if(!(e!=null||typeof process>"u")&&(e=process.env[t],!(e==null||typeof e!="string")))return e}function H6(e){var t;const[r,n=""]=e.toLowerCase().split("/");return(t={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[n])!=null?t:n}var B6=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,J6=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function oy(e){const t=JSON.parse(e);return t===null||typeof t!="object"||B6.test(e)===!1&&J6.test(e)===!1?t:W6(t)}function W6(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&n.constructor!==null&&typeof n.constructor=="object"&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Bd(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return oy(e)}try{return oy(e)}finally{Error.stackTraceLimit=t}}function Jd(e){if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){e.additionalProperties=!1;const{properties:r}=e;if(r!=null)for(const n of Object.keys(r))r[n]=mo(r[n])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(mo):mo(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(mo)),e.allOf!=null&&(e.allOf=e.allOf.map(mo)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(mo));const{definitions:t}=e;if(t!=null)for(const r of Object.keys(t))t[r]=mo(t[r]);return e}function mo(e){return typeof e=="boolean"?e:Jd(e)}var G6=Symbol("Let zodToJsonSchema decide on which parser to use"),sy={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"},K6=e=>typeof e=="string"?{...sy,name:e}:{...sy,...e};function hr(){return{}}function Y6(e,t){var r,n,o;const s={type:"array"};return(r=e.type)!=null&&r._def&&((o=(n=e.type)==null?void 0:n._def)==null?void 0:o.typeName)!==G.ZodAny&&(s.items=at(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&(s.minItems=e.minLength.value),e.maxLength&&(s.maxItems=e.maxLength.value),e.exactLength&&(s.minItems=e.exactLength.value,s.maxItems=e.exactLength.value),s}function Q6(e){const t={type:"integer",format:"int64"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function X6(){return{type:"boolean"}}function ay(e,t){return at(e.type._def,t)}var e5=(e,t)=>at(e.innerType._def,t);function iy(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>iy(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return t5(e)}}var t5=e=>{const t={type:"integer",format:"unix-time"};for(const r of e.checks)switch(r.kind){case"min":t.minimum=r.value;break;case"max":t.maximum=r.value;break}return t};function r5(e,t){return{...at(e.innerType._def,t),default:e.defaultValue()}}function n5(e,t){return t.effectStrategy==="input"?at(e.schema._def,t):hr()}function o5(e){return{type:"string",enum:Array.from(e.values)}}var s5=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function a5(e,t){const r=[at(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),at(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(o=>!!o),n=[];return r.forEach(o=>{if(s5(o))n.push(...o.allOf);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){const{additionalProperties:a,...i}=o;s=i}n.push(s)}}),n.length?{allOf:n}:void 0}function i5(e){const t=typeof e.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(e.value)?"array":"object"}:{type:t==="bigint"?"integer":t,const:e.value}}var Wd=void 0,zr={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:()=>(Wd===void 0&&(Wd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Wd),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 ly(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"email":switch(t.emailStrategy){case"format:email":Zr(r,"email",n.message,t);break;case"format:idn-email":Zr(r,"idn-email",n.message,t);break;case"pattern:zod":Qt(r,zr.email,n.message,t);break}break;case"url":Zr(r,"uri",n.message,t);break;case"uuid":Zr(r,"uuid",n.message,t);break;case"regex":Qt(r,n.regex,n.message,t);break;case"cuid":Qt(r,zr.cuid,n.message,t);break;case"cuid2":Qt(r,zr.cuid2,n.message,t);break;case"startsWith":Qt(r,RegExp(`^${Gd(n.value,t)}`),n.message,t);break;case"endsWith":Qt(r,RegExp(`${Gd(n.value,t)}$`),n.message,t);break;case"datetime":Zr(r,"date-time",n.message,t);break;case"date":Zr(r,"date",n.message,t);break;case"time":Zr(r,"time",n.message,t);break;case"duration":Zr(r,"duration",n.message,t);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value;break;case"includes":{Qt(r,RegExp(Gd(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Zr(r,"ipv4",n.message,t),n.version!=="v4"&&Zr(r,"ipv6",n.message,t);break}case"base64url":Qt(r,zr.base64url,n.message,t);break;case"jwt":Qt(r,zr.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Qt(r,zr.ipv4Cidr,n.message,t),n.version!=="v4"&&Qt(r,zr.ipv6Cidr,n.message,t);break}case"emoji":Qt(r,zr.emoji(),n.message,t);break;case"ulid":{Qt(r,zr.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Zr(r,"binary",n.message,t);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Qt(r,zr.base64,n.message,t);break}}break}case"nanoid":Qt(r,zr.nanoid,n.message,t)}return r}function Gd(e,t){return t.patternStrategy==="escape"?c5(e):e}var l5=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function c5(e){let t="";for(let r=0;r<e.length;r++)l5.has(e[r])||(t+="\\"),t+=e[r];return t}function Zr(e,t,r,n){var o;e.format||(o=e.anyOf)!=null&&o.some(s=>s.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):e.format=t}function Qt(e,t,r,n){var o;e.pattern||(o=e.allOf)!=null&&o.some(s=>s.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:cy(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):e.pattern=cy(t,n)}function cy(e,t){var r;if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},o=n.i?e.source.toLowerCase():e.source;let s="",a=!1,i=!1,l=!1;for(let c=0;c<o.length;c++){if(a){s+=o[c],a=!1;continue}if(n.i){if(i){if(o[c].match(/[a-z]/)){l?(s+=o[c],s+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&((r=o[c+2])!=null&&r.match(/[a-z]/))?(s+=o[c],l=!0):s+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){s+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(n.m){if(o[c]==="^"){s+=`(^|(?<=[\r
551
551
  ]))`;continue}else if(o[c]==="$"){s+=`($|(?=[\r
552
552
  ]))`;continue}}if(n.s&&o[c]==="."){s+=i?`${o[c]}\r
553
553
  `:`[${o[c]}\r
554
- ]`;continue}s+=o[c],o[c]==="\\"?a=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function iy(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=Qe(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===B.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=sy(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===B.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===B.ZodBranded&&e.keyType._def.type._def.typeName===B.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=ny(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function ex(e,t){if(t.mapStrategy==="record")return iy(e,t);const r=Qe(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||pr(),n=Qe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||pr();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function tx(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function rx(){return{not:pr()}}function nx(){return{type:"null"}}var Bd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ox(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Bd&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Bd[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return sx(e,t)}var sx=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Qe(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function ax(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Bd[e.innerType._def.typeName],"null"]};const r=Qe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ix(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function lx(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=ux(i),c=Qe(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const s=cx(e,t);return s!==void 0&&(r.additionalProperties=s),r}function cx(e,t){if(e.catchall._def.typeName!=="ZodNever")return Qe(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function ux(e){try{return e.isOptional()}catch{return!0}}var dx=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return Qe(e.innerType._def,t);const n=Qe(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:pr()},n]}:pr()},px=(e,t)=>{if(t.pipeStrategy==="input")return Qe(e.in._def,t);if(t.pipeStrategy==="output")return Qe(e.out._def,t);const r=Qe(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Qe(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function fx(e,t){return Qe(e.type._def,t)}function hx(e,t){const n={type:"array",uniqueItems:!0,items:Qe(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function mx(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Qe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Qe(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Qe(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function gx(){return{not:pr()}}function yx(){return pr()}var vx=(e,t)=>Qe(e.innerType._def,t),_x=(e,t,r)=>{switch(t){case B.ZodString:return sy(e,r);case B.ZodNumber:return ix(e);case B.ZodObject:return lx(e,r);case B.ZodBigInt:return Z5(e);case B.ZodBoolean:return F5();case B.ZodDate:return oy(e,r);case B.ZodUndefined:return gx();case B.ZodNull:return nx();case B.ZodArray:return z5(e,r);case B.ZodUnion:case B.ZodDiscriminatedUnion:return ox(e,r);case B.ZodIntersection:return K5(e,r);case B.ZodTuple:return mx(e,r);case B.ZodRecord:return iy(e,r);case B.ZodLiteral:return Y5(e);case B.ZodEnum:return G5(e);case B.ZodNativeEnum:return tx(e);case B.ZodNullable:return ax(e,r);case B.ZodOptional:return dx(e,r);case B.ZodMap:return ex(e,r);case B.ZodSet:return hx(e,r);case B.ZodLazy:return()=>e.getter()._def;case B.ZodPromise:return fx(e,r);case B.ZodNaN:case B.ZodNever:return rx();case B.ZodEffects:return W5(e,r);case B.ZodAny:return pr();case B.ZodUnknown:return yx();case B.ZodDefault:return B5(e,r);case B.ZodBranded:return ny(e,r);case B.ZodReadonly:return vx(e,r);case B.ZodCatch:return V5(e,r);case B.ZodPipeline:return px(e,r);case B.ZodFunction:case B.ZodVoid:case B.ZodSymbol:return;default:return(n=>{})()}},wx=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function Qe(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==D5)return l}if(o&&!r){const l=bx(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=_x(e,e.typeName,t),i=typeof a=="function"?Qe(a(),t):a;if(i&&Tx(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var bx=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:wx(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),pr()):t.$refStrategy==="seen"?pr():void 0}},Tx=(e,t,r)=>(e.description&&(r.description=e.description),r),kx=e=>{const t=U5(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},Sx=(e,t)=>{var r;const n=kx(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,f])=>{var p;return{...c,[u]:(p=Qe(f._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:pr()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=Qe(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:pr(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[n.definitionPath]:o}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Wd=Symbol.for("vercel.ai.schema");function Te(e){let t;return()=>(t==null&&(t=e()),t)}function Qo(e,{validate:t}={}){return{[Wd]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function Cx(e){return typeof e=="object"&&e!==null&&Wd in e&&e[Wd]===!0&&"jsonSchema"in e&&"validate"in e}function po(e){return e==null?Qo({properties:{},additionalProperties:!1}):Cx(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?be(e):Ix(e):e()}function Ix(e){return Qo(()=>Fd(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async t=>{const r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new lo({value:t,cause:r.issues})}}})}function xx(e,t){var r;const n=(r=void 0)!=null?r:!1;return Qo(()=>Sx(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function Ex(e,t){var r;const n=(r=void 0)!=null?r:!1;return Qo(()=>Fd(Sm(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await Im(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function $x(e){return"_zod"in e}function be(e,t){return $x(e)?Ex(e):xx(e)}async function _t({value:e,schema:t,context:r}){const n=await Cr({value:e,schema:t,context:r});if(!n.success)throw lo.wrap({value:e,cause:n.error,context:r});return n.value}async function Cr({value:e,schema:t,context:r}){const n=po(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:lo.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:lo.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function ly({text:e,schema:t}){try{const r=Zd(e);return t==null?r:_t({value:r,schema:t})}catch(r){throw Cl.isInstance(r)||lo.isInstance(r)?r:new Cl({text:e,cause:r})}}async function Ir({text:e,schema:t}){try{const r=Zd(e);return t==null?{success:!0,value:r,rawValue:r}:await Cr({value:r,schema:t})}catch(r){return{success:!1,error:Cl.isInstance(r)?r:new Cl({text:e,cause:r}),rawValue:void 0}}}function cy(e){try{return Zd(e),!0}catch{return!1}}function uy({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Fo).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Ir({text:r,schema:t}))}}))}async function gn({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Cr({value:t[e],schema:r});if(!n.success)throw new mg({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var Rx=()=>globalThis.fetch,nr=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>py({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),dy=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>py({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),py=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=Rx()})=>{try{const i=await a(e,{method:"POST",headers:qn(t,`ai-sdk/provider-utils/${Xg}`,la()),body:r.content,signal:s}),l=Wo(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw co(u)||ht.isInstance(u)?u:new ht({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(co(c)||ht.isInstance(c))?c:new ht({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw Qg({error:i,url:e,requestBodyValues:r.values})}};function aO(e){return e}function fy(e){return{...e,type:"dynamic"}}function Px({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}function xr({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function Ut(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Xr=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Wo(n);if(a.trim()==="")return{responseHeaders:i,value:new ht({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await ly({text:a,schema:e});return{responseHeaders:i,value:new ht({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new ht({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},$l=e=>async({response:t})=>{const r=Wo(t);if(t.body==null)throw new d5({});return{responseHeaders:r,value:uy({stream:t.body,schema:e})}},or=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Ir({text:o,schema:e}),a=Wo(t);if(!s.success)throw new ht({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},Mx=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=Wo(e);if(!e.body)throw new ht({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new ht({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function hy(e){return e?.replace(/\/$/,"")}function Nx(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*Ox({execute:e,input:t,options:r}){const n=e(t,r);if(Nx(n)){let o;for await(const s of n)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await n}}var Gd,my;function Ax(){if(my)return Gd;my=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,f)=>{for(var p in f)e(u,p,{get:f[p],enumerable:!0})},s=(u,f,p,h)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of r(f))!n.call(u,m)&&m!==p&&e(u,m,{get:()=>f[m],enumerable:!(h=t(f,m))||h.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Gd=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Gd}var Jd,gy;function qx(){if(gy)return Jd;gy=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(f,p)=>{for(var h in p)e(f,h,{get:p[h],enumerable:!0})},s=(f,p,h,m)=>{if(p&&typeof p=="object"||typeof p=="function")for(let _ of r(p))!n.call(f,_)&&_!==h&&e(f,_,{get:()=>p[_],enumerable:!(m=t(p,_))||m.enumerable});return f},a=f=>s(e({},"__esModule",{value:!0}),f),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),Jd=a(i);var l=Ax();async function c(){return""}function u(){return""}return Jd}var yy=qx(),Lx="vercel.ai.gateway.error",Kd=Symbol.for(Lx),vy,_y,Jt=class Gw extends(_y=Error,vy=Kd,_y){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[vy]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return Gw.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&Kd in t&&t[Kd]===!0}},wy="GatewayAuthenticationError",jx=`vercel.ai.gateway.error.${wy}`,by=Symbol.for(jx),Ty,ky,Yd=class Jw extends(ky=Jt,Ty=by,ky){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Ty]=!0,this.name=wy,this.type="authentication_error"}static isInstance(t){return Jt.hasMarker(t)&&by in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let i;return t?i=`AI Gateway authentication failed: Invalid API key.
554
+ ]`;continue}s+=o[c],o[c]==="\\"?a=!0:i&&o[c]==="]"?i=!1:!i&&o[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function uy(e,t){var r,n,o,s,a,i;const l={type:"object",additionalProperties:(r=at(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]}))!=null?r:t.allowedAdditionalProperties};if(((n=e.keyType)==null?void 0:n._def.typeName)===G.ZodString&&((o=e.keyType._def.checks)!=null&&o.length)){const{type:c,...u}=ly(e.keyType._def,t);return{...l,propertyNames:u}}else{if(((s=e.keyType)==null?void 0:s._def.typeName)===G.ZodEnum)return{...l,propertyNames:{enum:e.keyType._def.values}};if(((a=e.keyType)==null?void 0:a._def.typeName)===G.ZodBranded&&e.keyType._def.type._def.typeName===G.ZodString&&((i=e.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=ay(e.keyType._def,t);return{...l,propertyNames:u}}}return l}function u5(e,t){if(t.mapStrategy==="record")return uy(e,t);const r=at(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||hr(),n=at(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||hr();return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function d5(e){const t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function p5(){return{not:hr()}}function f5(){return{type:"null"}}var Kd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function h5(e,t){const r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in Kd&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((o,s)=>{const a=Kd[s._def.typeName];return a&&!o.includes(a)?[...o,a]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((o,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...o,a];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){const o=n.filter((s,a,i)=>i.indexOf(s)===a);return{type:o.length>1?o:o[0],enum:r.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return m5(e,t)}var m5=(e,t)=>{const r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>at(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function g5(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[Kd[e.innerType._def.typeName],"null"]};const r=at(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function y5(e){const t={type:"number"};if(!e.checks)return t;for(const r of e.checks)switch(r.kind){case"int":t.type="integer";break;case"min":r.inclusive?t.minimum=r.value:t.exclusiveMinimum=r.value;break;case"max":r.inclusive?t.maximum=r.value:t.exclusiveMaximum=r.value;break;case"multipleOf":t.multipleOf=r.value;break}return t}function v5(e,t){const r={type:"object",properties:{}},n=[],o=e.shape();for(const a in o){let i=o[a];if(i===void 0||i._def===void 0)continue;const l=w5(i),c=at(i._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});c!==void 0&&(r.properties[a]=c,l||n.push(a))}n.length&&(r.required=n);const s=_5(e,t);return s!==void 0&&(r.additionalProperties=s),r}function _5(e,t){if(e.catchall._def.typeName!=="ZodNever")return at(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function w5(e){try{return e.isOptional()}catch{return!0}}var b5=(e,t)=>{var r;if(t.currentPath.toString()===((r=t.propertyPath)==null?void 0:r.toString()))return at(e.innerType._def,t);const n=at(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:hr()},n]}:hr()},k5=(e,t)=>{if(t.pipeStrategy==="input")return at(e.in._def,t);if(t.pipeStrategy==="output")return at(e.out._def,t);const r=at(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=at(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function T5(e,t){return at(e.type._def,t)}function S5(e,t){const n={type:"array",uniqueItems:!0,items:at(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function C5(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>at(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:at(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>at(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function x5(){return{not:hr()}}function I5(){return hr()}var $5=(e,t)=>at(e.innerType._def,t),E5=(e,t,r)=>{switch(t){case G.ZodString:return ly(e,r);case G.ZodNumber:return y5(e);case G.ZodObject:return v5(e,r);case G.ZodBigInt:return Q6(e);case G.ZodBoolean:return X6();case G.ZodDate:return iy(e,r);case G.ZodUndefined:return x5();case G.ZodNull:return f5();case G.ZodArray:return Y6(e,r);case G.ZodUnion:case G.ZodDiscriminatedUnion:return h5(e,r);case G.ZodIntersection:return a5(e,r);case G.ZodTuple:return C5(e,r);case G.ZodRecord:return uy(e,r);case G.ZodLiteral:return i5(e);case G.ZodEnum:return o5(e);case G.ZodNativeEnum:return d5(e);case G.ZodNullable:return g5(e,r);case G.ZodOptional:return b5(e,r);case G.ZodMap:return u5(e,r);case G.ZodSet:return S5(e,r);case G.ZodLazy:return()=>e.getter()._def;case G.ZodPromise:return T5(e,r);case G.ZodNaN:case G.ZodNever:return p5();case G.ZodEffects:return n5(e,r);case G.ZodAny:return hr();case G.ZodUnknown:return I5();case G.ZodDefault:return r5(e,r);case G.ZodBranded:return ay(e,r);case G.ZodReadonly:return $5(e,r);case G.ZodCatch:return e5(e,r);case G.ZodPipeline:return k5(e,r);case G.ZodFunction:case G.ZodVoid:case G.ZodSymbol:return;default:return(n=>{})()}},R5=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")};function at(e,t,r=!1){var n;const o=t.seen.get(e);if(t.override){const l=(n=t.override)==null?void 0:n.call(t,e,t,o,r);if(l!==G6)return l}if(o&&!r){const l=P5(o,t);if(l!==void 0)return l}const s={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,s);const a=E5(e,e.typeName,t),i=typeof a=="function"?at(a(),t):a;if(i&&M5(e,t,i),t.postProcess){const l=t.postProcess(i,e,t);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var P5=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:R5(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),hr()):t.$refStrategy==="seen"?hr():void 0}},M5=(e,t,r)=>(e.description&&(r.description=e.description),r),O5=e=>{const t=K6(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}},N5=(e,t)=>{var r;const n=O5(t);let o=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[u,f])=>{var p;return{...c,[u]:(p=at(f._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0))!=null?p:hr()}},{}):void 0;const s=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,a=(r=at(e._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1))!=null?r:hr(),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;i!==void 0&&(a.title=i);const l=s===void 0?o?{...a,[n.definitionPath]:o}:a:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...o,[s]:a}};return l.$schema="http://json-schema.org/draft-07/schema#",l},Yd=Symbol.for("vercel.ai.schema");function $e(e){let t;return()=>(t==null&&(t=e()),t)}function go(e,{validate:t}={}){return{[Yd]:!0,_type:void 0,get jsonSchema(){return typeof e=="function"&&(e=e()),e},validate:t}}function A5(e){return typeof e=="object"&&e!==null&&Yd in e&&e[Yd]===!0&&"jsonSchema"in e&&"validate"in e}function yo(e){return e==null?go({properties:{},additionalProperties:!1}):A5(e)?e:"~standard"in e?e["~standard"].vendor==="zod"?xe(e):q5(e):e()}function q5(e){return go(()=>Jd(e["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async t=>{const r=await e["~standard"].validate(t);return"value"in r?{success:!0,value:r.value}:{success:!1,error:new fo({value:t,cause:r.issues})}}})}function j5(e,t){var r;const n=(r=void 0)!=null?r:!1;return go(()=>N5(e,{$refStrategy:n?"root":"none"}),{validate:async o=>{const s=await e.safeParseAsync(o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function L5(e,t){var r;const n=(r=void 0)!=null?r:!1;return go(()=>Jd(Im(e,{target:"draft-7",io:"input",reused:n?"ref":"inline"})),{validate:async o=>{const s=await Em(e,o);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function D5(e){return"_zod"in e}function xe(e,t){return D5(e)?L5(e):j5(e)}async function Ct({value:e,schema:t,context:r}){const n=await xr({value:e,schema:t,context:r});if(!n.success)throw fo.wrap({value:e,cause:n.error,context:r});return n.value}async function xr({value:e,schema:t,context:r}){const n=yo(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};const o=await n.validate(e);return o.success?{success:!0,value:o.value,rawValue:e}:{success:!1,error:fo.wrap({value:e,cause:o.error,context:r}),rawValue:e}}catch(o){return{success:!1,error:fo.wrap({value:e,cause:o,context:r}),rawValue:e}}}async function dy({text:e,schema:t}){try{const r=Bd(e);return t==null?r:Ct({value:r,schema:t})}catch(r){throw Rl.isInstance(r)||fo.isInstance(r)?r:new Rl({text:e,cause:r})}}async function Ir({text:e,schema:t}){try{const r=Bd(e);return t==null?{success:!0,value:r,rawValue:r}:await xr({value:r,schema:t})}catch(r){return{success:!1,error:Rl.isInstance(r)?r:new Rl({text:e,cause:r}),rawValue:void 0}}}function py(e){try{return Bd(e),!0}catch{return!1}}function fy({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Yo).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await Ir({text:r,schema:t}))}}))}async function _n({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await xr({value:t[e],schema:r});if(!n.success)throw new vg({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var U5=()=>globalThis.fetch,ar=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>my({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),hy=async({url:e,headers:t,formData:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>my({url:e,headers:t,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),my=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=U5()})=>{try{const i=await a(e,{method:"POST",headers:Dn(t,`ai-sdk/provider-utils/${ry}`,fa()),body:r.content,signal:s}),l=ts(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw ho(u)||_t.isInstance(u)?u:new _t({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(ho(c)||_t.isInstance(c))?c:new _t({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw ty({error:i,url:e,requestBodyValues:r.values})}};function YN(e){return e}function Qd(e){return{...e,type:"dynamic"}}function z5({id:e,inputSchema:t}){return({execute:r,outputSchema:n,needsApproval:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider",id:e,args:c,inputSchema:t,outputSchema:n,execute:r,needsApproval:o,toModelOutput:s,onInputStart:a,onInputDelta:i,onInputAvailable:l})}function $r({id:e,inputSchema:t,outputSchema:r,supportsDeferredResults:n}){return({execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,...u})=>({type:"provider",id:e,args:u,inputSchema:t,outputSchema:r,execute:o,needsApproval:s,toModelOutput:a,onInputStart:i,onInputDelta:l,onInputAvailable:c,supportsDeferredResults:n})}async function Ht(e){return typeof e=="function"&&(e=e()),Promise.resolve(e)}var Xr=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=ts(n);if(a.trim()==="")return{responseHeaders:i,value:new _t({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await dy({text:a,schema:e});return{responseHeaders:i,value:new _t({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new _t({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},Nl=e=>async({response:t})=>{const r=ts(t);if(t.body==null)throw new b6({});return{responseHeaders:r,value:fy({stream:t.body,schema:e})}},ir=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await Ir({text:o,schema:e}),a=ts(t);if(!s.success)throw new _t({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}},Z5=()=>async({response:e,url:t,requestBodyValues:r})=>{const n=ts(e);if(!e.body)throw new _t({message:"Response body is empty",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0});try{const o=await e.arrayBuffer();return{responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new _t({message:"Failed to read response as array buffer",url:t,requestBodyValues:r,statusCode:e.status,responseHeaders:n,responseBody:void 0,cause:o})}};function gy(e){return e?.replace(/\/$/,"")}function F5(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}async function*V5({execute:e,input:t,options:r}){const n=e(t,r);if(F5(n)){let o;for await(const s of n)o=s,yield{type:"preliminary",output:s};yield{type:"final",output:o}}else yield{type:"final",output:await n}}var Xd,yy;function H5(){if(yy)return Xd;yy=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(u,f)=>{for(var p in f)e(u,p,{get:f[p],enumerable:!0})},s=(u,f,p,h)=>{if(f&&typeof f=="object"||typeof f=="function")for(let m of r(f))!n.call(u,m)&&m!==p&&e(u,m,{get:()=>f[m],enumerable:!(h=t(f,m))||h.enumerable});return u},a=u=>s(e({},"__esModule",{value:!0}),u),i={};o(i,{SYMBOL_FOR_REQ_CONTEXT:()=>l,getContext:()=>c}),Xd=a(i);const l=Symbol.for("@vercel/request-context");function c(){return globalThis[l]?.get?.()??{}}return Xd}var ep,vy;function B5(){if(vy)return ep;vy=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o=(f,p)=>{for(var h in p)e(f,h,{get:p[h],enumerable:!0})},s=(f,p,h,m)=>{if(p&&typeof p=="object"||typeof p=="function")for(let _ of r(p))!n.call(f,_)&&_!==h&&e(f,_,{get:()=>p[_],enumerable:!(m=t(p,_))||m.enumerable});return f},a=f=>s(e({},"__esModule",{value:!0}),f),i={};o(i,{getContext:()=>l.getContext,getVercelOidcToken:()=>c,getVercelOidcTokenSync:()=>u}),ep=a(i);var l=H5();async function c(){return""}function u(){return""}return ep}var _y=B5(),J5="vercel.ai.gateway.error",tp=Symbol.for(J5),wy,by,Xt=class nb extends(by=Error,wy=tp,by){constructor({message:t,statusCode:r=500,cause:n,generationId:o}){super(o?`${t} [${o}]`:t),this[wy]=!0,this.statusCode=r,this.cause=n,this.generationId=o}static isInstance(t){return nb.hasMarker(t)}static hasMarker(t){return typeof t=="object"&&t!==null&&tp in t&&t[tp]===!0}},ky="GatewayAuthenticationError",W5=`vercel.ai.gateway.error.${ky}`,Ty=Symbol.for(W5),Sy,Cy,rp=class ob extends(Cy=Xt,Sy=Ty,Cy){constructor({message:t="Authentication failed",statusCode:r=401,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Sy]=!0,this.name=ky,this.type="authentication_error"}static isInstance(t){return Xt.hasMarker(t)&&Ty in t}static createContextualError({apiKeyProvided:t,oidcTokenProvided:r,message:n="Authentication failed",statusCode:o=401,cause:s,generationId:a}){let i;return t?i=`AI Gateway authentication failed: Invalid API key.
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,9 +566,9 @@ 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 Jw({message:i,statusCode:o,cause:s,generationId:a})}},Sy="GatewayInvalidRequestError",Dx=`vercel.ai.gateway.error.${Sy}`,Cy=Symbol.for(Dx),Iy,xy,Ux=class extends(xy=Jt,Iy=Cy,xy){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Iy]=!0,this.name=Sy,this.type="invalid_request_error"}static isInstance(e){return Jt.hasMarker(e)&&Cy in e}},Ey="GatewayRateLimitError",zx=`vercel.ai.gateway.error.${Ey}`,$y=Symbol.for(zx),Ry,Py,Zx=class extends(Py=Jt,Ry=$y,Py){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Ry]=!0,this.name=Ey,this.type="rate_limit_exceeded"}static isInstance(e){return Jt.hasMarker(e)&&$y in e}},My="GatewayModelNotFoundError",Fx=`vercel.ai.gateway.error.${My}`,Ny=Symbol.for(Fx),Vx=Te(()=>be(T({modelId:d()}))),Oy,Ay,Hx=class extends(Ay=Jt,Oy=Ny,Ay){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[Oy]=!0,this.name=My,this.type="model_not_found",this.modelId=r}static isInstance(e){return Jt.hasMarker(e)&&Ny in e}},qy="GatewayInternalServerError",Bx=`vercel.ai.gateway.error.${qy}`,Ly=Symbol.for(Bx),jy,Dy,Uy=class extends(Dy=Jt,jy=Ly,Dy){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[jy]=!0,this.name=qy,this.type="internal_server_error"}static isInstance(e){return Jt.hasMarker(e)&&Ly in e}},zy="GatewayResponseError",Wx=`vercel.ai.gateway.error.${zy}`,Zy=Symbol.for(Wx),Fy,Vy,Gx=class extends(Vy=Jt,Fy=Zy,Vy){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:s}={}){super({message:e,statusCode:t,cause:o,generationId:s}),this[Fy]=!0,this.name=zy,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Jt.hasMarker(e)&&Zy in e}};async function Hy({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const a=await Cr({value:e,schema:Jx});if(!a.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new Gx({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:a.error,cause:n,generationId:f})}const i=a.value,l=i.error.type,c=i.error.message,u=(s=i.generationId)!=null?s:void 0;switch(l){case"authentication_error":return Yd.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new Ux({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new Zx({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const f=await Cr({value:i.error.param,schema:Vx});return new Hx({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Uy({message:c,statusCode:t,cause:n,generationId:u});default:return new Uy({message:c,statusCode:t,cause:n,generationId:u})}}var Jx=Te(()=>be(T({error:T({message:d(),type:d().nullish(),param:xe().nullish(),code:ae([d(),O()]).nullish()}),generationId:d().nullish()}))),By="GatewayTimeoutError",Kx=`vercel.ai.gateway.error.${By}`,Wy=Symbol.for(Kx),Gy,Jy,Ky=class Kw extends(Jy=Jt,Gy=Wy,Jy){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Gy]=!0,this.name=By,this.type="timeout_error"}static isInstance(t){return Jt.hasMarker(t)&&Wy in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
569
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new ob({message:i,statusCode:o,cause:s,generationId:a})}},xy="GatewayInvalidRequestError",G5=`vercel.ai.gateway.error.${xy}`,Iy=Symbol.for(G5),$y,Ey,K5=class extends(Ey=Xt,$y=Iy,Ey){constructor({message:e="Invalid request",statusCode:t=400,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[$y]=!0,this.name=xy,this.type="invalid_request_error"}static isInstance(e){return Xt.hasMarker(e)&&Iy in e}},Ry="GatewayRateLimitError",Y5=`vercel.ai.gateway.error.${Ry}`,Py=Symbol.for(Y5),My,Oy,Q5=class extends(Oy=Xt,My=Py,Oy){constructor({message:e="Rate limit exceeded",statusCode:t=429,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[My]=!0,this.name=Ry,this.type="rate_limit_exceeded"}static isInstance(e){return Xt.hasMarker(e)&&Py in e}},Ny="GatewayModelNotFoundError",X5=`vercel.ai.gateway.error.${Ny}`,Ay=Symbol.for(X5),e$=$e(()=>xe(k({modelId:d()}))),qy,jy,t$=class extends(jy=Xt,qy=Ay,jy){constructor({message:e="Model not found",statusCode:t=404,modelId:r,cause:n,generationId:o}={}){super({message:e,statusCode:t,cause:n,generationId:o}),this[qy]=!0,this.name=Ny,this.type="model_not_found",this.modelId=r}static isInstance(e){return Xt.hasMarker(e)&&Ay in e}},Ly="GatewayInternalServerError",r$=`vercel.ai.gateway.error.${Ly}`,Dy=Symbol.for(r$),Uy,zy,Zy=class extends(zy=Xt,Uy=Dy,zy){constructor({message:e="Internal server error",statusCode:t=500,cause:r,generationId:n}={}){super({message:e,statusCode:t,cause:r,generationId:n}),this[Uy]=!0,this.name=Ly,this.type="internal_server_error"}static isInstance(e){return Xt.hasMarker(e)&&Dy in e}},Fy="GatewayResponseError",n$=`vercel.ai.gateway.error.${Fy}`,Vy=Symbol.for(n$),Hy,By,o$=class extends(By=Xt,Hy=Vy,By){constructor({message:e="Invalid response from Gateway",statusCode:t=502,response:r,validationError:n,cause:o,generationId:s}={}){super({message:e,statusCode:t,cause:o,generationId:s}),this[Hy]=!0,this.name=Fy,this.type="response_error",this.response=r,this.validationError=n}static isInstance(e){return Xt.hasMarker(e)&&Vy in e}};async function Jy({response:e,statusCode:t,defaultMessage:r="Gateway request failed",cause:n,authMethod:o}){var s;const a=await xr({value:e,schema:s$});if(!a.success){const f=typeof e=="object"&&e!==null&&"generationId"in e?e.generationId:void 0;return new o$({message:`Invalid error response format: ${r}`,statusCode:t,response:e,validationError:a.error,cause:n,generationId:f})}const i=a.value,l=i.error.type,c=i.error.message,u=(s=i.generationId)!=null?s:void 0;switch(l){case"authentication_error":return rp.createContextualError({apiKeyProvided:o==="api-key",oidcTokenProvided:o==="oidc",statusCode:t,cause:n,generationId:u});case"invalid_request_error":return new K5({message:c,statusCode:t,cause:n,generationId:u});case"rate_limit_exceeded":return new Q5({message:c,statusCode:t,cause:n,generationId:u});case"model_not_found":{const f=await xr({value:i.error.param,schema:e$});return new t$({message:c,statusCode:t,modelId:f.success?f.value.modelId:void 0,cause:n,generationId:u})}case"internal_server_error":return new Zy({message:c,statusCode:t,cause:n,generationId:u});default:return new Zy({message:c,statusCode:t,cause:n,generationId:u})}}var s$=$e(()=>xe(k({error:k({message:d(),type:d().nullish(),param:Ne().nullish(),code:le([d(),N()]).nullish()}),generationId:d().nullish()}))),Wy="GatewayTimeoutError",a$=`vercel.ai.gateway.error.${Wy}`,Gy=Symbol.for(a$),Ky,Yy,Qy=class sb extends(Yy=Xt,Ky=Gy,Yy){constructor({message:t="Request timed out",statusCode:r=408,cause:n,generationId:o}={}){super({message:t,statusCode:r,cause:n,generationId:o}),this[Ky]=!0,this.name=Wy,this.type="timeout_error"}static isInstance(t){return Xt.hasMarker(t)&&Gy in t}static createTimeoutError({originalMessage:t,statusCode:r=408,cause:n,generationId:o}){const s=`Gateway request timed out: ${t}
570
570
 
571
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new Kw({message:s,statusCode:r,cause:n,generationId:o})}};function Yy(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function fr(e,t){var r;return Jt.isInstance(e)?e:Yy(e)?Ky.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):ht.isInstance(e)?e.cause&&Yy(e.cause)?Ky.createTimeoutError({originalMessage:e.message,cause:e}):await Hy({response:Yx(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await Hy({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function Yx(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var Qy="ai-gateway-auth-method";async function yn(e){const t=await Cr({value:e[Qy],schema:Qx});return t.success?t.value:void 0}var Qx=Te(()=>be(ae([P("api-key"),P("oidc")]))),Xy=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await El({url:`${this.config.baseURL}/config`,headers:await Ut(this.config.headers()),successfulResponseHandler:or(Xx),failedResponseHandler:Xr({errorSchema:Tt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await fr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await El({url:`${e.origin}/v1/credits`,headers:await Ut(this.config.headers()),successfulResponseHandler:or(eE),failedResponseHandler:Xr({errorSchema:Tt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await fr(e)}}},Xx=Te(()=>be(T({models:q(T({id:d(),name:d(),description:d().nullish(),pricing:T({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:T({specificationVersion:P("v3"),provider:d(),modelId:d()}),modelType:de(["embedding","image","language","video"]).nullish()}))}))),eE=Te(()=>be(T({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),tE=class{constructor(e){this.config=e}async getSpendReport(e){try{const t=new URL(this.config.baseURL),r=new URLSearchParams;r.set("start_date",e.startDate),r.set("end_date",e.endDate),e.groupBy&&r.set("group_by",e.groupBy),e.datePart&&r.set("date_part",e.datePart),e.userId&&r.set("user_id",e.userId),e.model&&r.set("model",e.model),e.provider&&r.set("provider",e.provider),e.credentialType&&r.set("credential_type",e.credentialType),e.tags&&e.tags.length>0&&r.set("tags",e.tags.join(","));const{value:n}=await El({url:`${t.origin}/v1/report?${r.toString()}`,headers:await Ut(this.config.headers()),successfulResponseHandler:or(rE),failedResponseHandler:Xr({errorSchema:Tt(),errorToMessage:o=>o}),fetch:this.config.fetch});return n}catch(t){throw await fr(t)}}},rE=Te(()=>be(T({results:q(T({day:d().optional(),hour:d().optional(),user:d().optional(),model:d().optional(),tag:d().optional(),provider:d().optional(),credential_type:de(["byok","system"]).optional(),total_cost:O(),market_cost:O().optional(),input_tokens:O().optional(),output_tokens:O().optional(),cached_input_tokens:O().optional(),cache_creation_input_tokens:O().optional(),reasoning_tokens:O().optional(),request_count:O().optional()}).transform(({credential_type:e,total_cost:t,market_cost:r,input_tokens:n,output_tokens:o,cached_input_tokens:s,cache_creation_input_tokens:a,reasoning_tokens:i,request_count:l,...c})=>({...c,...e!==void 0?{credentialType:e}:{},totalCost:t,...r!==void 0?{marketCost:r}:{},...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...s!==void 0?{cachedInputTokens:s}:{},...a!==void 0?{cacheCreationInputTokens:a}:{},...i!==void 0?{reasoningTokens:i}:{},...l!==void 0?{requestCount:l}:{}})))}))),nE=class{constructor(e){this.config=e}async getGenerationInfo(e){try{const t=new URL(this.config.baseURL),{value:r}=await El({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await Ut(this.config.headers()),successfulResponseHandler:or(oE),failedResponseHandler:Xr({errorSchema:Tt(),errorToMessage:n=>n}),fetch:this.config.fetch});return r}catch(t){throw await fr(t)}}},oE=Te(()=>be(T({data:T({id:d(),total_cost:O(),upstream_inference_cost:O(),usage:O(),created_at:d(),model:d(),is_byok:ve(),provider_name:d(),streamed:ve(),finish_reason:d(),latency:O(),generation_time:O(),native_tokens_prompt:O(),native_tokens_completion:O(),native_tokens_reasoning:O(),native_tokens_cached:O(),native_tokens_cache_creation:O(),billable_web_search_calls:O()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:r,is_byok:n,provider_name:o,finish_reason:s,generation_time:a,native_tokens_prompt:i,native_tokens_completion:l,native_tokens_reasoning:c,native_tokens_cached:u,native_tokens_cache_creation:f,billable_web_search_calls:p,...h})=>({...h,totalCost:e,upstreamInferenceCost:t,createdAt:r,isByok:n,providerName:o,finishReason:s,generationTime:a,promptTokens:i,completionTokens:l,reasoningTokens:c,cachedTokens:u,cacheCreationTokens:f,billableWebSearchCalls:p}))}).transform(({data:e})=>e))),sE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Ut(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await nr({url:this.getUrl(),headers:Dt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Ut(this.config.o11yHeaders)),body:t,successfulResponseHandler:or(Tt()),failedResponseHandler:Xr({errorSchema:Tt(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:r}}catch(s){throw await fr(s,await yn(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Ut(this.config.headers());try{const{value:s,responseHeaders:a}=await nr({url:this.getUrl(),headers:Dt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Ut(this.config.o11yHeaders)),body:t,successfulResponseHandler:$l(Tt()),failedResponseHandler:Xr({errorSchema:Tt(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw await fr(s,await yn(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const o=Uint8Array.from(n.data),s=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},aE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await Ut(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await nr({url:this.getUrl(),headers:Dt(s,t??{},this.getModelConfigHeaders(),await Ut(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:or(iE),failedResponseHandler:Xr({errorSchema:Tt(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l},warnings:[]}}catch(a){throw await fr(a,await yn(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},iE=Te(()=>be(T({embeddings:q(q(O())),usage:T({tokens:O()}).nullish(),providerMetadata:_e(d(),_e(d(),xe())).optional()}))),lE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,files:s,mask:a,providerOptions:i,headers:l,abortSignal:c}){var u,f,p,h;const m=await Ut(this.config.headers());try{const{responseHeaders:_,value:y,rawValue:w}=await nr({url:this.getUrl(),headers:Dt(m,l??{},this.getModelConfigHeaders(),await Ut(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...i&&{providerOptions:i},...s&&{files:s.map(v=>ev(v))},...a&&{mask:ev(a)}},successfulResponseHandler:or(pE),failedResponseHandler:Xr({errorSchema:Tt(),errorToMessage:v=>v}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:y.images,warnings:(u=y.warnings)!=null?u:[],providerMetadata:y.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:_},...y.usage!=null&&{usage:{inputTokens:(f=y.usage.inputTokens)!=null?f:void 0,outputTokens:(p=y.usage.outputTokens)!=null?p:void 0,totalTokens:(h=y.usage.totalTokens)!=null?h:void 0}}}}catch(_){throw await fr(_,await yn(m))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function ev(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Jo(e.data)}:e}var cE=T({images:q(xe()).optional()}).catchall(xe()),uE=Ve("type",[T({type:P("unsupported"),feature:d(),details:d().optional()}),T({type:P("compatibility"),feature:d(),details:d().optional()}),T({type:P("other"),message:d()})]),dE=T({inputTokens:O().nullish(),outputTokens:O().nullish(),totalTokens:O().nullish()}),pE=T({images:q(d()),warnings:q(uE).optional(),providerMetadata:_e(d(),cE).optional(),usage:dE.optional()}),fE=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:n,duration:o,fps:s,seed:a,image:i,providerOptions:l,headers:c,abortSignal:u}){var f;const p=await Ut(this.config.headers());try{const{responseHeaders:h,value:m}=await nr({url:this.getUrl(),headers:Dt(p,c??{},this.getModelConfigHeaders(),await Ut(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...s&&{fps:s},...a&&{seed:a},...l&&{providerOptions:l},...i&&{image:hE(i)}},successfulResponseHandler:async({response:_,url:y,requestBodyValues:w})=>{if(_.body==null)throw new ht({message:"SSE response body is empty",url:y,requestBodyValues:w,statusCode:_.status});const g=uy({stream:_.body,schema:vE}).getReader(),{done:S,value:b}=await g.read();if(g.releaseLock(),S||!b)throw new ht({message:"SSE stream ended without a data event",url:y,requestBodyValues:w,statusCode:_.status});if(!b.success)throw new ht({message:"Failed to parse video SSE event",cause:b.error,url:y,requestBodyValues:w,statusCode:_.status});const k=b.value;if(k.type==="error")throw new ht({message:k.message,statusCode:k.statusCode,url:y,requestBodyValues:w,responseHeaders:Object.fromEntries([..._.headers]),responseBody:JSON.stringify(k),data:{error:{message:k.message,type:k.errorType,param:k.param}}});return{value:{videos:k.videos,warnings:k.warnings,providerMetadata:k.providerMetadata},responseHeaders:Object.fromEntries([..._.headers])}},failedResponseHandler:Xr({errorSchema:Tt(),errorToMessage:_=>_}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:m.videos,warnings:(f=m.warnings)!=null?f:[],providerMetadata:m.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(h){throw await fr(h,await yn(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function hE(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:Jo(e.data)}:e}var mE=T({videos:q(xe()).optional()}).catchall(xe()),gE=ae([T({type:P("url"),url:d(),mediaType:d()}),T({type:P("base64"),data:d(),mediaType:d()})]),yE=Ve("type",[T({type:P("unsupported"),feature:d(),details:d().optional()}),T({type:P("compatibility"),feature:d(),details:d().optional()}),T({type:P("other"),message:d()})]),vE=Ve("type",[T({type:P("result"),videos:q(gE),warnings:q(yE).optional(),providerMetadata:_e(d(),mE).optional()}),T({type:P("error"),message:d(),errorType:d(),statusCode:O(),param:xe().nullable()})]),_E=Te(()=>be(Qt({objective:Fe().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:un(Fe()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Es(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:br().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:Qt({include_domains:un(Fe()).optional().describe("List of domains to include in search results."),exclude_domains:un(Fe()).optional().describe("List of domains to exclude from search results."),after_date:Fe().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:Qt({max_chars_per_result:br().optional().describe("Maximum characters per result."),max_chars_total:br().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:Qt({max_age_seconds:br().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),wE=Te(()=>be(ji([Qt({searchId:Fe(),results:un(Qt({url:Fe(),title:Fe(),excerpt:Fe(),publishDate:Fe().nullable().optional(),relevanceScore:br().optional()}))}),Qt({error:Es(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:br().optional(),message:Fe()})]))),bE=xr({id:"gateway.parallel_search",inputSchema:_E,outputSchema:wE}),TE=(e={})=>bE(e),kE=Te(()=>be(Qt({query:ji([Fe(),un(Fe())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:br().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:br().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:br().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Fe().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:un(Fe()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:un(Fe()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Fe().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Fe().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Fe().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Fe().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Es(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),SE=Te(()=>be(ji([Qt({results:un(Qt({title:Fe(),url:Fe(),snippet:Fe(),date:Fe().optional(),lastUpdated:Fe().optional()})),id:Fe()}),Qt({error:Es(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:br().optional(),message:Fe()})]))),CE=xr({id:"gateway.perplexity_search",inputSchema:kE,outputSchema:SE}),IE=(e={})=>CE(e),xE={parallelSearch:TE,perplexitySearch:IE};async function EE(){var e;return(e=yy.getContext().headers)==null?void 0:e["x-vercel-id"]}var $E="3.0.83",RE="0.0.1";function PE(e={}){var t,r;let n=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(r=hy(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const w=await NE(e);return qn({Authorization:`Bearer ${w.token}`,"ai-gateway-protocol-version":RE,[Qy]:w.authMethod,...e.headers},`ai-sdk/gateway/${$E}`)}catch(w){throw Yd.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:w})}},c=()=>{const w=Yo({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=Yo({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),g=Yo({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),S=Yo({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const b=await EE();return{...w&&{"ai-o11y-deployment-id":w},...v&&{"ai-o11y-environment":v},...g&&{"ai-o11y-region":g},...b&&{"ai-o11y-request-id":b},...S&&{"ai-o11y-project-id":S}}}},u=w=>new sE(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f=async()=>{var w,v,g;const S=(g=(v=(w=e._internal)==null?void 0:w.currentDate)==null?void 0:v.call(w).getTime())!=null?g:Date.now();return(!n||S-a>s)&&(a=S,n=new Xy({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(b=>(o=b,b)).catch(async b=>{throw await fr(b,await yn(await l()))})),o?Promise.resolve(o):n},p=async()=>new Xy({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async w=>{throw await fr(w,await yn(await l()))}),h=async w=>new tE({baseURL:i,headers:l,fetch:e.fetch}).getSpendReport(w).catch(async v=>{throw await fr(v,await yn(await l()))}),m=async w=>new nE({baseURL:i,headers:l,fetch:e.fetch}).getGenerationInfo(w).catch(async v=>{throw await fr(v,await yn(await l()))}),_=function(w){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(w)};_.specificationVersion="v3",_.getAvailableModels=f,_.getCredits=p,_.getSpendReport=h,_.getGenerationInfo=m,_.imageModel=w=>new lE(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),_.languageModel=u;const y=w=>new aE(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return _.embeddingModel=y,_.textEmbeddingModel=y,_.videoModel=w=>new fE(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),_.chat=_.languageModel,_.embedding=_.embeddingModel,_.image=_.imageModel,_.video=_.videoModel,_.tools=xE,_}var ME=PE();async function NE(e){const t=Yo({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await yy.getVercelOidcToken(),authMethod:"oidc"}}var OE=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},fo="1.9.0",tv=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function AE(e){var t=new Set([e]),r=new Set,n=e.match(tv);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===e};function s(i){return r.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;var c=l.match(tv);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?s(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(l):s(l):o.minor<=u.minor?a(l):s(l)}}var qE=AE(fo),LE=fo.split(".")[0],ca=Symbol.for("opentelemetry.js.api."+LE),ua=OE;function da(e,t,r,n){var o;n===void 0&&(n=!1);var s=ua[ca]=(o=ua[ca])!==null&&o!==void 0?o:{version:fo};if(!n&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(a.stack||a.message),!1}if(s.version!==fo){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+fo);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+fo+"."),!0}function ho(e){var t,r,n=(t=ua[ca])===null||t===void 0?void 0:t.version;if(!(!n||!qE(n)))return(r=ua[ca])===null||r===void 0?void 0:r[e]}function pa(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+fo+".");var r=ua[ca];r&&delete r[e]}var jE=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},DE=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},UE=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return fa("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return fa("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return fa("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return fa("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return fa("verbose",this._namespace,t)},e})();function fa(e,t,r){var n=ho("diag");if(n)return r.unshift(t),n[e].apply(n,DE([],jE(r),!1))}var hr;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(hr||(hr={}));function zE(e,t){e<hr.NONE?e=hr.NONE:e>hr.ALL&&(e=hr.ALL),t=t||{};function r(n,o){var s=t[n];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:r("error",hr.ERROR),warn:r("warn",hr.WARN),info:r("info",hr.INFO),debug:r("debug",hr.DEBUG),verbose:r("verbose",hr.VERBOSE)}}var ZE=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},FE=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},VE="diag",en=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=ho("diag");if(i)return i[o].apply(i,FE([],ZE(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:hr.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=ho("diag"),f=zE((i=s.logLevel)!==null&&i!==void 0?i:hr.INFO,o);if(u&&!s.suppressOverrideMessage){var p=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),f.warn("Current logger will overwrite one already registered from "+p)}return da("diag",f,r,!0)};r.setLogger=n,r.disable=function(){pa(VE,r)},r.createComponentLogger=function(o){return new UE(o)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),HE=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},BE=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},WE=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var r=this._entries.get(t);if(r)return Object.assign({},r)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var r=HE(t,2),n=r[0],o=r[1];return[n,o]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var s=new e(this._entries);try{for(var a=BE(n),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e})();en.instance();function GE(e){return e===void 0&&(e={}),new WE(new Map(Object.entries(e)))}function rv(e){return Symbol.for(e)}var JE=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var s=new e(r._currentContext);return s._currentContext.set(n,o),s},r.deleteValue=function(n){var o=new e(r._currentContext);return o._currentContext.delete(n),o}}return e})(),KE=new JE,mo=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),YE=(function(){function e(){}return e.prototype.createGauge=function(t,r){return i8},e.prototype.createHistogram=function(t,r){return l8},e.prototype.createCounter=function(t,r){return a8},e.prototype.createUpDownCounter=function(t,r){return c8},e.prototype.createObservableGauge=function(t,r){return d8},e.prototype.createObservableCounter=function(t,r){return u8},e.prototype.createObservableUpDownCounter=function(t,r){return p8},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Rl=(function(){function e(){}return e})(),QE=(function(e){mo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Rl),XE=(function(e){mo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Rl),e8=(function(e){mo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Rl),t8=(function(e){mo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Rl),Qd=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),r8=(function(e){mo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Qd),n8=(function(e){mo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Qd),o8=(function(e){mo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(Qd),s8=new YE,a8=new QE,i8=new e8,l8=new t8,c8=new XE,u8=new r8,d8=new n8,p8=new o8,f8={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},h8={set:function(e,t,r){e!=null&&(e[t]=r)}},m8=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},g8=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},y8=(function(){function e(){}return e.prototype.active=function(){return KE},e.prototype.with=function(t,r,n){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return r.call.apply(r,g8([n],m8(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),v8=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},_8=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},Xd="context",w8=new y8,Pl=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return da(Xd,t,en.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,_8([t,r,n],v8(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return ho(Xd)||w8},e.prototype.disable=function(){this._getContextManager().disable(),pa(Xd,en.instance())},e})(),ep;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(ep||(ep={}));var nv="0000000000000000",ov="00000000000000000000000000000000",b8={traceId:ov,spanId:nv,traceFlags:ep.NONE},ha=(function(){function e(t){t===void 0&&(t=b8),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,r){},e})(),tp=rv("OpenTelemetry Context Key SPAN");function rp(e){return e.getValue(tp)||void 0}function T8(){return rp(Pl.getInstance().active())}function np(e,t){return e.setValue(tp,t)}function k8(e){return e.deleteValue(tp)}function S8(e,t){return np(e,new ha(t))}function sv(e){var t;return(t=rp(e))===null||t===void 0?void 0:t.spanContext()}var C8=/^([0-9a-f]{32})$/i,I8=/^[0-9a-f]{16}$/i;function x8(e){return C8.test(e)&&e!==ov}function E8(e){return I8.test(e)&&e!==nv}function av(e){return x8(e.traceId)&&E8(e.spanId)}function $8(e){return new ha(e)}var op=Pl.getInstance(),iv=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=op.active());var o=!!r?.root;if(o)return new ha;var s=n&&sv(n);return R8(s)&&av(s)?new ha(s):new ha},e.prototype.startActiveSpan=function(t,r,n,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=n):(s=r,a=n,i=o);var l=a??op.active(),c=this.startSpan(t,s,l),u=np(l,c);return op.with(u,i,void 0,c)}},e})();function R8(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var P8=new iv,M8=(function(){function e(t,r,n,o){this._provider=t,this.name=r,this.version=n,this.options=o}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):P8},e})(),N8=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new iv},e})(),O8=new N8,lv=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new M8(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:O8},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,r,n)},e})(),Ml;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(Ml||(Ml={}));var cv=Pl.getInstance();en.instance();var A8=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return s8},e})(),q8=new A8,sp="metrics",L8=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return da(sp,t,en.instance())},e.prototype.getMeterProvider=function(){return ho(sp)||q8},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){pa(sp,en.instance())},e})();L8.getInstance();var j8=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),ap=rv("OpenTelemetry Baggage Key");function uv(e){return e.getValue(ap)||void 0}function D8(){return uv(Pl.getInstance().active())}function U8(e,t){return e.setValue(ap,t)}function z8(e){return e.deleteValue(ap)}var ip="propagation",Z8=new j8,F8=(function(){function e(){this.createBaggage=GE,this.getBaggage=uv,this.getActiveBaggage=D8,this.setBaggage=U8,this.deleteBaggage=z8}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return da(ip,t,en.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=h8),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=f8),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){pa(ip,en.instance())},e.prototype._getGlobalPropagator=function(){return ho(ip)||Z8},e})();F8.getInstance();var lp="trace",V8=(function(){function e(){this._proxyTracerProvider=new lv,this.wrapSpanContext=$8,this.isSpanContextValid=av,this.deleteSpan=k8,this.getSpan=rp,this.getActiveSpan=T8,this.getSpanContext=sv,this.setSpan=np,this.setSpanContext=S8}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=da(lp,this._proxyTracerProvider,en.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return ho(lp)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){pa(lp,en.instance()),this._proxyTracerProvider=new lv},e})(),H8=V8.getInstance(),B8=Object.defineProperty,W8=(e,t)=>{for(var r in t)B8(e,r,{get:t[r],enumerable:!0})},dv="AI_InvalidArgumentError",pv=`vercel.ai.error.${dv}`,G8=Symbol.for(pv),fv,tn=class extends ke{constructor({parameter:t,value:r,message:n}){super({name:dv,message:`Invalid argument for parameter ${t}: ${n}`}),this[fv]=!0,this.parameter=t,this.value=r}static isInstance(t){return ke.hasMarker(t,pv)}};fv=G8;var hv="AI_InvalidToolApprovalError",mv=`vercel.ai.error.${hv}`,J8=Symbol.for(mv),gv,K8=class extends ke{constructor({approvalId:e}){super({name:hv,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[gv]=!0,this.approvalId=e}static isInstance(e){return ke.hasMarker(e,mv)}};gv=J8;var yv="AI_InvalidToolInputError",vv=`vercel.ai.error.${yv}`,Y8=Symbol.for(vv),_v,cp=class extends ke{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${ao(r)}`}){super({name:yv,message:n,cause:r}),this[_v]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return ke.hasMarker(e,vv)}};_v=Y8;var wv="AI_ToolCallNotFoundForApprovalError",bv=`vercel.ai.error.${wv}`,Q8=Symbol.for(bv),Tv,up=class extends ke{constructor({toolCallId:e,approvalId:t}){super({name:wv,message:`Tool call "${e}" not found for approval request "${t}".`}),this[Tv]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return ke.hasMarker(e,bv)}};Tv=Q8;var kv="AI_MissingToolResultsError",Sv=`vercel.ai.error.${kv}`,X8=Symbol.for(Sv),Cv,Iv=class extends ke{constructor({toolCallIds:e}){super({name:kv,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Cv]=!0,this.toolCallIds=e}static isInstance(e){return ke.hasMarker(e,Sv)}};Cv=X8;var xv="AI_NoObjectGeneratedError",Ev=`vercel.ai.error.${xv}`,e$=Symbol.for(Ev),$v,Ln=class extends ke{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:xv,message:e,cause:t}),this[$v]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return ke.hasMarker(e,Ev)}};$v=e$;var Rv="AI_NoOutputGeneratedError",Pv=`vercel.ai.error.${Rv}`,t$=Symbol.for(Pv),Mv,Nv=class extends ke{constructor({message:e="No output generated.",cause:t}={}){super({name:Rv,message:e,cause:t}),this[Mv]=!0}static isInstance(e){return ke.hasMarker(e,Pv)}};Mv=t$;var Ov="AI_NoSuchToolError",Av=`vercel.ai.error.${Ov}`,r$=Symbol.for(Av),qv,dp=class extends ke{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:Ov,message:r}),this[qv]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return ke.hasMarker(e,Av)}};qv=r$;var Lv="AI_ToolCallRepairError",jv=`vercel.ai.error.${Lv}`,n$=Symbol.for(jv),Dv,o$=class extends ke{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${ao(e)}`}){super({name:Lv,message:r,cause:e}),this[Dv]=!0,this.originalError=t}static isInstance(e){return ke.hasMarker(e,jv)}};Dv=n$;var s$=class extends ke{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Uv="AI_UIMessageStreamError",zv=`vercel.ai.error.${Uv}`,a$=Symbol.for(zv),Zv,Xo=class extends ke{constructor({chunkType:e,chunkId:t,message:r}){super({name:Uv,message:r}),this[Zv]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return ke.hasMarker(e,zv)}};Zv=a$;var Fv="AI_InvalidMessageRoleError",Vv=`vercel.ai.error.${Fv}`,i$=Symbol.for(Vv),Hv,l$=class extends ke{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Fv,message:t}),this[Hv]=!0,this.role=e}static isInstance(e){return ke.hasMarker(e,Vv)}};Hv=i$;var Bv="AI_RetryError",Wv=`vercel.ai.error.${Bv}`,c$=Symbol.for(Wv),Gv,Jv=class extends ke{constructor({message:e,reason:t,errors:r}){super({name:Bv,message:e}),this[Gv]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return ke.hasMarker(e,Wv)}};Gv=c$;function go(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function Fr(e){for(const t of go(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function u$({warning:e,provider:t,model:r}){const n=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let o=`${n} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${n} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${n} ${e.message}`;default:return`${n} ${JSON.stringify(e,null,2)}`}}var d$="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Kv=!1,pp=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}Kv||(Kv=!0,console.info(d$));for(const r of e.warnings)console.warn(u$({warning:r,provider:e.provider,model:e.model}))}};function p$({provider:e,modelId:t}){pp({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function f$(e){return e.specificationVersion==="v3"?e:(p$({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{const o=await t.doGenerate(...n);return{...o,finishReason:Yv(o.finishReason),usage:Qv(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:h$(o.stream)}};default:return t[r]}}}))}function h$(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:Yv(t.finishReason),usage:Qv(t.usage)});break;default:r.enqueue(t);break}}}))}function Yv(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function Qv(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function Nl(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new s$({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return f$(e)}return m$().languageModel(e)}function m$(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:ME}function fp(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function Xv(e){if(!(e==null||typeof e=="number"))return e.stepMs}function g$(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var y$=[{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]}],v$=e=>{const t=typeof e=="string"?Go(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function _$(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?v$(e):e}function w$({data:e,signatures:t}){const r=_$(e),n=typeof r=="string"?Go(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||n[a]===s))return o.mediaType}var e_="6.0.141",b$=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();xl(o);try{const s=await fetch(o,{headers:qn({},`ai-sdk/${e_}`,la()),signal:r});if(s.redirected&&xl(s.url),!s.ok)throw new rr({url:o,statusCode:s.status,statusText:s.statusText});return{data:await Jg({response:s,url:o,maxBytes:t??Dd}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw rr.isInstance(s)?s:new rr({url:o,cause:s})}},T$=(e=b$)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function k$(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var t_=ae([d(),Ji(Uint8Array),Ji(ArrayBuffer),Dm(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function r_(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:r}=k$(e.toString());if(t==null||r==null)throw new ke({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function S$(e){return typeof e=="string"?e:e instanceof ArrayBuffer?Jo(new Uint8Array(e)):Jo(e)}async function n_({prompt:e,supportedUrls:t,download:r=T$()}){const n=await I$(e.messages,r,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const u of c.content)u.type==="tool-approval-request"&&"approvalId"in u&&"toolCallId"in u&&o.set(u.approvalId,u.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const u of c.content)if(u.type==="tool-approval-response"){const f=o.get(u.approvalId);f&&s.add(f)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:go(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>C$({message:c,downloadedAssets:n}))],i=[];for(const c of a){if(c.role!=="tool"){i.push(c);continue}const u=i.at(-1);u?.role==="tool"?u.content.push(...c.content):i.push(c)}const l=new Set;for(const c of i)switch(c.role){case"assistant":{for(const u of c.content)u.type==="tool-call"&&!u.providerExecuted&&l.add(u.toolCallId);break}case"tool":{for(const u of c.content)u.type==="tool-result"&&l.delete(u.toolCallId);break}case"user":case"system":for(const u of s)l.delete(u);if(l.size>0)throw new Iv({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new Iv({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function C$({message:e,downloadedAssets:t}){const r=e.role;switch(r){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(n=>x$(n,t)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:a}=r_(n.data);return{type:"file",data:s,filename:n.filename,mediaType:a??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:o_(n.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:o_(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:e.providerOptions};default:{const n=r;throw new l$({role:n})}}}async function I$(e,t,r){const n=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const i=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&N5({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),o=await t(n);return Object.fromEntries(o.map((s,a)=>s==null?null:[n[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function x$(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const o=e.type;switch(o){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=r_(n);let i=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=w$({data:l,signatures:y$}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function o_(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}async function ma({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:ao(r)}:o==="json"?{type:"error-json",value:s_(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:s_(r)}}function s_(e){return e===void 0?null:e}function hp({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new tn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new tn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new tn({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new tn({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new tn({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new tn({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new tn({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new tn({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function E$(e){return e!=null&&Object.keys(e).length>0}async function a_({tools:e,toolChoice:t,activeTools:r}){if(!E$(e))return{tools:void 0,toolChoice:void 0};const n=r!=null?Object.entries(e).filter(([s])=>r.includes(s)):Object.entries(e),o=[];for(const[s,a]of n){const i=a.type;switch(i){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await po(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=i;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}var ga=Gi(()=>ae([Ls(),d(),O(),ve(),_e(d(),ga.optional()),q(ga)])),mt=_e(d(),_e(d(),ga.optional())),i_=T({type:P("text"),text:d(),providerOptions:mt.optional()}),$$=T({type:P("image"),image:ae([t_,Ji(URL)]),mediaType:d().optional(),providerOptions:mt.optional()}),l_=T({type:P("file"),data:ae([t_,Ji(URL)]),filename:d().optional(),mediaType:d(),providerOptions:mt.optional()}),R$=T({type:P("reasoning"),text:d(),providerOptions:mt.optional()}),P$=T({type:P("tool-call"),toolCallId:d(),toolName:d(),input:xe(),providerOptions:mt.optional(),providerExecuted:ve().optional()}),M$=Ve("type",[T({type:P("text"),value:d(),providerOptions:mt.optional()}),T({type:P("json"),value:ga,providerOptions:mt.optional()}),T({type:P("execution-denied"),reason:d().optional(),providerOptions:mt.optional()}),T({type:P("error-text"),value:d(),providerOptions:mt.optional()}),T({type:P("error-json"),value:ga,providerOptions:mt.optional()}),T({type:P("content"),value:q(ae([T({type:P("text"),text:d(),providerOptions:mt.optional()}),T({type:P("media"),data:d(),mediaType:d()}),T({type:P("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:mt.optional()}),T({type:P("file-url"),url:d(),providerOptions:mt.optional()}),T({type:P("file-id"),fileId:ae([d(),_e(d(),d())]),providerOptions:mt.optional()}),T({type:P("image-data"),data:d(),mediaType:d(),providerOptions:mt.optional()}),T({type:P("image-url"),url:d(),providerOptions:mt.optional()}),T({type:P("image-file-id"),fileId:ae([d(),_e(d(),d())]),providerOptions:mt.optional()}),T({type:P("custom"),providerOptions:mt.optional()})]))})]),c_=T({type:P("tool-result"),toolCallId:d(),toolName:d(),output:M$,providerOptions:mt.optional()}),N$=T({type:P("tool-approval-request"),approvalId:d(),toolCallId:d()}),O$=T({type:P("tool-approval-response"),approvalId:d(),approved:ve(),reason:d().optional()}),A$=T({role:P("system"),content:d(),providerOptions:mt.optional()}),q$=T({role:P("user"),content:ae([d(),q(ae([i_,$$,l_]))]),providerOptions:mt.optional()}),L$=T({role:P("assistant"),content:ae([d(),q(ae([i_,l_,R$,P$,c_,N$]))]),providerOptions:mt.optional()}),j$=T({role:P("tool"),content:q(ae([c_,O$])),providerOptions:mt.optional()}),D$=ae([A$,q$,L$,j$]);async function u_(e){if(e.prompt==null&&e.messages==null)throw new io({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new io({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!go(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new io({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new io({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new io({prompt:e,message:"messages must not be empty"});const r=await Cr({value:t,schema:q(D$)});if(!r.success)throw new io({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function d_(e){if(!Yd.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new ke({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
571
+ This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;return new sb({message:s,statusCode:r,cause:n,generationId:o})}};function Xy(e){if(!(e instanceof Error))return!1;const t=e.code;return typeof t=="string"?["UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT"].includes(t):!1}async function mr(e,t){var r;return Xt.isInstance(e)?e:Xy(e)?Qy.createTimeoutError({originalMessage:e instanceof Error?e.message:"Unknown error",cause:e}):_t.isInstance(e)?e.cause&&Xy(e.cause)?Qy.createTimeoutError({originalMessage:e.message,cause:e}):await Jy({response:i$(e),statusCode:(r=e.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:e,authMethod:t}):await Jy({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:"Unknown Gateway error",cause:e,authMethod:t})}function i$(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var ev="ai-gateway-auth-method";async function wn(e){const t=await xr({value:e[ev],schema:l$});return t.success?t.value:void 0}var l$=$e(()=>xe(le([P("api-key"),P("oidc")]))),tv=class{constructor(e){this.config=e}async getAvailableModels(){try{const{value:e}=await Ol({url:`${this.config.baseURL}/config`,headers:await Ht(this.config.headers()),successfulResponseHandler:ir(c$),failedResponseHandler:Xr({errorSchema:xt(),errorToMessage:t=>t}),fetch:this.config.fetch});return e}catch(e){throw await mr(e)}}async getCredits(){try{const e=new URL(this.config.baseURL),{value:t}=await Ol({url:`${e.origin}/v1/credits`,headers:await Ht(this.config.headers()),successfulResponseHandler:ir(u$),failedResponseHandler:Xr({errorSchema:xt(),errorToMessage:r=>r}),fetch:this.config.fetch});return t}catch(e){throw await mr(e)}}},c$=$e(()=>xe(k({models:j(k({id:d(),name:d(),description:d().nullish(),pricing:k({input:d(),output:d(),input_cache_read:d().nullish(),input_cache_write:d().nullish()}).transform(({input:e,output:t,input_cache_read:r,input_cache_write:n})=>({input:e,output:t,...r?{cachedInputTokens:r}:{},...n?{cacheCreationInputTokens:n}:{}})).nullish(),specification:k({specificationVersion:P("v3"),provider:d(),modelId:d()}),modelType:ge(["embedding","image","language","video"]).nullish()}))}))),u$=$e(()=>xe(k({balance:d(),total_used:d()}).transform(({balance:e,total_used:t})=>({balance:e,totalUsed:t})))),d$=class{constructor(e){this.config=e}async getSpendReport(e){try{const t=new URL(this.config.baseURL),r=new URLSearchParams;r.set("start_date",e.startDate),r.set("end_date",e.endDate),e.groupBy&&r.set("group_by",e.groupBy),e.datePart&&r.set("date_part",e.datePart),e.userId&&r.set("user_id",e.userId),e.model&&r.set("model",e.model),e.provider&&r.set("provider",e.provider),e.credentialType&&r.set("credential_type",e.credentialType),e.tags&&e.tags.length>0&&r.set("tags",e.tags.join(","));const{value:n}=await Ol({url:`${t.origin}/v1/report?${r.toString()}`,headers:await Ht(this.config.headers()),successfulResponseHandler:ir(p$),failedResponseHandler:Xr({errorSchema:xt(),errorToMessage:o=>o}),fetch:this.config.fetch});return n}catch(t){throw await mr(t)}}},p$=$e(()=>xe(k({results:j(k({day:d().optional(),hour:d().optional(),user:d().optional(),model:d().optional(),tag:d().optional(),provider:d().optional(),credential_type:ge(["byok","system"]).optional(),total_cost:N(),market_cost:N().optional(),input_tokens:N().optional(),output_tokens:N().optional(),cached_input_tokens:N().optional(),cache_creation_input_tokens:N().optional(),reasoning_tokens:N().optional(),request_count:N().optional()}).transform(({credential_type:e,total_cost:t,market_cost:r,input_tokens:n,output_tokens:o,cached_input_tokens:s,cache_creation_input_tokens:a,reasoning_tokens:i,request_count:l,...c})=>({...c,...e!==void 0?{credentialType:e}:{},totalCost:t,...r!==void 0?{marketCost:r}:{},...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...s!==void 0?{cachedInputTokens:s}:{},...a!==void 0?{cacheCreationInputTokens:a}:{},...i!==void 0?{reasoningTokens:i}:{},...l!==void 0?{requestCount:l}:{}})))}))),f$=class{constructor(e){this.config=e}async getGenerationInfo(e){try{const t=new URL(this.config.baseURL),{value:r}=await Ol({url:`${t.origin}/v1/generation?id=${encodeURIComponent(e.id)}`,headers:await Ht(this.config.headers()),successfulResponseHandler:ir(h$),failedResponseHandler:Xr({errorSchema:xt(),errorToMessage:n=>n}),fetch:this.config.fetch});return r}catch(t){throw await mr(t)}}},h$=$e(()=>xe(k({data:k({id:d(),total_cost:N(),upstream_inference_cost:N(),usage:N(),created_at:d(),model:d(),is_byok:Te(),provider_name:d(),streamed:Te(),finish_reason:d(),latency:N(),generation_time:N(),native_tokens_prompt:N(),native_tokens_completion:N(),native_tokens_reasoning:N(),native_tokens_cached:N(),native_tokens_cache_creation:N(),billable_web_search_calls:N()}).transform(({total_cost:e,upstream_inference_cost:t,created_at:r,is_byok:n,provider_name:o,finish_reason:s,generation_time:a,native_tokens_prompt:i,native_tokens_completion:l,native_tokens_reasoning:c,native_tokens_cached:u,native_tokens_cache_creation:f,billable_web_search_calls:p,...h})=>({...h,totalCost:e,upstreamInferenceCost:t,createdAt:r,isByok:n,providerName:o,finishReason:s,generationTime:a,promptTokens:i,completionTokens:l,reasoningTokens:c,cachedTokens:u,cacheCreationTokens:f,billableWebSearchCalls:p}))}).transform(({data:e})=>e))),m$=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){const{abortSignal:t,...r}=e;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Ht(this.config.headers());try{const{responseHeaders:s,value:a,rawValue:i}=await ar({url:this.getUrl(),headers:Vt(o,e.headers,this.getModelConfigHeaders(this.modelId,!1),await Ht(this.config.o11yHeaders)),body:t,successfulResponseHandler:ir(xt()),failedResponseHandler:Xr({errorSchema:xt(),errorToMessage:l=>l}),...n&&{abortSignal:n},fetch:this.config.fetch});return{...a,request:{body:t},response:{headers:s,body:i},warnings:r}}catch(s){throw await mr(s,await wn(o))}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),{abortSignal:n}=e,o=await Ht(this.config.headers());try{const{value:s,responseHeaders:a}=await ar({url:this.getUrl(),headers:Vt(o,e.headers,this.getModelConfigHeaders(this.modelId,!0),await Ht(this.config.o11yHeaders)),body:t,successfulResponseHandler:Nl(xt()),failedResponseHandler:Xr({errorSchema:xt(),errorToMessage:i=>i}),...n&&{abortSignal:n},fetch:this.config.fetch});return{stream:s.pipeThrough(new TransformStream({start(i){r.length>0&&i.enqueue({type:"stream-start",warnings:r})},transform(i,l){if(i.success){const c=i.value;if(c.type==="raw"&&!e.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:t},response:{headers:a}}}catch(s){throw await mr(s,await wn(o))}}isFilePart(e){return e&&typeof e=="object"&&"type"in e&&e.type==="file"}maybeEncodeFileParts(e){for(const t of e.prompt)for(const r of t.content)if(this.isFilePart(r)){const n=r;if(n.data instanceof Uint8Array){const o=Uint8Array.from(n.data),s=Buffer.from(o).toString("base64");n.data=new URL(`data:${n.mediaType||"application/octet-stream"};base64,${s}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":"3","ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},g$=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;const s=await Ht(this.config.headers());try{const{responseHeaders:a,value:i,rawValue:l}=await ar({url:this.getUrl(),headers:Vt(s,t??{},this.getModelConfigHeaders(),await Ht(this.config.o11yHeaders)),body:{values:e,...n?{providerOptions:n}:{}},successfulResponseHandler:ir(y$),failedResponseHandler:Xr({errorSchema:xt(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(o=i.usage)!=null?o:void 0,providerMetadata:i.providerMetadata,response:{headers:a,body:l},warnings:[]}}catch(a){throw await mr(a,await wn(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"3","ai-model-id":this.modelId}}},y$=$e(()=>xe(k({embeddings:j(j(N())),usage:k({tokens:N()}).nullish(),providerMetadata:Se(d(),Se(d(),Ne())).optional()}))),v$=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxImagesPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:r,aspectRatio:n,seed:o,files:s,mask:a,providerOptions:i,headers:l,abortSignal:c}){var u,f,p,h;const m=await Ht(this.config.headers());try{const{responseHeaders:_,value:g,rawValue:w}=await ar({url:this.getUrl(),headers:Vt(m,l??{},this.getModelConfigHeaders(),await Ht(this.config.o11yHeaders)),body:{prompt:e,n:t,...r&&{size:r},...n&&{aspectRatio:n},...o&&{seed:o},...i&&{providerOptions:i},...s&&{files:s.map(v=>rv(v))},...a&&{mask:rv(a)}},successfulResponseHandler:ir(k$),failedResponseHandler:Xr({errorSchema:xt(),errorToMessage:v=>v}),...c&&{abortSignal:c},fetch:this.config.fetch});return{images:g.images,warnings:(u=g.warnings)!=null?u:[],providerMetadata:g.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:_},...g.usage!=null&&{usage:{inputTokens:(f=g.usage.inputTokens)!=null?f:void 0,outputTokens:(p=g.usage.outputTokens)!=null?p:void 0,totalTokens:(h=g.usage.totalTokens)!=null?h:void 0}}}}catch(_){throw await mr(_,await wn(m))}}getUrl(){return`${this.config.baseURL}/image-model`}getModelConfigHeaders(){return{"ai-image-model-specification-version":"3","ai-model-id":this.modelId}}};function rv(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:ns(e.data)}:e}var _$=k({images:j(Ne()).optional()}).catchall(Ne()),w$=Qe("type",[k({type:P("unsupported"),feature:d(),details:d().optional()}),k({type:P("compatibility"),feature:d(),details:d().optional()}),k({type:P("other"),message:d()})]),b$=k({inputTokens:N().nullish(),outputTokens:N().nullish(),totalTokens:N().nullish()}),k$=k({images:j(d()),warnings:j(w$).optional(),providerMetadata:Se(d(),_$).optional(),usage:b$.optional()}),T$=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3",this.maxVideosPerCall=Number.MAX_SAFE_INTEGER}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,aspectRatio:r,resolution:n,duration:o,fps:s,seed:a,image:i,providerOptions:l,headers:c,abortSignal:u}){var f;const p=await Ht(this.config.headers());try{const{responseHeaders:h,value:m}=await ar({url:this.getUrl(),headers:Vt(p,c??{},this.getModelConfigHeaders(),await Ht(this.config.o11yHeaders),{accept:"text/event-stream"}),body:{prompt:e,n:t,...r&&{aspectRatio:r},...n&&{resolution:n},...o&&{duration:o},...s&&{fps:s},...a&&{seed:a},...l&&{providerOptions:l},...i&&{image:S$(i)}},successfulResponseHandler:async({response:_,url:g,requestBodyValues:w})=>{if(_.body==null)throw new _t({message:"SSE response body is empty",url:g,requestBodyValues:w,statusCode:_.status});const y=fy({stream:_.body,schema:$$}).getReader(),{done:S,value:b}=await y.read();if(y.releaseLock(),S||!b)throw new _t({message:"SSE stream ended without a data event",url:g,requestBodyValues:w,statusCode:_.status});if(!b.success)throw new _t({message:"Failed to parse video SSE event",cause:b.error,url:g,requestBodyValues:w,statusCode:_.status});const T=b.value;if(T.type==="error")throw new _t({message:T.message,statusCode:T.statusCode,url:g,requestBodyValues:w,responseHeaders:Object.fromEntries([..._.headers]),responseBody:JSON.stringify(T),data:{error:{message:T.message,type:T.errorType,param:T.param}}});return{value:{videos:T.videos,warnings:T.warnings,providerMetadata:T.providerMetadata},responseHeaders:Object.fromEntries([..._.headers])}},failedResponseHandler:Xr({errorSchema:xt(),errorToMessage:_=>_}),...u&&{abortSignal:u},fetch:this.config.fetch});return{videos:m.videos,warnings:(f=m.warnings)!=null?f:[],providerMetadata:m.providerMetadata,response:{timestamp:new Date,modelId:this.modelId,headers:h}}}catch(h){throw await mr(h,await wn(p))}}getUrl(){return`${this.config.baseURL}/video-model`}getModelConfigHeaders(){return{"ai-video-model-specification-version":"3","ai-model-id":this.modelId}}};function S$(e){return e.type==="file"&&e.data instanceof Uint8Array?{...e,data:ns(e.data)}:e}var C$=k({videos:j(Ne()).optional()}).catchall(Ne()),x$=le([k({type:P("url"),url:d(),mediaType:d()}),k({type:P("base64"),data:d(),mediaType:d()})]),I$=Qe("type",[k({type:P("unsupported"),feature:d(),details:d().optional()}),k({type:P("compatibility"),feature:d(),details:d().optional()}),k({type:P("other"),message:d()})]),$$=Qe("type",[k({type:P("result"),videos:j(x$),warnings:j(I$).optional(),providerMetadata:Se(d(),C$).optional()}),k({type:P("error"),message:d(),errorType:d(),statusCode:N(),param:Ne().nullable()})]),E$=$e(()=>xe(tr({objective:Ye().describe("Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."),search_queries:fn(Ye()).optional().describe("Optional search queries to supplement the objective. Maximum 200 characters per query."),mode:Os(["one-shot","agentic"]).optional().describe('Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'),max_results:kr().optional().describe("Maximum number of results to return (1-20). Defaults to 10 if not specified."),source_policy:tr({include_domains:fn(Ye()).optional().describe("List of domains to include in search results."),exclude_domains:fn(Ye()).optional().describe("List of domains to exclude from search results."),after_date:Ye().optional().describe("Only include results published after this date (ISO 8601 format).")}).optional().describe("Source policy for controlling which domains to include/exclude and freshness."),excerpts:tr({max_chars_per_result:kr().optional().describe("Maximum characters per result."),max_chars_total:kr().optional().describe("Maximum total characters across all results.")}).optional().describe("Excerpt configuration for controlling result length."),fetch_policy:tr({max_age_seconds:kr().optional().describe("Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.")}).optional().describe("Fetch policy for controlling content freshness.")}))),R$=$e(()=>xe(Fi([tr({searchId:Ye(),results:fn(tr({url:Ye(),title:Ye(),excerpt:Ye(),publishDate:Ye().nullable().optional(),relevanceScore:kr().optional()}))}),tr({error:Os(["api_error","rate_limit","timeout","invalid_input","configuration_error","unknown"]),statusCode:kr().optional(),message:Ye()})]))),P$=$r({id:"gateway.parallel_search",inputSchema:E$,outputSchema:R$}),M$=(e={})=>P$(e),O$=$e(()=>xe(tr({query:Fi([Ye(),fn(Ye())]).describe("Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."),max_results:kr().optional().describe("Maximum number of search results to return (1-20, default: 10)"),max_tokens_per_page:kr().optional().describe("Maximum number of tokens to extract per search result page (256-2048, default: 2048)"),max_tokens:kr().optional().describe("Maximum total tokens across all search results (default: 25000, max: 1000000)"),country:Ye().optional().describe("Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"),search_domain_filter:fn(Ye()).optional().describe("List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"),search_language_filter:fn(Ye()).optional().describe("List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"),search_after_date:Ye().optional().describe("Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),search_before_date:Ye().optional().describe("Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),last_updated_after_filter:Ye().optional().describe("Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."),last_updated_before_filter:Ye().optional().describe("Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."),search_recency_filter:Os(["day","week","month","year"]).optional().describe("Filter results by relative time period. Cannot be used with search_after_date or search_before_date.")}))),N$=$e(()=>xe(Fi([tr({results:fn(tr({title:Ye(),url:Ye(),snippet:Ye(),date:Ye().optional(),lastUpdated:Ye().optional()})),id:Ye()}),tr({error:Os(["api_error","rate_limit","timeout","invalid_input","unknown"]),statusCode:kr().optional(),message:Ye()})]))),A$=$r({id:"gateway.perplexity_search",inputSchema:O$,outputSchema:N$}),q$=(e={})=>A$(e),j$={parallelSearch:M$,perplexitySearch:q$};async function L$(){var e;return(e=_y.getContext().headers)==null?void 0:e["x-vercel-id"]}var D$="3.0.87",U$="0.0.1";function z$(e={}){var t,r;let n=null,o=null;const s=(t=e.metadataCacheRefreshMillis)!=null?t:1e3*60*5;let a=0;const i=(r=gy(e.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v3/ai",l=async()=>{try{const w=await F$(e);return Dn({Authorization:`Bearer ${w.token}`,"ai-gateway-protocol-version":U$,[ev]:w.authMethod,...e.headers},`ai-sdk/gateway/${D$}`)}catch(w){throw rp.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401,cause:w})}},c=()=>{const w=ss({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=ss({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),y=ss({settingValue:void 0,environmentVariableName:"VERCEL_REGION"}),S=ss({settingValue:void 0,environmentVariableName:"VERCEL_PROJECT_ID"});return async()=>{const b=await L$();return{...w&&{"ai-o11y-deployment-id":w},...v&&{"ai-o11y-environment":v},...y&&{"ai-o11y-region":y},...b&&{"ai-o11y-request-id":b},...S&&{"ai-o11y-project-id":S}}}},u=w=>new m$(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),f=async()=>{var w,v,y;const S=(y=(v=(w=e._internal)==null?void 0:w.currentDate)==null?void 0:v.call(w).getTime())!=null?y:Date.now();return(!n||S-a>s)&&(a=S,n=new tv({baseURL:i,headers:l,fetch:e.fetch}).getAvailableModels().then(b=>(o=b,b)).catch(async b=>{throw await mr(b,await wn(await l()))})),o?Promise.resolve(o):n},p=async()=>new tv({baseURL:i,headers:l,fetch:e.fetch}).getCredits().catch(async w=>{throw await mr(w,await wn(await l()))}),h=async w=>new d$({baseURL:i,headers:l,fetch:e.fetch}).getSpendReport(w).catch(async v=>{throw await mr(v,await wn(await l()))}),m=async w=>new f$({baseURL:i,headers:l,fetch:e.fetch}).getGenerationInfo(w).catch(async v=>{throw await mr(v,await wn(await l()))}),_=function(w){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(w)};_.specificationVersion="v3",_.getAvailableModels=f,_.getCredits=p,_.getSpendReport=h,_.getGenerationInfo=m,_.imageModel=w=>new v$(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),_.languageModel=u;const g=w=>new g$(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()});return _.embeddingModel=g,_.textEmbeddingModel=g,_.videoModel=w=>new T$(w,{provider:"gateway",baseURL:i,headers:l,fetch:e.fetch,o11yHeaders:c()}),_.chat=_.languageModel,_.embedding=_.embeddingModel,_.image=_.imageModel,_.video=_.videoModel,_.tools=j$,_}var Z$=z$();async function F$(e){const t=ss({settingValue:e.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});return t?{token:t,authMethod:"api-key"}:{token:await _y.getVercelOidcToken(),authMethod:"oidc"}}var V$=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},vo="1.9.0",nv=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function H$(e){var t=new Set([e]),r=new Set,n=e.match(nv);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===e};function s(i){return r.add(i),!1}function a(i){return t.add(i),!0}return function(l){if(t.has(l))return!0;if(r.has(l))return!1;var c=l.match(nv);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||o.major!==u.major?s(l):o.major===0?o.minor===u.minor&&o.patch<=u.patch?a(l):s(l):o.minor<=u.minor?a(l):s(l)}}var B$=H$(vo),J$=vo.split(".")[0],ha=Symbol.for("opentelemetry.js.api."+J$),ma=V$;function ga(e,t,r,n){var o;n===void 0&&(n=!1);var s=ma[ha]=(o=ma[ha])!==null&&o!==void 0?o:{version:vo};if(!n&&s[e]){var a=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+e);return r.error(a.stack||a.message),!1}if(s.version!==vo){var a=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+e+" does not match previously registered API v"+vo);return r.error(a.stack||a.message),!1}return s[e]=t,r.debug("@opentelemetry/api: Registered a global for "+e+" v"+vo+"."),!0}function _o(e){var t,r,n=(t=ma[ha])===null||t===void 0?void 0:t.version;if(!(!n||!B$(n)))return(r=ma[ha])===null||r===void 0?void 0:r[e]}function ya(e,t){t.debug("@opentelemetry/api: Unregistering a global for "+e+" v"+vo+".");var r=ma[ha];r&&delete r[e]}var W$=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},G$=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},K$=(function(){function e(t){this._namespace=t.namespace||"DiagComponentLogger"}return e.prototype.debug=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return va("debug",this._namespace,t)},e.prototype.error=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return va("error",this._namespace,t)},e.prototype.info=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return va("info",this._namespace,t)},e.prototype.warn=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return va("warn",this._namespace,t)},e.prototype.verbose=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return va("verbose",this._namespace,t)},e})();function va(e,t,r){var n=_o("diag");if(n)return r.unshift(t),n[e].apply(n,G$([],W$(r),!1))}var gr;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(gr||(gr={}));function Y$(e,t){e<gr.NONE?e=gr.NONE:e>gr.ALL&&(e=gr.ALL),t=t||{};function r(n,o){var s=t[n];return typeof s=="function"&&e>=o?s.bind(t):function(){}}return{error:r("error",gr.ERROR),warn:r("warn",gr.WARN),info:r("info",gr.INFO),debug:r("debug",gr.DEBUG),verbose:r("verbose",gr.VERBOSE)}}var Q$=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},X$=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},eE="diag",en=(function(){function e(){function t(o){return function(){for(var s=[],a=0;a<arguments.length;a++)s[a]=arguments[a];var i=_o("diag");if(i)return i[o].apply(i,X$([],Q$(s),!1))}}var r=this,n=function(o,s){var a,i,l;if(s===void 0&&(s={logLevel:gr.INFO}),o===r){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((a=c.stack)!==null&&a!==void 0?a:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=_o("diag"),f=Y$((i=s.logLevel)!==null&&i!==void 0?i:gr.INFO,o);if(u&&!s.suppressOverrideMessage){var p=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),f.warn("Current logger will overwrite one already registered from "+p)}return ga("diag",f,r,!0)};r.setLogger=n,r.disable=function(){ya(eE,r)},r.createComponentLogger=function(o){return new K$(o)},r.verbose=t("verbose"),r.debug=t("debug"),r.info=t("info"),r.warn=t("warn"),r.error=t("error")}return e.instance=function(){return this._instance||(this._instance=new e),this._instance},e})(),tE=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},rE=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},nE=(function(){function e(t){this._entries=t?new Map(t):new Map}return e.prototype.getEntry=function(t){var r=this._entries.get(t);if(r)return Object.assign({},r)},e.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(t){var r=tE(t,2),n=r[0],o=r[1];return[n,o]})},e.prototype.setEntry=function(t,r){var n=new e(this._entries);return n._entries.set(t,r),n},e.prototype.removeEntry=function(t){var r=new e(this._entries);return r._entries.delete(t),r},e.prototype.removeEntries=function(){for(var t,r,n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var s=new e(this._entries);try{for(var a=rE(n),i=a.next();!i.done;i=a.next()){var l=i.value;s._entries.delete(l)}}catch(c){t={error:c}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return s},e.prototype.clear=function(){return new e},e})();en.instance();function oE(e){return e===void 0&&(e={}),new nE(new Map(Object.entries(e)))}function ov(e){return Symbol.for(e)}var sE=(function(){function e(t){var r=this;r._currentContext=t?new Map(t):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,o){var s=new e(r._currentContext);return s._currentContext.set(n,o),s},r.deleteValue=function(n){var o=new e(r._currentContext);return o._currentContext.delete(n),o}}return e})(),aE=new sE,wo=(function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,o){n.__proto__=o}||function(n,o){for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[s]=o[s])},e(t,r)};return function(t,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");e(t,r);function n(){this.constructor=t}t.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}})(),iE=(function(){function e(){}return e.prototype.createGauge=function(t,r){return yE},e.prototype.createHistogram=function(t,r){return vE},e.prototype.createCounter=function(t,r){return gE},e.prototype.createUpDownCounter=function(t,r){return _E},e.prototype.createObservableGauge=function(t,r){return bE},e.prototype.createObservableCounter=function(t,r){return wE},e.prototype.createObservableUpDownCounter=function(t,r){return kE},e.prototype.addBatchObservableCallback=function(t,r){},e.prototype.removeBatchObservableCallback=function(t){},e})(),Al=(function(){function e(){}return e})(),lE=(function(e){wo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Al),cE=(function(e){wo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.add=function(r,n){},t})(Al),uE=(function(e){wo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Al),dE=(function(e){wo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.record=function(r,n){},t})(Al),np=(function(){function e(){}return e.prototype.addCallback=function(t){},e.prototype.removeCallback=function(t){},e})(),pE=(function(e){wo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(np),fE=(function(e){wo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(np),hE=(function(e){wo(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(np),mE=new iE,gE=new lE,yE=new uE,vE=new dE,_E=new cE,wE=new pE,bE=new fE,kE=new hE,TE={get:function(e,t){if(e!=null)return e[t]},keys:function(e){return e==null?[]:Object.keys(e)}},SE={set:function(e,t,r){e!=null&&(e[t]=r)}},CE=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},xE=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},IE=(function(){function e(){}return e.prototype.active=function(){return aE},e.prototype.with=function(t,r,n){for(var o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return r.call.apply(r,xE([n],CE(o),!1))},e.prototype.bind=function(t,r){return r},e.prototype.enable=function(){return this},e.prototype.disable=function(){return this},e})(),$E=function(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,s=[],a;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)s.push(o.value)}catch(i){a={error:i}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(a)throw a.error}}return s},EE=function(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))},op="context",RE=new IE,ql=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalContextManager=function(t){return ga(op,t,en.instance())},e.prototype.active=function(){return this._getContextManager().active()},e.prototype.with=function(t,r,n){for(var o,s=[],a=3;a<arguments.length;a++)s[a-3]=arguments[a];return(o=this._getContextManager()).with.apply(o,EE([t,r,n],$E(s),!1))},e.prototype.bind=function(t,r){return this._getContextManager().bind(t,r)},e.prototype._getContextManager=function(){return _o(op)||RE},e.prototype.disable=function(){this._getContextManager().disable(),ya(op,en.instance())},e})(),sp;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(sp||(sp={}));var sv="0000000000000000",av="00000000000000000000000000000000",PE={traceId:av,spanId:sv,traceFlags:sp.NONE},_a=(function(){function e(t){t===void 0&&(t=PE),this._spanContext=t}return e.prototype.spanContext=function(){return this._spanContext},e.prototype.setAttribute=function(t,r){return this},e.prototype.setAttributes=function(t){return this},e.prototype.addEvent=function(t,r){return this},e.prototype.addLink=function(t){return this},e.prototype.addLinks=function(t){return this},e.prototype.setStatus=function(t){return this},e.prototype.updateName=function(t){return this},e.prototype.end=function(t){},e.prototype.isRecording=function(){return!1},e.prototype.recordException=function(t,r){},e})(),ap=ov("OpenTelemetry Context Key SPAN");function ip(e){return e.getValue(ap)||void 0}function ME(){return ip(ql.getInstance().active())}function lp(e,t){return e.setValue(ap,t)}function OE(e){return e.deleteValue(ap)}function NE(e,t){return lp(e,new _a(t))}function iv(e){var t;return(t=ip(e))===null||t===void 0?void 0:t.spanContext()}var AE=/^([0-9a-f]{32})$/i,qE=/^[0-9a-f]{16}$/i;function jE(e){return AE.test(e)&&e!==av}function LE(e){return qE.test(e)&&e!==sv}function lv(e){return jE(e.traceId)&&LE(e.spanId)}function DE(e){return new _a(e)}var cp=ql.getInstance(),cv=(function(){function e(){}return e.prototype.startSpan=function(t,r,n){n===void 0&&(n=cp.active());var o=!!r?.root;if(o)return new _a;var s=n&&iv(n);return UE(s)&&lv(s)?new _a(s):new _a},e.prototype.startActiveSpan=function(t,r,n,o){var s,a,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=n):(s=r,a=n,i=o);var l=a??cp.active(),c=this.startSpan(t,s,l),u=lp(l,c);return cp.with(u,i,void 0,c)}},e})();function UE(e){return typeof e=="object"&&typeof e.spanId=="string"&&typeof e.traceId=="string"&&typeof e.traceFlags=="number"}var zE=new cv,ZE=(function(){function e(t,r,n,o){this._provider=t,this.name=r,this.version=n,this.options=o}return e.prototype.startSpan=function(t,r,n){return this._getTracer().startSpan(t,r,n)},e.prototype.startActiveSpan=function(t,r,n,o){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},e.prototype._getTracer=function(){if(this._delegate)return this._delegate;var t=this._provider.getDelegateTracer(this.name,this.version,this.options);return t?(this._delegate=t,this._delegate):zE},e})(),FE=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){return new cv},e})(),VE=new FE,uv=(function(){function e(){}return e.prototype.getTracer=function(t,r,n){var o;return(o=this.getDelegateTracer(t,r,n))!==null&&o!==void 0?o:new ZE(this,t,r,n)},e.prototype.getDelegate=function(){var t;return(t=this._delegate)!==null&&t!==void 0?t:VE},e.prototype.setDelegate=function(t){this._delegate=t},e.prototype.getDelegateTracer=function(t,r,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(t,r,n)},e})(),jl;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(jl||(jl={}));var dv=ql.getInstance();en.instance();var HE=(function(){function e(){}return e.prototype.getMeter=function(t,r,n){return mE},e})(),BE=new HE,up="metrics",JE=(function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(t){return ga(up,t,en.instance())},e.prototype.getMeterProvider=function(){return _o(up)||BE},e.prototype.getMeter=function(t,r,n){return this.getMeterProvider().getMeter(t,r,n)},e.prototype.disable=function(){ya(up,en.instance())},e})();JE.getInstance();var WE=(function(){function e(){}return e.prototype.inject=function(t,r){},e.prototype.extract=function(t,r){return t},e.prototype.fields=function(){return[]},e})(),dp=ov("OpenTelemetry Baggage Key");function pv(e){return e.getValue(dp)||void 0}function GE(){return pv(ql.getInstance().active())}function KE(e,t){return e.setValue(dp,t)}function YE(e){return e.deleteValue(dp)}var pp="propagation",QE=new WE,XE=(function(){function e(){this.createBaggage=oE,this.getBaggage=pv,this.getActiveBaggage=GE,this.setBaggage=KE,this.deleteBaggage=YE}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalPropagator=function(t){return ga(pp,t,en.instance())},e.prototype.inject=function(t,r,n){return n===void 0&&(n=SE),this._getGlobalPropagator().inject(t,r,n)},e.prototype.extract=function(t,r,n){return n===void 0&&(n=TE),this._getGlobalPropagator().extract(t,r,n)},e.prototype.fields=function(){return this._getGlobalPropagator().fields()},e.prototype.disable=function(){ya(pp,en.instance())},e.prototype._getGlobalPropagator=function(){return _o(pp)||QE},e})();XE.getInstance();var fp="trace",e8=(function(){function e(){this._proxyTracerProvider=new uv,this.wrapSpanContext=DE,this.isSpanContextValid=lv,this.deleteSpan=OE,this.getSpan=ip,this.getActiveSpan=ME,this.getSpanContext=iv,this.setSpan=lp,this.setSpanContext=NE}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalTracerProvider=function(t){var r=ga(fp,this._proxyTracerProvider,en.instance());return r&&this._proxyTracerProvider.setDelegate(t),r},e.prototype.getTracerProvider=function(){return _o(fp)||this._proxyTracerProvider},e.prototype.getTracer=function(t,r){return this.getTracerProvider().getTracer(t,r)},e.prototype.disable=function(){ya(fp,en.instance()),this._proxyTracerProvider=new uv},e})(),t8=e8.getInstance(),r8=Object.defineProperty,n8=(e,t)=>{for(var r in t)r8(e,r,{get:t[r],enumerable:!0})},fv="AI_InvalidArgumentError",hv=`vercel.ai.error.${fv}`,o8=Symbol.for(hv),mv,tn=class extends Re{constructor({parameter:t,value:r,message:n}){super({name:fv,message:`Invalid argument for parameter ${t}: ${n}`}),this[mv]=!0,this.parameter=t,this.value=r}static isInstance(t){return Re.hasMarker(t,hv)}};mv=o8;var gv="AI_InvalidToolApprovalError",yv=`vercel.ai.error.${gv}`,s8=Symbol.for(yv),vv,a8=class extends Re{constructor({approvalId:e}){super({name:gv,message:`Tool approval response references unknown approvalId: "${e}". No matching tool-approval-request found in message history.`}),this[vv]=!0,this.approvalId=e}static isInstance(e){return Re.hasMarker(e,yv)}};vv=s8;var _v="AI_InvalidToolInputError",wv=`vercel.ai.error.${_v}`,i8=Symbol.for(wv),bv,hp=class extends Re{constructor({toolInput:e,toolName:t,cause:r,message:n=`Invalid input for tool ${t}: ${uo(r)}`}){super({name:_v,message:n,cause:r}),this[bv]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return Re.hasMarker(e,wv)}};bv=i8;var kv="AI_ToolCallNotFoundForApprovalError",Tv=`vercel.ai.error.${kv}`,l8=Symbol.for(Tv),Sv,mp=class extends Re{constructor({toolCallId:e,approvalId:t}){super({name:kv,message:`Tool call "${e}" not found for approval request "${t}".`}),this[Sv]=!0,this.toolCallId=e,this.approvalId=t}static isInstance(e){return Re.hasMarker(e,Tv)}};Sv=l8;var Cv="AI_MissingToolResultsError",xv=`vercel.ai.error.${Cv}`,c8=Symbol.for(xv),Iv,$v=class extends Re{constructor({toolCallIds:e}){super({name:Cv,message:`Tool result${e.length>1?"s are":" is"} missing for tool call${e.length>1?"s":""} ${e.join(", ")}.`}),this[Iv]=!0,this.toolCallIds=e}static isInstance(e){return Re.hasMarker(e,xv)}};Iv=c8;var Ev="AI_NoObjectGeneratedError",Rv=`vercel.ai.error.${Ev}`,u8=Symbol.for(Rv),Pv,Un=class extends Re{constructor({message:e="No object generated.",cause:t,text:r,response:n,usage:o,finishReason:s}){super({name:Ev,message:e,cause:t}),this[Pv]=!0,this.text=r,this.response=n,this.usage=o,this.finishReason=s}static isInstance(e){return Re.hasMarker(e,Rv)}};Pv=u8;var Mv="AI_NoOutputGeneratedError",Ov=`vercel.ai.error.${Mv}`,d8=Symbol.for(Ov),Nv,Av=class extends Re{constructor({message:e="No output generated.",cause:t}={}){super({name:Mv,message:e,cause:t}),this[Nv]=!0}static isInstance(e){return Re.hasMarker(e,Ov)}};Nv=d8;var qv="AI_NoSuchToolError",jv=`vercel.ai.error.${qv}`,p8=Symbol.for(jv),Lv,gp=class extends Re{constructor({toolName:e,availableTools:t=void 0,message:r=`Model tried to call unavailable tool '${e}'. ${t===void 0?"No tools are available.":`Available tools: ${t.join(", ")}.`}`}){super({name:qv,message:r}),this[Lv]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return Re.hasMarker(e,jv)}};Lv=p8;var Dv="AI_ToolCallRepairError",Uv=`vercel.ai.error.${Dv}`,f8=Symbol.for(Uv),zv,h8=class extends Re{constructor({cause:e,originalError:t,message:r=`Error repairing tool call: ${uo(e)}`}){super({name:Dv,message:r,cause:e}),this[zv]=!0,this.originalError=t}static isInstance(e){return Re.hasMarker(e,Uv)}};zv=f8;var m8=class extends Re{constructor(e){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},Zv="AI_UIMessageStreamError",Fv=`vercel.ai.error.${Zv}`,g8=Symbol.for(Fv),Vv,as=class extends Re{constructor({chunkType:e,chunkId:t,message:r}){super({name:Zv,message:r}),this[Vv]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return Re.hasMarker(e,Fv)}};Vv=g8;var Hv="AI_InvalidMessageRoleError",Bv=`vercel.ai.error.${Hv}`,y8=Symbol.for(Bv),Jv,v8=class extends Re{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Hv,message:t}),this[Jv]=!0,this.role=e}static isInstance(e){return Re.hasMarker(e,Bv)}};Jv=y8;var Wv="AI_RetryError",Gv=`vercel.ai.error.${Wv}`,_8=Symbol.for(Gv),Kv,Yv=class extends Re{constructor({message:e,reason:t,errors:r}){super({name:Wv,message:e}),this[Kv]=!0,this.reason=t,this.errors=r,this.lastError=r[r.length-1]}static isInstance(e){return Re.hasMarker(e,Gv)}};Kv=_8;function bo(e){return e===void 0?[]:Array.isArray(e)?e:[e]}async function Fr(e){for(const t of bo(e.callbacks))if(t!=null)try{await t(e.event)}catch{}}function w8({warning:e,provider:t,model:r}){const n=`AI SDK Warning (${t} / ${r}):`;switch(e.type){case"unsupported":{let o=`${n} The feature "${e.feature}" is not supported.`;return e.details&&(o+=` ${e.details}`),o}case"compatibility":{let o=`${n} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(o+=` ${e.details}`),o}case"other":return`${n} ${e.message}`;default:return`${n} ${JSON.stringify(e,null,2)}`}}var b8="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",Qv=!1,yp=e=>{if(e.warnings.length===0)return;const t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t=="function"){t(e);return}Qv||(Qv=!0,console.info(b8));for(const r of e.warnings)console.warn(w8({warning:r,provider:e.provider,model:e.model}))}};function k8({provider:e,modelId:t}){yp({warnings:[{type:"compatibility",feature:"specificationVersion",details:"Using v2 specification compatibility mode. Some features may not be available."}],provider:e,model:t})}function T8(e){return e.specificationVersion==="v3"?e:(k8({provider:e.provider,modelId:e.modelId}),new Proxy(e,{get(t,r){switch(r){case"specificationVersion":return"v3";case"doGenerate":return async(...n)=>{const o=await t.doGenerate(...n);return{...o,finishReason:Xv(o.finishReason),usage:e_(o.usage)}};case"doStream":return async(...n)=>{const o=await t.doStream(...n);return{...o,stream:S8(o.stream)}};default:return t[r]}}}))}function S8(e){return e.pipeThrough(new TransformStream({transform(t,r){switch(t.type){case"finish":r.enqueue({...t,finishReason:Xv(t.finishReason),usage:e_(t.usage)});break;default:r.enqueue(t);break}}}))}function Xv(e){return{unified:e==="unknown"?"other":e,raw:void 0}}function e_(e){return{inputTokens:{total:e.inputTokens,noCache:void 0,cacheRead:e.cachedInputTokens,cacheWrite:void 0},outputTokens:{total:e.outputTokens,text:void 0,reasoning:e.reasoningTokens}}}function Ll(e){if(typeof e!="string"){if(e.specificationVersion!=="v3"&&e.specificationVersion!=="v2"){const t=e;throw new m8({version:t.specificationVersion,provider:t.provider,modelId:t.modelId})}return T8(e)}return C8().languageModel(e)}function C8(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?e:Z$}function vp(e){if(e!=null)return typeof e=="number"?e:e.totalMs}function t_(e){if(!(e==null||typeof e=="number"))return e.stepMs}function x8(e){if(!(e==null||typeof e=="number"))return e.chunkMs}var I8=[{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]}],$8=e=>{const t=typeof e=="string"?rs(e):e,r=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(r+10)};function E8(e){return typeof e=="string"&&e.startsWith("SUQz")||typeof e!="string"&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51?$8(e):e}function R8({data:e,signatures:t}){const r=E8(e),n=typeof r=="string"?rs(r.substring(0,Math.min(r.length,24))):r;for(const o of t)if(n.length>=o.bytesPrefix.length&&o.bytesPrefix.every((s,a)=>s===null||n[a]===s))return o.mediaType}var r_="6.0.145",P8=async({url:e,maxBytes:t,abortSignal:r})=>{var n;const o=e.toString();Ml(o);try{const s=await fetch(o,{headers:Dn({},`ai-sdk/${r_}`,fa()),signal:r});if(s.redirected&&Ml(s.url),!s.ok)throw new sr({url:o,statusCode:s.status,statusText:s.statusText});return{data:await Qg({response:s,url:o,maxBytes:t??Fd}),mediaType:(n=s.headers.get("content-type"))!=null?n:void 0}}catch(s){throw sr.isInstance(s)?s:new sr({url:o,cause:s})}},M8=(e=P8)=>t=>Promise.all(t.map(async r=>r.isUrlSupportedByModel?null:e(r)));function O8(e){try{const[t,r]=e.split(",");return{mediaType:t.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var n_=le([d(),el(Uint8Array),el(ArrayBuffer),Zm(e=>{var t,r;return(r=(t=globalThis.Buffer)==null?void 0:t.isBuffer(e))!=null?r:!1},{message:"Must be a Buffer"})]);function o_(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e=="string")try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol==="data:"){const{mediaType:t,base64Content:r}=O8(e.toString());if(t==null||r==null)throw new Re({name:"InvalidDataContentError",message:`Invalid data URL format in content ${e.toString()}`});return{data:r,mediaType:t}}return{data:e,mediaType:void 0}}function N8(e){return typeof e=="string"?e:e instanceof ArrayBuffer?ns(new Uint8Array(e)):ns(e)}async function s_({prompt:e,supportedUrls:t,download:r=M8()}){const n=await q8(e.messages,r,t),o=new Map;for(const c of e.messages)if(c.role==="assistant"&&Array.isArray(c.content))for(const u of c.content)u.type==="tool-approval-request"&&"approvalId"in u&&"toolCallId"in u&&o.set(u.approvalId,u.toolCallId);const s=new Set;for(const c of e.messages)if(c.role==="tool"){for(const u of c.content)if(u.type==="tool-approval-response"){const f=o.get(u.approvalId);f&&s.add(f)}}const a=[...e.system!=null?typeof e.system=="string"?[{role:"system",content:e.system}]:bo(e.system).map(c=>({role:"system",content:c.content,providerOptions:c.providerOptions})):[],...e.messages.map(c=>A8({message:c,downloadedAssets:n}))],i=[];for(const c of a){if(c.role!=="tool"){i.push(c);continue}const u=i.at(-1);u?.role==="tool"?u.content.push(...c.content):i.push(c)}const l=new Set;for(const c of i)switch(c.role){case"assistant":{for(const u of c.content)u.type==="tool-call"&&!u.providerExecuted&&l.add(u.toolCallId);break}case"tool":{for(const u of c.content)u.type==="tool-result"&&l.delete(u.toolCallId);break}case"user":case"system":for(const u of s)l.delete(u);if(l.size>0)throw new $v({toolCallIds:Array.from(l)});break}for(const c of s)l.delete(c);if(l.size>0)throw new $v({toolCallIds:Array.from(l)});return i.filter(c=>c.role!=="tool"||c.content.length>0)}function A8({message:e,downloadedAssets:t}){const r=e.role;switch(r){case"system":return{role:"system",content:e.content,providerOptions:e.providerOptions};case"user":return typeof e.content=="string"?{role:"user",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"user",content:e.content.map(n=>j8(n,t)).filter(n=>n.type!=="text"||n.text!==""),providerOptions:e.providerOptions};case"assistant":return typeof e.content=="string"?{role:"assistant",content:[{type:"text",text:e.content}],providerOptions:e.providerOptions}:{role:"assistant",content:e.content.filter(n=>n.type!=="text"||n.text!==""||n.providerOptions!=null).filter(n=>n.type!=="tool-approval-request").map(n=>{const o=n.providerOptions;switch(n.type){case"file":{const{data:s,mediaType:a}=o_(n.data);return{type:"file",data:s,filename:n.filename,mediaType:a??n.mediaType,providerOptions:o}}case"reasoning":return{type:"reasoning",text:n.text,providerOptions:o};case"text":return{type:"text",text:n.text,providerOptions:o};case"tool-call":return{type:"tool-call",toolCallId:n.toolCallId,toolName:n.toolName,input:n.input,providerExecuted:n.providerExecuted,providerOptions:o};case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:a_(n.output),providerOptions:o}}}),providerOptions:e.providerOptions};case"tool":return{role:"tool",content:e.content.filter(n=>n.type!=="tool-approval-response"||n.providerExecuted).map(n=>{switch(n.type){case"tool-result":return{type:"tool-result",toolCallId:n.toolCallId,toolName:n.toolName,output:a_(n.output),providerOptions:n.providerOptions};case"tool-approval-response":return{type:"tool-approval-response",approvalId:n.approvalId,approved:n.approved,reason:n.reason}}}),providerOptions:e.providerOptions};default:{const n=r;throw new v8({role:n})}}}async function q8(e,t,r){const n=e.filter(s=>s.role==="user").map(s=>s.content).filter(s=>Array.isArray(s)).flat().filter(s=>s.type==="image"||s.type==="file").map(s=>{var a;const i=(a=s.mediaType)!=null?a:s.type==="image"?"image/*":void 0;let l=s.type==="image"?s.image:s.data;if(typeof l=="string")try{l=new URL(l)}catch{}return{mediaType:i,data:l}}).filter(s=>s.data instanceof URL).map(s=>({url:s.data,isUrlSupportedByModel:s.mediaType!=null&&F6({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),o=await t(n);return Object.fromEntries(o.map((s,a)=>s==null?null:[n[a].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function j8(e,t){var r;if(e.type==="text")return{type:"text",text:e.text,providerOptions:e.providerOptions};let n;const o=e.type;switch(o){case"image":n=e.image;break;case"file":n=e.data;break;default:throw new Error(`Unsupported part type: ${o}`)}const{data:s,mediaType:a}=o_(n);let i=a??e.mediaType,l=s;if(l instanceof URL){const c=t[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(o){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=R8({data:l,signatures:I8}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:e.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:e.filename,data:l,providerOptions:e.providerOptions}}}}function a_(e){return e.type!=="content"?e:{type:"content",value:e.value.map(t=>t.type!=="media"?t:t.mediaType.startsWith("image/")?{type:"image-data",data:t.data,mediaType:t.mediaType}:{type:"file-data",data:t.data,mediaType:t.mediaType})}}async function wa({toolCallId:e,input:t,output:r,tool:n,errorMode:o}){return o==="text"?{type:"error-text",value:uo(r)}:o==="json"?{type:"error-json",value:i_(r)}:n?.toModelOutput?await n.toModelOutput({toolCallId:e,input:t,output:r}):typeof r=="string"?{type:"text",value:r}:{type:"json",value:i_(r)}}function i_(e){return e===void 0?null:e}function _p({maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,seed:a,stopSequences:i}){if(e!=null){if(!Number.isInteger(e))throw new tn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be an integer"});if(e<1)throw new tn({parameter:"maxOutputTokens",value:e,message:"maxOutputTokens must be >= 1"})}if(t!=null&&typeof t!="number")throw new tn({parameter:"temperature",value:t,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new tn({parameter:"topP",value:r,message:"topP must be a number"});if(n!=null&&typeof n!="number")throw new tn({parameter:"topK",value:n,message:"topK must be a number"});if(o!=null&&typeof o!="number")throw new tn({parameter:"presencePenalty",value:o,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new tn({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(a!=null&&!Number.isInteger(a))throw new tn({parameter:"seed",value:a,message:"seed must be an integer"});return{maxOutputTokens:e,temperature:t,topP:r,topK:n,presencePenalty:o,frequencyPenalty:s,stopSequences:i,seed:a}}function L8(e){return e!=null&&Object.keys(e).length>0}async function l_({tools:e,toolChoice:t,activeTools:r}){if(!L8(e))return{tools:void 0,toolChoice:void 0};const n=r!=null?Object.entries(e).filter(([s])=>r.includes(s)):Object.entries(e),o=[];for(const[s,a]of n){const i=a.type;switch(i){case void 0:case"dynamic":case"function":o.push({type:"function",name:s,description:a.description,inputSchema:await yo(a.inputSchema).jsonSchema,...a.inputExamples!=null?{inputExamples:a.inputExamples}:{},providerOptions:a.providerOptions,...a.strict!=null?{strict:a.strict}:{}});break;case"provider":o.push({type:"provider",name:s,id:a.id,args:a.args});break;default:{const l=i;throw new Error(`Unsupported tool type: ${l}`)}}}return{tools:o,toolChoice:t==null?{type:"auto"}:typeof t=="string"?{type:t}:{type:"tool",toolName:t.toolName}}}var ba=Xi(()=>le([Zs(),d(),N(),Te(),Se(d(),ba.optional()),j(ba)])),wt=Se(d(),Se(d(),ba.optional())),c_=k({type:P("text"),text:d(),providerOptions:wt.optional()}),D8=k({type:P("image"),image:le([n_,el(URL)]),mediaType:d().optional(),providerOptions:wt.optional()}),u_=k({type:P("file"),data:le([n_,el(URL)]),filename:d().optional(),mediaType:d(),providerOptions:wt.optional()}),U8=k({type:P("reasoning"),text:d(),providerOptions:wt.optional()}),z8=k({type:P("tool-call"),toolCallId:d(),toolName:d(),input:Ne(),providerOptions:wt.optional(),providerExecuted:Te().optional()}),Z8=Qe("type",[k({type:P("text"),value:d(),providerOptions:wt.optional()}),k({type:P("json"),value:ba,providerOptions:wt.optional()}),k({type:P("execution-denied"),reason:d().optional(),providerOptions:wt.optional()}),k({type:P("error-text"),value:d(),providerOptions:wt.optional()}),k({type:P("error-json"),value:ba,providerOptions:wt.optional()}),k({type:P("content"),value:j(le([k({type:P("text"),text:d(),providerOptions:wt.optional()}),k({type:P("media"),data:d(),mediaType:d()}),k({type:P("file-data"),data:d(),mediaType:d(),filename:d().optional(),providerOptions:wt.optional()}),k({type:P("file-url"),url:d(),providerOptions:wt.optional()}),k({type:P("file-id"),fileId:le([d(),Se(d(),d())]),providerOptions:wt.optional()}),k({type:P("image-data"),data:d(),mediaType:d(),providerOptions:wt.optional()}),k({type:P("image-url"),url:d(),providerOptions:wt.optional()}),k({type:P("image-file-id"),fileId:le([d(),Se(d(),d())]),providerOptions:wt.optional()}),k({type:P("custom"),providerOptions:wt.optional()})]))})]),d_=k({type:P("tool-result"),toolCallId:d(),toolName:d(),output:Z8,providerOptions:wt.optional()}),F8=k({type:P("tool-approval-request"),approvalId:d(),toolCallId:d()}),V8=k({type:P("tool-approval-response"),approvalId:d(),approved:Te(),reason:d().optional()}),H8=k({role:P("system"),content:d(),providerOptions:wt.optional()}),B8=k({role:P("user"),content:le([d(),j(le([c_,D8,u_]))]),providerOptions:wt.optional()}),J8=k({role:P("assistant"),content:le([d(),j(le([c_,u_,U8,z8,d_,F8]))]),providerOptions:wt.optional()}),W8=k({role:P("tool"),content:j(le([d_,V8])),providerOptions:wt.optional()}),G8=le([H8,B8,J8,W8]);async function p_(e){if(e.prompt==null&&e.messages==null)throw new po({prompt:e,message:"prompt or messages must be defined"});if(e.prompt!=null&&e.messages!=null)throw new po({prompt:e,message:"prompt and messages cannot be defined at the same time"});if(e.system!=null&&typeof e.system!="string"&&!bo(e.system).every(n=>typeof n=="object"&&n!==null&&"role"in n&&n.role==="system"))throw new po({prompt:e,message:"system must be a string, SystemModelMessage, or array of SystemModelMessage"});let t;if(e.prompt!=null&&typeof e.prompt=="string")t=[{role:"user",content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new po({prompt:e,message:"prompt or messages must be defined"});if(t.length===0)throw new po({prompt:e,message:"messages must not be empty"});const r=await xr({value:t,schema:j(G8)});if(!r.success)throw new po({prompt:e,message:"The messages do not match the ModelMessage[] schema.",cause:r.error});return{messages:t,system:e.system}}function f_(e){if(!rp.isInstance(e))return e;const t=(process==null?void 0:process.env.NODE_ENV)==="production",r="https://ai-sdk.dev/unauthenticated-ai-gateway";return t?new Re({name:"GatewayError",message:`Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${r}`}):Object.assign(new Error(`\x1B[1m\x1B[31mUnauthenticated request to AI Gateway.\x1B[0m
572
572
 
573
573
  To authenticate, set the \x1B[33mAI_GATEWAY_API_KEY\x1B[0m environment variable with your API key.
574
574
 
@@ -576,14 +576,14 @@ Alternatively, you can use a provider module instead of the AI Gateway.
576
576
 
577
577
  Learn more: \x1B[34m${r}\x1B[0m
578
578
 
579
- `),{name:"GatewayAuthenticationError"})}function ya({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function p_({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,i])=>{if(a==="timeout"){const l=fp(i);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=i;return s},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(n??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var U$={startSpan(){return Ol},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Ol);if(typeof r=="function")return r(Ol);if(typeof n=="function")return n(Ol)}},Ol={spanContext(){return z$},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}},z$={traceId:"",spanId:"",traceFlags:0};function f_({isEnabled:e=!1,tracer:t}={}){return e?t||H8.getTracer("ai"):U$}async function va({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const a=cv.active();try{const i=await cv.with(a,()=>n(s));return o&&s.end(),i}catch(i){try{h_(s,i)}finally{s.end()}throw i}})}function h_(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:Ml.ERROR,message:t.message})):e.setStatus({code:Ml.ERROR})}async function Er({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(r[n]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(r[n]=s);continue}r[n]=o}return r}function m_(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?S$(r.data):r.data}:r)})))}function Z$(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function g_(){const e=Z$();return t=>{const r=go(t),n=[...e,...r];function o(s){const a=n.map(s).filter(Boolean);return async i=>{for(const l of a)try{await l(i)}catch{}}}return{onStart:o(s=>s.onStart),onStepStart:o(s=>s.onStepStart),onToolCallStart:o(s=>s.onToolCallStart),onToolCallFinish:o(s=>s.onToolCallFinish),onStepFinish:o(s=>s.onStepFinish),onFinish:o(s=>s.onFinish)}}}function mp(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:Vr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function gp(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function y_(e,t){var r,n,o,s,a,i,l,c,u,f;return{inputTokens:Vr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:Vr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:Vr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:Vr((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:Vr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:Vr((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:Vr((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:Vr(e.totalTokens,t.totalTokens),reasoningTokens:Vr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Vr(e.cachedInputTokens,t.cachedInputTokens)}}function Vr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Al(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const s=n in e?e[n]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&i?r[n]=Al(s,o):r[n]=o}return r}function F$({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(n=a)}const s=r["retry-after"];if(s&&n===void 0){const a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var V$=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>v_(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function v_(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(co(a)||t===0)throw a;const i=zd(a),l=[...s,a],c=l.length;if(c>t)throw new Jv({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&ht.isInstance(a)&&a.isRetryable===!0&&c<=t)return await T5(F$({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),v_(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new Jv({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function __({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new tn({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new tn({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:V$({maxRetries:r,abortSignal:t})}}function w_({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],i=t.content.filter(l=>l.type==="tool-approval-response");for(const l of i){const c=n[l.approvalId];if(c==null)throw new K8({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new up({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(f):a.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:a}}function ql(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function yp({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:f}){const{toolName:p,toolCallId:h,input:m}=e,_=t?.[p];if(_?.execute==null)return;const y={stepNumber:i,model:l,toolCall:e,messages:o,abortSignal:s,functionId:n?.functionId,metadata:n?.metadata,experimental_context:a};return va({name:"ai.toolCall",attributes:Er({telemetry:n,attributes:{...ya({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":h,"ai.toolCall.args":{output:()=>JSON.stringify(m)}}}),tracer:r,fn:async w=>{let v;await Fr({event:y,callbacks:u});const g=ql();try{const b=Ox({execute:_.execute.bind(_),input:m,options:{toolCallId:h,messages:o,abortSignal:s,experimental_context:a}});for await(const k of b)k.type==="preliminary"?c?.({...e,type:"tool-result",output:k.output,preliminary:!0}):v=k.output}catch(b){const k=ql()-g;return await Fr({event:{...y,success:!1,error:b,durationMs:k},callbacks:f}),h_(w,b),{type:"tool-error",toolCallId:h,toolName:p,input:m,error:b,dynamic:_.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const S=ql()-g;await Fr({event:{...y,success:!0,output:v,durationMs:S},callbacks:f});try{w.setAttributes(await Er({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(v)}}}))}catch{}return{type:"tool-result",toolCallId:h,toolName:p,input:m,output:v,dynamic:_.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function b_(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
580
- `)}function T_(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var k_=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=Jo(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=Go(this.base64Data)),this.uint8ArrayData}},H$=class extends k_{constructor(e){super(e),this.type="file"}};async function S_({tool:e,toolCall:t,messages:r,experimental_context:n}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:n})}var B$={};W8(B$,{array:()=>J$,choice:()=>K$,json:()=>Y$,object:()=>G$,text:()=>Ll});function W$(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(n,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):r=l;break}}}let i=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=e.substring(n,e.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function _a(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ir({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ir({text:W$(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Ll=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),G$=({schema:e,name:t,description:r})=>{const n=po(e);return{name:"object",responseFormat:Ut(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const a=await Ir({text:o});if(!a.success)throw new Ln({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=await Cr({value:a.value,schema:n});if(!i.success)throw new Ln({message:"No object generated: response did not match schema.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return i.value},async parsePartialOutput({text:o}){const s=await _a(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},J$=({element:e,name:t,description:r})=>{const n=po(e);return{name:"array",responseFormat:Ut(n.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},s){const a=await Ir({text:o});if(!a.success)throw new Ln({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))throw new Ln({message:"No object generated: response did not match schema.",cause:new lo({value:i,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of i.elements){const c=await Cr({value:l,schema:n});if(!c.success)throw new Ln({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return i.elements},async parsePartialOutput({text:o}){const s=await _a(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const i=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of i){const u=await Cr({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},K$=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){const s=await Ir({text:n});if(!s.success)throw new Ln({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new Ln({message:"No object generated: response did not match schema.",cause:new lo({value:a,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:n}){const o=await _a(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(i=>i.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),Y$=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:r},n){const o=await Ir({text:r});if(!o.success)throw new Ln({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){const n=await _a(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function C_({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await I_(e);throw new dp({toolName:e.toolName})}try{return await x_({toolCall:e,tools:t})}catch(a){if(r==null||!(dp.isInstance(a)||cp.isInstance(a)))throw a;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{const{inputSchema:c}=t[l];return await po(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new o$({cause:l,originalError:a})}if(i==null)throw a;return await x_({toolCall:i,tools:t})}}catch(a){const i=await Ir({text:e.input}),l=i.success?i.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function I_(e){const t=e.input.trim()===""?{success:!0,value:{}}:await Ir({text:e.input});if(t.success===!1)throw new cp({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function x_({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await I_(e);throw new dp({toolName:e.toolName,availableTools:Object.keys(t)})}const o=po(n.inputSchema),s=e.input.trim()===""?await Cr({value:{},schema:o}):await Ir({text:e.input,schema:o});if(s.success===!1)throw new cp({toolName:r,toolInput:e.input,cause:s.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:n.title}}var E_=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:s,finishReason:a,rawFinishReason:i,usage:l,warnings:c,request:u,response:f,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=s,this.finishReason=a,this.rawFinishReason=i,this.usage=l,this.warnings=c,this.request=u,this.response=f,this.providerMetadata=p}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function vp(e){return({steps:t})=>t.length===e}async function $_({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function _p({content:e,tools:t}){const r=[],n=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":n.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":n.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await ma({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await ma({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await ma({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function R_(...e){const t=e.filter(n=>n!=null);if(t.length===0)return;if(t.length===1)return t[0];const r=new AbortController;for(const n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var Q$=ia({prefix:"aitxt",size:24});async function P_({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=vp(1),experimental_output:f,output:p=f,experimental_telemetry:h,providerOptions:m,experimental_activeTools:_,activeTools:y=_,experimental_prepareStep:w,prepareStep:v=w,experimental_repairToolCall:g,experimental_download:S,experimental_context:b,experimental_include:k,_internal:{generateId:C=Q$}={},experimental_onStart:R,experimental_onStepStart:I,experimental_onToolCallStart:j,experimental_onToolCallFinish:N,onStepFinish:L,onFinish:z,...H}){const ee=Nl(e),te=g_(),X=go(u),V=fp(l),se=Xv(l),D=se!=null?new AbortController:void 0,E=R_(i,V!=null?AbortSignal.timeout(V):void 0,D?.signal),{maxRetries:U,retry:Z}=__({maxRetries:a,abortSignal:E}),x=hp(H),M=qn(c??{},`ai/${e_}`),W=p_({model:ee,telemetry:h,headers:M,settings:{...x,maxRetries:U}}),oe={provider:ee.provider,modelId:ee.modelId},ne=await u_({system:n,prompt:o,messages:s}),we=te(h?.integrations);await Fr({event:{model:oe,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:y,maxOutputTokens:x.maxOutputTokens,temperature:x.temperature,topP:x.topP,topK:x.topK,presencePenalty:x.presencePenalty,frequencyPenalty:x.frequencyPenalty,stopSequences:x.stopSequences,seed:x.seed,maxRetries:U,timeout:l,headers:c,providerOptions:m,stopWhen:u,output:p,abortSignal:i,include:k,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b},callbacks:[R,we.onStart]});const K=f_(h);try{return await va({name:"ai.generateText",attributes:Er({telemetry:h,attributes:{...ya({operationId:"ai.generateText",telemetry:h}),...W,"ai.model.provider":ee.provider,"ai.model.id":ee.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:K,fn:async A=>{var F,G,Q,pe,Ie,Ge,dt,wt,st,it,zt,bt,Br,ar,et,$r,$,Y,je,$e;const lt=ne.messages,kt=[],{approvedToolApprovals:Yt,deniedToolApprovals:gr}=w_({messages:lt}),yr=Yt.filter(vt=>!vt.toolCall.providerExecuted);if(gr.length>0||yr.length>0){const vt=await M_({toolCalls:yr.map(Ae=>Ae.toolCall),tools:t,tracer:K,telemetry:h,messages:lt,abortSignal:E,experimental_context:b,stepNumber:0,model:oe,onToolCallStart:[j,we.onToolCallStart],onToolCallFinish:[N,we.onToolCallFinish]}),Zt=[];for(const Ae of vt){const ir=await ma({toolCallId:Ae.toolCallId,input:Ae.input,tool:t?.[Ae.toolName],output:Ae.type==="tool-result"?Ae.output:Ae.error,errorMode:Ae.type==="tool-error"?"text":"none"});Zt.push({type:"tool-result",toolCallId:Ae.toolCallId,toolName:Ae.toolName,output:ir})}for(const Ae of gr)Zt.push({type:"tool-result",toolCallId:Ae.toolCall.toolCallId,toolName:Ae.toolCall.toolName,output:{type:"execution-denied",reason:Ae.approvalResponse.reason,...Ae.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ae.approvalResponse.approvalId}}}}});kt.push({role:"tool",content:Zt})}const ie=[...Yt,...gr].filter(vt=>vt.toolCall.providerExecuted);ie.length>0&&kt.push({role:"tool",content:ie.map(vt=>({type:"tool-approval-response",approvalId:vt.approvalResponse.approvalId,approved:vt.approvalResponse.approved,reason:vt.approvalResponse.reason,providerExecuted:!0}))});const Je=hp(H);let Ue,gt=[],Me=[];const ze=[],jn=new Map;do{const vt=se!=null?setTimeout(()=>D.abort(),se):void 0;try{const Zt=[...lt,...kt],Ae=await v?.({model:ee,steps:ze,stepNumber:ze.length,messages:Zt,experimental_context:b}),ir=Nl((F=Ae?.model)!=null?F:ee),Dn={provider:ir.provider,modelId:ir.modelId},bn=await n_({prompt:{system:(G=Ae?.system)!=null?G:ne.system,messages:(Q=Ae?.messages)!=null?Q:Zt},supportedUrls:await ir.supportedUrls,download:S});b=(pe=Ae?.experimental_context)!=null?pe:b;const ac=(Ie=Ae?.activeTools)!=null?Ie:y,{toolChoice:vo,tools:as}=await a_({tools:t,toolChoice:(Ge=Ae?.toolChoice)!=null?Ge:r,activeTools:ac}),Un=(dt=Ae?.messages)!=null?dt:Zt,St=(wt=Ae?.system)!=null?wt:ne.system,Wr=Al(m,Ae?.providerOptions);await Fr({event:{stepNumber:ze.length,model:Dn,system:St,messages:Un,tools:t,toolChoice:vo,activeTools:ac,steps:[...ze],providerOptions:Wr,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:i,include:k,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b},callbacks:[I,we.onStepStart]}),Ue=await Z(()=>{var qe;return va({name:"ai.generateText.doGenerate",attributes:Er({telemetry:h,attributes:{...ya({operationId:"ai.generateText.doGenerate",telemetry:h}),...W,"ai.model.provider":ir.provider,"ai.model.id":ir.modelId,"ai.prompt.messages":{input:()=>m_(bn)},"ai.prompt.tools":{input:()=>as?.map(Ft=>JSON.stringify(Ft))},"ai.prompt.toolChoice":{input:()=>vo!=null?JSON.stringify(vo):void 0},"gen_ai.system":ir.provider,"gen_ai.request.model":ir.modelId,"gen_ai.request.frequency_penalty":H.frequencyPenalty,"gen_ai.request.max_tokens":H.maxOutputTokens,"gen_ai.request.presence_penalty":H.presencePenalty,"gen_ai.request.stop_sequences":H.stopSequences,"gen_ai.request.temperature":(qe=H.temperature)!=null?qe:void 0,"gen_ai.request.top_k":H.topK,"gen_ai.request.top_p":H.topP}}),tracer:K,fn:async Ft=>{var wo,vr,Na,lc,cc,Zn,Fn,ls;const ot=await ir.doGenerate({...Je,tools:as,toolChoice:vo,responseFormat:await p?.responseFormat,prompt:bn,providerOptions:Wr,abortSignal:E,headers:M}),_r={id:(vr=(wo=ot.response)==null?void 0:wo.id)!=null?vr:C(),timestamp:(lc=(Na=ot.response)==null?void 0:Na.timestamp)!=null?lc:new Date,modelId:(Zn=(cc=ot.response)==null?void 0:cc.modelId)!=null?Zn:ir.modelId,headers:(Fn=ot.response)==null?void 0:Fn.headers,body:(ls=ot.response)==null?void 0:ls.body},Oa=mp(ot.usage);return Ft.setAttributes(await Er({telemetry:h,attributes:{"ai.response.finishReason":ot.finishReason.unified,"ai.response.text":{output:()=>T_(ot.content)},"ai.response.reasoning":{output:()=>b_(ot.content)},"ai.response.toolCalls":{output:()=>{const xt=N_(ot.content);return xt==null?void 0:JSON.stringify(xt)}},"ai.response.id":_r.id,"ai.response.model":_r.modelId,"ai.response.timestamp":_r.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ot.providerMetadata),"ai.usage.inputTokens":ot.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":ot.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":ot.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":ot.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":ot.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":ot.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":ot.usage.outputTokens.reasoning,"ai.usage.totalTokens":Oa.totalTokens,"ai.usage.reasoningTokens":ot.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":ot.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[ot.finishReason.unified],"gen_ai.response.id":_r.id,"gen_ai.response.model":_r.modelId,"gen_ai.usage.input_tokens":ot.usage.inputTokens.total,"gen_ai.usage.output_tokens":ot.usage.outputTokens.total}})),{...ot,response:_r}}})});const zn=await Promise.all(Ue.content.filter(qe=>qe.type==="tool-call").map(qe=>C_({toolCall:qe,tools:t,repairToolCall:g,system:n,messages:Zt}))),is={};for(const qe of zn){if(qe.invalid)continue;const Ft=t?.[qe.toolName];Ft!=null&&(Ft?.onInputAvailable!=null&&await Ft.onInputAvailable({input:qe.input,toolCallId:qe.toolCallId,messages:Zt,abortSignal:E,experimental_context:b}),await S_({tool:Ft,toolCall:qe,messages:Zt,experimental_context:b})&&(is[qe.toolCallId]={type:"tool-approval-request",approvalId:C(),toolCall:qe}))}const ic=zn.filter(qe=>qe.invalid&&qe.dynamic);Me=[];for(const qe of ic)Me.push({type:"tool-error",toolCallId:qe.toolCallId,toolName:qe.toolName,input:qe.input,error:zd(qe.error),dynamic:!0});gt=zn.filter(qe=>!qe.providerExecuted),t!=null&&Me.push(...await M_({toolCalls:gt.filter(qe=>!qe.invalid&&is[qe.toolCallId]==null),tools:t,tracer:K,telemetry:h,messages:Zt,abortSignal:E,experimental_context:b,stepNumber:ze.length,model:Dn,onToolCallStart:[j,we.onToolCallStart],onToolCallFinish:[N,we.onToolCallFinish]}));for(const qe of zn){if(!qe.providerExecuted)continue;const Ft=t?.[qe.toolName];Ft?.type==="provider"&&Ft.supportsDeferredResults&&(Ue.content.some(vr=>vr.type==="tool-result"&&vr.toolCallId===qe.toolCallId)||jn.set(qe.toolCallId,{toolName:qe.toolName}))}for(const qe of Ue.content)qe.type==="tool-result"&&jn.delete(qe.toolCallId);const _o=e7({content:Ue.content,toolCalls:zn,toolOutputs:Me,toolApprovalRequests:Object.values(is),tools:t});kt.push(...await _p({content:_o,tools:t}));const Pa=(st=k?.requestBody)==null||st?(it=Ue.request)!=null?it:{}:{...Ue.request,body:void 0},Wp={...Ue.response,messages:structuredClone(kt),body:(zt=k?.responseBody)==null||zt?(bt=Ue.response)==null?void 0:bt.body:void 0},Gp=ze.length,Ma=new E_({stepNumber:Gp,model:Dn,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b,content:_o,finishReason:Ue.finishReason.unified,rawFinishReason:Ue.finishReason.raw,usage:mp(Ue.usage),warnings:Ue.warnings,providerMetadata:Ue.providerMetadata,request:Pa,response:Wp});pp({warnings:(Br=Ue.warnings)!=null?Br:[],provider:Dn.provider,model:Dn.modelId}),ze.push(Ma),await Fr({event:Ma,callbacks:[L,we.onStepFinish]})}finally{vt!=null&&clearTimeout(vt)}}while((gt.length>0&&Me.length===gt.length||jn.size>0)&&!await $_({stopConditions:X,steps:ze}));A.setAttributes(await Er({telemetry:h,attributes:{"ai.response.finishReason":Ue.finishReason.unified,"ai.response.text":{output:()=>T_(Ue.content)},"ai.response.reasoning":{output:()=>b_(Ue.content)},"ai.response.toolCalls":{output:()=>{const vt=N_(Ue.content);return vt==null?void 0:JSON.stringify(vt)}},"ai.response.providerMetadata":JSON.stringify(Ue.providerMetadata)}}));const Ee=ze[ze.length-1],nt=ze.reduce((vt,Zt)=>y_(vt,Zt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});A.setAttributes(await Er({telemetry:h,attributes:{"ai.usage.inputTokens":nt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ar=nt.inputTokenDetails)==null?void 0:ar.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(et=nt.inputTokenDetails)==null?void 0:et.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":($r=nt.inputTokenDetails)==null?void 0:$r.cacheWriteTokens,"ai.usage.outputTokens":nt.outputTokens,"ai.usage.outputTokenDetails.textTokens":($=nt.outputTokenDetails)==null?void 0:$.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Y=nt.outputTokenDetails)==null?void 0:Y.reasoningTokens,"ai.usage.totalTokens":nt.totalTokens,"ai.usage.reasoningTokens":(je=nt.outputTokenDetails)==null?void 0:je.reasoningTokens,"ai.usage.cachedInputTokens":($e=nt.inputTokenDetails)==null?void 0:$e.cacheReadTokens}})),await Fr({event:{stepNumber:Ee.stepNumber,model:Ee.model,functionId:Ee.functionId,metadata:Ee.metadata,experimental_context:Ee.experimental_context,finishReason:Ee.finishReason,rawFinishReason:Ee.rawFinishReason,usage:Ee.usage,content:Ee.content,text:Ee.text,reasoningText:Ee.reasoningText,reasoning:Ee.reasoning,files:Ee.files,sources:Ee.sources,toolCalls:Ee.toolCalls,staticToolCalls:Ee.staticToolCalls,dynamicToolCalls:Ee.dynamicToolCalls,toolResults:Ee.toolResults,staticToolResults:Ee.staticToolResults,dynamicToolResults:Ee.dynamicToolResults,request:Ee.request,response:Ee.response,warnings:Ee.warnings,providerMetadata:Ee.providerMetadata,steps:ze,totalUsage:nt},callbacks:[z,we.onFinish]});let yt;return Ee.finishReason==="stop"&&(yt=await(p??Ll()).parseCompleteOutput({text:Ee.text},{response:Ee.response,usage:Ee.usage,finishReason:Ee.finishReason})),new X$({steps:ze,totalUsage:nt,output:yt})}})}catch(A){throw d_(A)}}async function M_({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>yp({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var X$=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new Nv;return this._output}};function N_(e){const t=e.filter(r=>r.type==="tool-call");if(t.length!==0)return t.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function e7({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new k_(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(i=>i.toolCallId===a.toolCallId));break}case"tool-result":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,error:a.result,providerExecuted:!0,dynamic:i.dynamic,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,output:a.result,providerExecuted:!0,dynamic:i.dynamic,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-approval-request":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null)throw new up({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:i});break}}return[...s,...r,...n]}function jl(e,t){const r=new Headers(e??{});for(const[n,o]of Object.entries(t))r.has(n)||r.set(n,o);return r}function t7({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:jl(r,{"content-type":"text/plain; charset=utf-8"})})}function O_({response:e,status:t,statusText:r,headers:n,stream:o}){const s=t??200;r!==void 0?e.writeHead(s,r,n):e.writeHead(s,n);const a=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await a.read();if(l)break;e.write(c)||await new Promise(f=>{e.once("drain",f)})}}catch(l){throw l}finally{e.end()}})()}function r7({response:e,status:t,statusText:r,headers:n,textStream:o}){O_({response:e,status:t,statusText:r,headers:Object.fromEntries(jl(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var A_=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
579
+ `),{name:"GatewayAuthenticationError"})}function ka({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId!=null?` ${t.functionId}`:""}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function h_({model:e,settings:t,telemetry:r,headers:n}){var o;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((s,[a,i])=>{if(a==="timeout"){const l=vp(i);l!=null&&(s[`ai.settings.${a}`]=l)}else s[`ai.settings.${a}`]=i;return s},{}),...Object.entries((o=r?.metadata)!=null?o:{}).reduce((s,[a,i])=>(s[`ai.telemetry.metadata.${a}`]=i,s),{}),...Object.entries(n??{}).reduce((s,[a,i])=>(i!==void 0&&(s[`ai.request.headers.${a}`]=i),s),{})}}var K8={startSpan(){return Dl},startActiveSpan(e,t,r,n){if(typeof t=="function")return t(Dl);if(typeof r=="function")return r(Dl);if(typeof n=="function")return n(Dl)}},Dl={spanContext(){return Y8},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}},Y8={traceId:"",spanId:"",traceFlags:0};function m_({isEnabled:e=!1,tracer:t}={}){return e?t||t8.getTracer("ai"):K8}async function Ta({name:e,tracer:t,attributes:r,fn:n,endWhenDone:o=!0}){return t.startActiveSpan(e,{attributes:await r},async s=>{const a=dv.active();try{const i=await dv.with(a,()=>n(s));return o&&s.end(),i}catch(i){try{g_(s,i)}finally{s.end()}throw i}})}function g_(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:jl.ERROR,message:t.message})):e.setStatus({code:jl.ERROR})}async function Er({telemetry:e,attributes:t}){if(e?.isEnabled!==!0)return{};const r={};for(const[n,o]of Object.entries(t))if(o!=null){if(typeof o=="object"&&"input"in o&&typeof o.input=="function"){if(e?.recordInputs===!1)continue;const s=await o.input();s!=null&&(r[n]=s);continue}if(typeof o=="object"&&"output"in o&&typeof o.output=="function"){if(e?.recordOutputs===!1)continue;const s=await o.output();s!=null&&(r[n]=s);continue}r[n]=o}return r}function y_(e){return JSON.stringify(e.map(t=>({...t,content:typeof t.content=="string"?t.content:t.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?N8(r.data):r.data}:r)})))}function Q8(){var e;return(e=globalThis.AI_SDK_TELEMETRY_INTEGRATIONS)!=null?e:[]}function v_(){const e=Q8();return t=>{const r=bo(t),n=[...e,...r];function o(s){const a=n.map(s).filter(Boolean);return async i=>{for(const l of a)try{await l(i)}catch{}}}return{onStart:o(s=>s.onStart),onStepStart:o(s=>s.onStepStart),onToolCallStart:o(s=>s.onToolCallStart),onToolCallFinish:o(s=>s.onToolCallFinish),onStepFinish:o(s=>s.onStepFinish),onFinish:o(s=>s.onFinish)}}}function wp(e){return{inputTokens:e.inputTokens.total,inputTokenDetails:{noCacheTokens:e.inputTokens.noCache,cacheReadTokens:e.inputTokens.cacheRead,cacheWriteTokens:e.inputTokens.cacheWrite},outputTokens:e.outputTokens.total,outputTokenDetails:{textTokens:e.outputTokens.text,reasoningTokens:e.outputTokens.reasoning},totalTokens:Vr(e.inputTokens.total,e.outputTokens.total),raw:e.raw,reasoningTokens:e.outputTokens.reasoning,cachedInputTokens:e.inputTokens.cacheRead}}function bp(){return{inputTokens:void 0,inputTokenDetails:{noCacheTokens:void 0,cacheReadTokens:void 0,cacheWriteTokens:void 0},outputTokens:void 0,outputTokenDetails:{textTokens:void 0,reasoningTokens:void 0},totalTokens:void 0,raw:void 0}}function __(e,t){var r,n,o,s,a,i,l,c,u,f;return{inputTokens:Vr(e.inputTokens,t.inputTokens),inputTokenDetails:{noCacheTokens:Vr((r=e.inputTokenDetails)==null?void 0:r.noCacheTokens,(n=t.inputTokenDetails)==null?void 0:n.noCacheTokens),cacheReadTokens:Vr((o=e.inputTokenDetails)==null?void 0:o.cacheReadTokens,(s=t.inputTokenDetails)==null?void 0:s.cacheReadTokens),cacheWriteTokens:Vr((a=e.inputTokenDetails)==null?void 0:a.cacheWriteTokens,(i=t.inputTokenDetails)==null?void 0:i.cacheWriteTokens)},outputTokens:Vr(e.outputTokens,t.outputTokens),outputTokenDetails:{textTokens:Vr((l=e.outputTokenDetails)==null?void 0:l.textTokens,(c=t.outputTokenDetails)==null?void 0:c.textTokens),reasoningTokens:Vr((u=e.outputTokenDetails)==null?void 0:u.reasoningTokens,(f=t.outputTokenDetails)==null?void 0:f.reasoningTokens)},totalTokens:Vr(e.totalTokens,t.totalTokens),reasoningTokens:Vr(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:Vr(e.cachedInputTokens,t.cachedInputTokens)}}function Vr(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function Ul(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const r={...e};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const o=t[n];if(o===void 0)continue;const s=n in e?e[n]:void 0,a=o!==null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);a&&i?r[n]=Ul(s,o):r[n]=o}return r}function X8({error:e,exponentialBackoffDelay:t}){const r=e.responseHeaders;if(!r)return t;let n;const o=r["retry-after-ms"];if(o){const a=parseFloat(o);Number.isNaN(a)||(n=a)}const s=r["retry-after"];if(s&&n===void 0){const a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}return n!=null&&!Number.isNaN(n)&&0<=n&&(n<60*1e3||n<t)?n:t}var eR=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:r=2,abortSignal:n}={})=>async o=>w_(o,{maxRetries:e,delayInMs:t,backoffFactor:r,abortSignal:n});async function w_(e,{maxRetries:t,delayInMs:r,backoffFactor:n,abortSignal:o},s=[]){try{return await e()}catch(a){if(ho(a)||t===0)throw a;const i=Hd(a),l=[...s,a],c=l.length;if(c>t)throw new Yv({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(a instanceof Error&&_t.isInstance(a)&&a.isRetryable===!0&&c<=t)return await M6(X8({error:a,exponentialBackoffDelay:r}),{abortSignal:o}),w_(e,{maxRetries:t,delayInMs:n*r,backoffFactor:n,abortSignal:o},l);throw c===1?a:new Yv({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function b_({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new tn({parameter:"maxRetries",value:e,message:"maxRetries must be an integer"});if(e<0)throw new tn({parameter:"maxRetries",value:e,message:"maxRetries must be >= 0"})}const r=e??2;return{maxRetries:r,retry:eR({maxRetries:r,abortSignal:t})}}function k_({messages:e}){const t=e.at(-1);if(t?.role!="tool")return{approvedToolApprovals:[],deniedToolApprovals:[]};const r={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-call"&&(r[u.toolCallId]=u)}const n={};for(const l of e)if(l.role==="assistant"&&typeof l.content!="string"){const c=l.content;for(const u of c)u.type==="tool-approval-request"&&(n[u.approvalId]=u)}const o={};for(const l of t.content)l.type==="tool-result"&&(o[l.toolCallId]=l);const s=[],a=[],i=t.content.filter(l=>l.type==="tool-approval-response");for(const l of i){const c=n[l.approvalId];if(c==null)throw new a8({approvalId:l.approvalId});if(o[c.toolCallId]!=null)continue;const u=r[c.toolCallId];if(u==null)throw new mp({toolCallId:c.toolCallId,approvalId:c.approvalId});const f={approvalRequest:c,approvalResponse:l,toolCall:u};l.approved?s.push(f):a.push(f)}return{approvedToolApprovals:s,deniedToolApprovals:a}}function zl(){var e,t;return(t=(e=globalThis?.performance)==null?void 0:e.now())!=null?t:Date.now()}async function kp({toolCall:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onPreliminaryToolResult:c,onToolCallStart:u,onToolCallFinish:f}){const{toolName:p,toolCallId:h,input:m}=e,_=t?.[p];if(_?.execute==null)return;const g={stepNumber:i,model:l,toolCall:e,messages:o,abortSignal:s,functionId:n?.functionId,metadata:n?.metadata,experimental_context:a};return Ta({name:"ai.toolCall",attributes:Er({telemetry:n,attributes:{...ka({operationId:"ai.toolCall",telemetry:n}),"ai.toolCall.name":p,"ai.toolCall.id":h,"ai.toolCall.args":{output:()=>JSON.stringify(m)}}}),tracer:r,fn:async w=>{let v;await Fr({event:g,callbacks:u});const y=zl();try{const b=V5({execute:_.execute.bind(_),input:m,options:{toolCallId:h,messages:o,abortSignal:s,experimental_context:a}});for await(const T of b)T.type==="preliminary"?c?.({...e,type:"tool-result",output:T.output,preliminary:!0}):v=T.output}catch(b){const T=zl()-y;return await Fr({event:{...g,success:!1,error:b,durationMs:T},callbacks:f}),g_(w,b),{type:"tool-error",toolCallId:h,toolName:p,input:m,error:b,dynamic:_.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}const S=zl()-y;await Fr({event:{...g,success:!0,output:v,durationMs:S},callbacks:f});try{w.setAttributes(await Er({telemetry:n,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(v)}}}))}catch{}return{type:"tool-result",toolCallId:h,toolName:p,input:m,output:v,dynamic:_.type==="dynamic",...e.providerMetadata!=null?{providerMetadata:e.providerMetadata}:{}}}})}function T_(e){const t=e.filter(r=>r.type==="reasoning");return t.length===0?void 0:t.map(r=>r.text).join(`
580
+ `)}function S_(e){const t=e.filter(r=>r.type==="text");if(t.length!==0)return t.map(r=>r.text).join("")}var C_=class{constructor({data:e,mediaType:t}){const r=e instanceof Uint8Array;this.base64Data=r?void 0:e,this.uint8ArrayData=r?e:void 0,this.mediaType=t}get base64(){return this.base64Data==null&&(this.base64Data=ns(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=rs(this.base64Data)),this.uint8ArrayData}},tR=class extends C_{constructor(e){super(e),this.type="file"}};async function x_({tool:e,toolCall:t,messages:r,experimental_context:n}){return e.needsApproval==null?!1:typeof e.needsApproval=="boolean"?e.needsApproval:await e.needsApproval(t.input,{toolCallId:t.toolCallId,messages:r,experimental_context:n})}var rR={};n8(rR,{array:()=>sR,choice:()=>aR,json:()=>iR,object:()=>oR,text:()=>Zl});function nR(e){const t=["ROOT"];let r=-1,n=null;function o(l,c,u){switch(l){case'"':{r=c,t.pop(),t.push(u),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,n=c,t.pop(),t.push(u),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,t.pop(),t.push(u),t.push("INSIDE_NUMBER");break}case"{":{r=c,t.pop(),t.push(u),t.push("INSIDE_OBJECT_START");break}case"[":{r=c,t.pop(),t.push(u),t.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,t.pop();break}}}function a(l,c){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,t.pop();break}}}for(let l=0;l<e.length;l++){const c=e[l];switch(t[t.length-1]){case"ROOT":o(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{t.pop(),r=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,t.pop();break}default:{r=l,o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,t.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(n,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(c,l)):r=l;break}}}let i=e.slice(0,r+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=e.substring(n,e.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function Sa(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ir({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ir({text:nR(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Zl=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),oR=({schema:e,name:t,description:r})=>{const n=yo(e);return{name:"object",responseFormat:Ht(n.jsonSchema).then(o=>({type:"json",schema:o,...t!=null&&{name:t},...r!=null&&{description:r}})),async parseCompleteOutput({text:o},s){const a=await Ir({text:o});if(!a.success)throw new Un({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=await xr({value:a.value,schema:n});if(!i.success)throw new Un({message:"No object generated: response did not match schema.",cause:i.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});return i.value},async parsePartialOutput({text:o}){const s=await Sa(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:s.value}}},createElementStreamTransform(){}}},sR=({element:e,name:t,description:r})=>{const n=yo(e);return{name:"array",responseFormat:Ht(n.jsonSchema).then(o=>{const{$schema:s,...a}=o;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:a}},required:["elements"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}}),async parseCompleteOutput({text:o},s){const a=await Ir({text:o});if(!a.success)throw new Un({message:"No object generated: could not parse the response.",cause:a.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});const i=a.value;if(i==null||typeof i!="object"||!("elements"in i)||!Array.isArray(i.elements))throw new Un({message:"No object generated: response did not match schema.",cause:new fo({value:i,cause:"response must be an object with an elements array"}),text:o,response:s.response,usage:s.usage,finishReason:s.finishReason});for(const l of i.elements){const c=await xr({value:l,schema:n});if(!c.success)throw new Un({message:"No object generated: response did not match schema.",cause:c.error,text:o,response:s.response,usage:s.usage,finishReason:s.finishReason})}return i.elements},async parsePartialOutput({text:o}){const s=await Sa(o);switch(s.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const a=s.value;if(a==null||typeof a!="object"||!("elements"in a)||!Array.isArray(a.elements))return;const i=s.state==="repaired-parse"&&a.elements.length>0?a.elements.slice(0,-1):a.elements,l=[];for(const c of i){const u=await xr({value:c,schema:n});u.success&&l.push(u.value)}return{partial:l}}}},createElementStreamTransform(){let o=0;return new TransformStream({transform({partialOutput:s},a){if(s!=null)for(;o<s.length;o++)a.enqueue(s[o])}})}}},aR=({options:e,name:t,description:r})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1},...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:n},o){const s=await Ir({text:n});if(!s.success)throw new Un({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});const a=s.value;if(a==null||typeof a!="object"||!("result"in a)||typeof a.result!="string"||!e.includes(a.result))throw new Un({message:"No object generated: response did not match schema.",cause:new fo({value:a,cause:"response must be an object that contains a choice value."}),text:n,response:o.response,usage:o.usage,finishReason:o.finishReason});return a.result},async parsePartialOutput({text:n}){const o=await Sa(n);switch(o.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const s=o.value;if(s==null||typeof s!="object"||!("result"in s)||typeof s.result!="string")return;const a=e.filter(i=>i.startsWith(s.result));return o.state==="successful-parse"?a.includes(s.result)?{partial:s.result}:void 0:a.length===1?{partial:a[0]}:void 0}}},createElementStreamTransform(){}}),iR=({name:e,description:t}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:r},n){const o=await Ir({text:r});if(!o.success)throw new Un({message:"No object generated: could not parse the response.",cause:o.error,text:r,response:n.response,usage:n.usage,finishReason:n.finishReason});return o.value},async parsePartialOutput({text:r}){const n=await Sa(r);switch(n.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return n.value===void 0?void 0:{partial:n.value}}},createElementStreamTransform(){}});async function I_({toolCall:e,tools:t,repairToolCall:r,system:n,messages:o}){var s;try{if(t==null){if(e.providerExecuted&&e.dynamic)return await $_(e);throw new gp({toolName:e.toolName})}try{return await E_({toolCall:e,tools:t})}catch(a){if(r==null||!(gp.isInstance(a)||hp.isInstance(a)))throw a;let i=null;try{i=await r({toolCall:e,tools:t,inputSchema:async({toolName:l})=>{const{inputSchema:c}=t[l];return await yo(c).jsonSchema},system:n,messages:o,error:a})}catch(l){throw new h8({cause:l,originalError:a})}if(i==null)throw a;return await E_({toolCall:i,tools:t})}}catch(a){const i=await Ir({text:e.input}),l=i.success?i.value:e.input;return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:l,dynamic:!0,invalid:!0,error:a,title:(s=t?.[e.toolName])==null?void 0:s.title,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}}async function $_(e){const t=e.input.trim()===""?{success:!0,value:{}}:await Ir({text:e.input});if(t.success===!1)throw new hp({toolName:e.toolName,toolInput:e.input,cause:t.error});return{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:t.value,providerExecuted:!0,dynamic:!0,providerMetadata:e.providerMetadata}}async function E_({toolCall:e,tools:t}){const r=e.toolName,n=t[r];if(n==null){if(e.providerExecuted&&e.dynamic)return await $_(e);throw new gp({toolName:e.toolName,availableTools:Object.keys(t)})}const o=yo(n.inputSchema),s=e.input.trim()===""?await xr({value:{},schema:o}):await Ir({text:e.input,schema:o});if(s.success===!1)throw new hp({toolName:r,toolInput:e.input,cause:s.error});return n.type==="dynamic"?{type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0,title:n.title}:{type:"tool-call",toolCallId:e.toolCallId,toolName:r,input:s.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:n.title}}var R_=class{constructor({stepNumber:e,model:t,functionId:r,metadata:n,experimental_context:o,content:s,finishReason:a,rawFinishReason:i,usage:l,warnings:c,request:u,response:f,providerMetadata:p}){this.stepNumber=e,this.model=t,this.functionId=r,this.metadata=n,this.experimental_context=o,this.content=s,this.finishReason=a,this.rawFinishReason=i,this.usage=l,this.warnings=c,this.request=u,this.response=f,this.providerMetadata=p}get text(){return this.content.filter(e=>e.type==="text").map(e=>e.text).join("")}get reasoning(){return this.content.filter(e=>e.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join("")}get files(){return this.content.filter(e=>e.type==="file").map(e=>e.file)}get sources(){return this.content.filter(e=>e.type==="source")}get toolCalls(){return this.content.filter(e=>e.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function Tp(e){return({steps:t})=>t.length===e}async function P_({stopConditions:e,steps:t}){return(await Promise.all(e.map(r=>r({steps:t})))).some(r=>r)}async function Sp({content:e,tools:t}){const r=[],n=[];for(const s of e)if(s.type!=="source"&&!((s.type==="tool-result"||s.type==="tool-error")&&!s.providerExecuted)&&!(s.type==="text"&&s.text.length===0))switch(s.type){case"text":n.push({type:"text",text:s.text,providerOptions:s.providerMetadata});break;case"reasoning":n.push({type:"reasoning",text:s.text,providerOptions:s.providerMetadata});break;case"file":n.push({type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata});break;case"tool-call":n.push({type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata});break;case"tool-result":{const a=await wa({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.output,errorMode:"none"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-error":{const a=await wa({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.error,errorMode:"json"});n.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,providerOptions:s.providerMetadata});break}case"tool-approval-request":n.push({type:"tool-approval-request",approvalId:s.approvalId,toolCallId:s.toolCall.toolCallId});break}n.length>0&&r.push({role:"assistant",content:n});const o=[];for(const s of e){if(!(s.type==="tool-result"||s.type==="tool-error")||s.providerExecuted)continue;const a=await wa({toolCallId:s.toolCallId,input:s.input,tool:t?.[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"});o.push({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:a,...s.providerMetadata!=null?{providerOptions:s.providerMetadata}:{}})}return o.length>0&&r.push({role:"tool",content:o}),r}function M_(...e){const t=e.filter(n=>n!=null);if(t.length===0)return;if(t.length===1)return t[0];const r=new AbortController;for(const n of t){if(n.aborted)return r.abort(n.reason),r.signal;n.addEventListener("abort",()=>{r.abort(n.reason)},{once:!0})}return r.signal}var lR=pa({prefix:"aitxt",size:24});async function O_({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Tp(1),experimental_output:f,output:p=f,experimental_telemetry:h,providerOptions:m,experimental_activeTools:_,activeTools:g=_,experimental_prepareStep:w,prepareStep:v=w,experimental_repairToolCall:y,experimental_download:S,experimental_context:b,experimental_include:T,_internal:{generateId:x=lR}={},experimental_onStart:R,experimental_onStepStart:C,experimental_onToolCallStart:L,experimental_onToolCallFinish:O,onStepFinish:q,onFinish:z,...H}){const ee=Ll(e),re=v_(),X=bo(u),V=vp(l),ie=t_(l),D=ie!=null?new AbortController:void 0,E=M_(i,V!=null?AbortSignal.timeout(V):void 0,D?.signal),{maxRetries:U,retry:Z}=b_({maxRetries:a,abortSignal:E}),I=_p(H),M=Dn(c??{},`ai/${r_}`),B=h_({model:ee,telemetry:h,headers:M,settings:{...I,maxRetries:U}}),oe={provider:ee.provider,modelId:ee.modelId},ne=await p_({system:n,prompt:o,messages:s}),be=re(h?.integrations);await Fr({event:{model:oe,system:n,prompt:o,messages:s,tools:t,toolChoice:r,activeTools:g,maxOutputTokens:I.maxOutputTokens,temperature:I.temperature,topP:I.topP,topK:I.topK,presencePenalty:I.presencePenalty,frequencyPenalty:I.frequencyPenalty,stopSequences:I.stopSequences,seed:I.seed,maxRetries:U,timeout:l,headers:c,providerOptions:m,stopWhen:u,output:p,abortSignal:i,include:T,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b},callbacks:[R,be.onStart]});const W=m_(h);try{return await Ta({name:"ai.generateText",attributes:Er({telemetry:h,attributes:{...ka({operationId:"ai.generateText",telemetry:h}),...B,"ai.model.provider":ee.provider,"ai.model.id":ee.modelId,"ai.prompt":{input:()=>JSON.stringify({system:n,prompt:o,messages:s})}}}),tracer:W,fn:async A=>{var F,J,Q,he,Pe,Ke,it,gt,ae,rt,_e,ue,Ie,ce,te,Ce,$,Y,Fe,Ae;const ft=ne.messages,It=[],{approvedToolApprovals:er,deniedToolApprovals:yr}=k_({messages:ft}),vr=er.filter(St=>!St.toolCall.providerExecuted);if(yr.length>0||vr.length>0){const St=await N_({toolCalls:vr.map(Ze=>Ze.toolCall),tools:t,tracer:W,telemetry:h,messages:ft,abortSignal:E,experimental_context:b,stepNumber:0,model:oe,onToolCallStart:[L,be.onToolCallStart],onToolCallFinish:[O,be.onToolCallFinish]}),Bt=[];for(const Ze of St){const cr=await wa({toolCallId:Ze.toolCallId,input:Ze.input,tool:t?.[Ze.toolName],output:Ze.type==="tool-result"?Ze.output:Ze.error,errorMode:Ze.type==="tool-error"?"text":"none"});Bt.push({type:"tool-result",toolCallId:Ze.toolCallId,toolName:Ze.toolName,output:cr})}for(const Ze of yr)Bt.push({type:"tool-result",toolCallId:Ze.toolCall.toolCallId,toolName:Ze.toolCall.toolName,output:{type:"execution-denied",reason:Ze.approvalResponse.reason,...Ze.toolCall.providerExecuted&&{providerOptions:{openai:{approvalId:Ze.approvalResponse.approvalId}}}}});It.push({role:"tool",content:Bt})}const de=[...er,...yr].filter(St=>St.toolCall.providerExecuted);de.length>0&&It.push({role:"tool",content:de.map(St=>({type:"tool-approval-response",approvalId:St.approvalResponse.approvalId,approved:St.approvalResponse.approved,reason:St.approvalResponse.reason,providerExecuted:!0}))});const nt=_p(H);let Je,kt=[],De=[];const We=[],Zn=new Map;do{const St=ie!=null?setTimeout(()=>D.abort(),ie):void 0;try{const Bt=[...ft,...It],Ze=await v?.({model:ee,steps:We,stepNumber:We.length,messages:Bt,experimental_context:b}),cr=Ll((F=Ze?.model)!=null?F:ee),Fn={provider:cr.provider,modelId:cr.modelId},Sn=await s_({prompt:{system:(J=Ze?.system)!=null?J:ne.system,messages:(Q=Ze?.messages)!=null?Q:Bt},supportedUrls:await cr.supportedUrls,download:S});b=(he=Ze?.experimental_context)!=null?he:b;const uc=(Pe=Ze?.activeTools)!=null?Pe:g,{toolChoice:xo,tools:ds}=await l_({tools:t,toolChoice:(Ke=Ze?.toolChoice)!=null?Ke:r,activeTools:uc}),Vn=(it=Ze?.messages)!=null?it:Bt,$t=(gt=Ze?.system)!=null?gt:ne.system,Jr=Ul(m,Ze?.providerOptions);await Fr({event:{stepNumber:We.length,model:Fn,system:$t,messages:Vn,tools:t,toolChoice:xo,activeTools:uc,steps:[...We],providerOptions:Jr,timeout:l,headers:c,stopWhen:u,output:p,abortSignal:i,include:T,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b},callbacks:[C,be.onStepStart]}),Je=await Z(()=>{var Ve;return Ta({name:"ai.generateText.doGenerate",attributes:Er({telemetry:h,attributes:{...ka({operationId:"ai.generateText.doGenerate",telemetry:h}),...B,"ai.model.provider":cr.provider,"ai.model.id":cr.modelId,"ai.prompt.messages":{input:()=>y_(Sn)},"ai.prompt.tools":{input:()=>ds?.map(Jt=>JSON.stringify(Jt))},"ai.prompt.toolChoice":{input:()=>xo!=null?JSON.stringify(xo):void 0},"gen_ai.system":cr.provider,"gen_ai.request.model":cr.modelId,"gen_ai.request.frequency_penalty":H.frequencyPenalty,"gen_ai.request.max_tokens":H.maxOutputTokens,"gen_ai.request.presence_penalty":H.presencePenalty,"gen_ai.request.stop_sequences":H.stopSequences,"gen_ai.request.temperature":(Ve=H.temperature)!=null?Ve:void 0,"gen_ai.request.top_k":H.topK,"gen_ai.request.top_p":H.topP}}),tracer:W,fn:async Jt=>{var $o,_r,La,pc,fc,Bn,Jn,fs;const dt=await cr.doGenerate({...nt,tools:ds,toolChoice:xo,responseFormat:await p?.responseFormat,prompt:Sn,providerOptions:Jr,abortSignal:E,headers:M}),wr={id:(_r=($o=dt.response)==null?void 0:$o.id)!=null?_r:x(),timestamp:(pc=(La=dt.response)==null?void 0:La.timestamp)!=null?pc:new Date,modelId:(Bn=(fc=dt.response)==null?void 0:fc.modelId)!=null?Bn:cr.modelId,headers:(Jn=dt.response)==null?void 0:Jn.headers,body:(fs=dt.response)==null?void 0:fs.body},Da=wp(dt.usage);return Jt.setAttributes(await Er({telemetry:h,attributes:{"ai.response.finishReason":dt.finishReason.unified,"ai.response.text":{output:()=>S_(dt.content)},"ai.response.reasoning":{output:()=>T_(dt.content)},"ai.response.toolCalls":{output:()=>{const Pt=A_(dt.content);return Pt==null?void 0:JSON.stringify(Pt)}},"ai.response.id":wr.id,"ai.response.model":wr.modelId,"ai.response.timestamp":wr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(dt.providerMetadata),"ai.usage.inputTokens":dt.usage.inputTokens.total,"ai.usage.inputTokenDetails.noCacheTokens":dt.usage.inputTokens.noCache,"ai.usage.inputTokenDetails.cacheReadTokens":dt.usage.inputTokens.cacheRead,"ai.usage.inputTokenDetails.cacheWriteTokens":dt.usage.inputTokens.cacheWrite,"ai.usage.outputTokens":dt.usage.outputTokens.total,"ai.usage.outputTokenDetails.textTokens":dt.usage.outputTokens.text,"ai.usage.outputTokenDetails.reasoningTokens":dt.usage.outputTokens.reasoning,"ai.usage.totalTokens":Da.totalTokens,"ai.usage.reasoningTokens":dt.usage.outputTokens.reasoning,"ai.usage.cachedInputTokens":dt.usage.inputTokens.cacheRead,"gen_ai.response.finish_reasons":[dt.finishReason.unified],"gen_ai.response.id":wr.id,"gen_ai.response.model":wr.modelId,"gen_ai.usage.input_tokens":dt.usage.inputTokens.total,"gen_ai.usage.output_tokens":dt.usage.outputTokens.total}})),{...dt,response:wr}}})});const Hn=await Promise.all(Je.content.filter(Ve=>Ve.type==="tool-call").map(Ve=>I_({toolCall:Ve,tools:t,repairToolCall:y,system:n,messages:Bt}))),ps={};for(const Ve of Hn){if(Ve.invalid)continue;const Jt=t?.[Ve.toolName];Jt!=null&&(Jt?.onInputAvailable!=null&&await Jt.onInputAvailable({input:Ve.input,toolCallId:Ve.toolCallId,messages:Bt,abortSignal:E,experimental_context:b}),await x_({tool:Jt,toolCall:Ve,messages:Bt,experimental_context:b})&&(ps[Ve.toolCallId]={type:"tool-approval-request",approvalId:x(),toolCall:Ve}))}const dc=Hn.filter(Ve=>Ve.invalid&&Ve.dynamic);De=[];for(const Ve of dc)De.push({type:"tool-error",toolCallId:Ve.toolCallId,toolName:Ve.toolName,input:Ve.input,error:Hd(Ve.error),dynamic:!0});kt=Hn.filter(Ve=>!Ve.providerExecuted),t!=null&&De.push(...await N_({toolCalls:kt.filter(Ve=>!Ve.invalid&&ps[Ve.toolCallId]==null),tools:t,tracer:W,telemetry:h,messages:Bt,abortSignal:E,experimental_context:b,stepNumber:We.length,model:Fn,onToolCallStart:[L,be.onToolCallStart],onToolCallFinish:[O,be.onToolCallFinish]}));for(const Ve of Hn){if(!Ve.providerExecuted)continue;const Jt=t?.[Ve.toolName];Jt?.type==="provider"&&Jt.supportsDeferredResults&&(Je.content.some(_r=>_r.type==="tool-result"&&_r.toolCallId===Ve.toolCallId)||Zn.set(Ve.toolCallId,{toolName:Ve.toolName}))}for(const Ve of Je.content)Ve.type==="tool-result"&&Zn.delete(Ve.toolCallId);const Io=uR({content:Je.content,toolCalls:Hn,toolOutputs:De,toolApprovalRequests:Object.values(ps),tools:t});It.push(...await Sp({content:Io,tools:t}));const qa=(ae=T?.requestBody)==null||ae?(rt=Je.request)!=null?rt:{}:{...Je.request,body:void 0},Kp={...Je.response,messages:structuredClone(It),body:(_e=T?.responseBody)==null||_e?(ue=Je.response)==null?void 0:ue.body:void 0},Yp=We.length,ja=new R_({stepNumber:Yp,model:Fn,functionId:h?.functionId,metadata:h?.metadata,experimental_context:b,content:Io,finishReason:Je.finishReason.unified,rawFinishReason:Je.finishReason.raw,usage:wp(Je.usage),warnings:Je.warnings,providerMetadata:Je.providerMetadata,request:qa,response:Kp});yp({warnings:(Ie=Je.warnings)!=null?Ie:[],provider:Fn.provider,model:Fn.modelId}),We.push(ja),await Fr({event:ja,callbacks:[q,be.onStepFinish]})}finally{St!=null&&clearTimeout(St)}}while((kt.length>0&&De.length===kt.length||Zn.size>0)&&!await P_({stopConditions:X,steps:We}));A.setAttributes(await Er({telemetry:h,attributes:{"ai.response.finishReason":Je.finishReason.unified,"ai.response.text":{output:()=>S_(Je.content)},"ai.response.reasoning":{output:()=>T_(Je.content)},"ai.response.toolCalls":{output:()=>{const St=A_(Je.content);return St==null?void 0:JSON.stringify(St)}},"ai.response.providerMetadata":JSON.stringify(Je.providerMetadata)}}));const qe=We[We.length-1],ut=We.reduce((St,Bt)=>__(St,Bt.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0});A.setAttributes(await Er({telemetry:h,attributes:{"ai.usage.inputTokens":ut.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ce=ut.inputTokenDetails)==null?void 0:ce.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(te=ut.inputTokenDetails)==null?void 0:te.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Ce=ut.inputTokenDetails)==null?void 0:Ce.cacheWriteTokens,"ai.usage.outputTokens":ut.outputTokens,"ai.usage.outputTokenDetails.textTokens":($=ut.outputTokenDetails)==null?void 0:$.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Y=ut.outputTokenDetails)==null?void 0:Y.reasoningTokens,"ai.usage.totalTokens":ut.totalTokens,"ai.usage.reasoningTokens":(Fe=ut.outputTokenDetails)==null?void 0:Fe.reasoningTokens,"ai.usage.cachedInputTokens":(Ae=ut.inputTokenDetails)==null?void 0:Ae.cacheReadTokens}})),await Fr({event:{stepNumber:qe.stepNumber,model:qe.model,functionId:qe.functionId,metadata:qe.metadata,experimental_context:qe.experimental_context,finishReason:qe.finishReason,rawFinishReason:qe.rawFinishReason,usage:qe.usage,content:qe.content,text:qe.text,reasoningText:qe.reasoningText,reasoning:qe.reasoning,files:qe.files,sources:qe.sources,toolCalls:qe.toolCalls,staticToolCalls:qe.staticToolCalls,dynamicToolCalls:qe.dynamicToolCalls,toolResults:qe.toolResults,staticToolResults:qe.staticToolResults,dynamicToolResults:qe.dynamicToolResults,request:qe.request,response:qe.response,warnings:qe.warnings,providerMetadata:qe.providerMetadata,steps:We,totalUsage:ut},callbacks:[z,be.onFinish]});let Tt;return qe.finishReason==="stop"&&(Tt=await(p??Zl()).parseCompleteOutput({text:qe.text},{response:qe.response,usage:qe.usage,finishReason:qe.finishReason})),new cR({steps:We,totalUsage:ut,output:Tt})}})}catch(A){throw f_(A)}}async function N_({toolCalls:e,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u}){return(await Promise.all(e.map(async p=>kp({toolCall:p,tools:t,tracer:r,telemetry:n,messages:o,abortSignal:s,experimental_context:a,stepNumber:i,model:l,onToolCallStart:c,onToolCallFinish:u})))).filter(p=>p!=null)}var cR=class{constructor(e){this.steps=e.steps,this._output=e.output,this.totalUsage=e.totalUsage}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get rawFinishReason(){return this.finalStep.rawFinishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get experimental_output(){return this.output}get output(){if(this._output==null)throw new Av;return this._output}};function A_(e){const t=e.filter(r=>r.type==="tool-call");if(t.length!==0)return t.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function uR({content:e,toolCalls:t,toolOutputs:r,toolApprovalRequests:n,tools:o}){const s=[];for(const a of e)switch(a.type){case"text":case"reasoning":case"source":s.push(a);break;case"file":{s.push({type:"file",file:new C_(a),...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-call":{s.push(t.find(i=>i.toolCallId===a.toolCallId));break}case"tool-result":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null){const l=o?.[a.toolName];if(!(l?.type==="provider"&&l.supportsDeferredResults))throw new Error(`Tool call ${a.toolCallId} not found.`);a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,error:a.result,providerExecuted:!0,dynamic:a.dynamic,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:void 0,output:a.result,providerExecuted:!0,dynamic:a.dynamic,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}a.isError?s.push({type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,error:a.result,providerExecuted:!0,dynamic:i.dynamic,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}}):s.push({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:i.input,output:a.result,providerExecuted:!0,dynamic:i.dynamic,...a.providerMetadata!=null?{providerMetadata:a.providerMetadata}:{}});break}case"tool-approval-request":{const i=t.find(l=>l.toolCallId===a.toolCallId);if(i==null)throw new mp({toolCallId:a.toolCallId,approvalId:a.approvalId});s.push({type:"tool-approval-request",approvalId:a.approvalId,toolCall:i});break}}return[...s,...r,...n]}function Fl(e,t){const r=new Headers(e??{});for(const[n,o]of Object.entries(t))r.has(n)||r.set(n,o);return r}function dR({status:e,statusText:t,headers:r,textStream:n}){return new Response(n.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Fl(r,{"content-type":"text/plain; charset=utf-8"})})}function q_({response:e,status:t,statusText:r,headers:n,stream:o}){const s=t??200;r!==void 0?e.writeHead(s,r,n):e.writeHead(s,n);const a=o.getReader();(async()=>{try{for(;;){const{done:l,value:c}=await a.read();if(l)break;e.write(c)||await new Promise(f=>{e.once("drain",f)})}}catch(l){throw l}finally{e.end()}})()}function pR({response:e,status:t,statusText:r,headers:n,textStream:o}){q_({response:e,status:t,statusText:r,headers:Object.fromEntries(Fl(n,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:o.pipeThrough(new TextEncoderStream)})}var j_=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
581
581
 
582
582
  `)},flush(e){e.enqueue(`data: [DONE]
583
583
 
584
- `)}})}},q_={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function n7({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new A_);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:jl(r,q_)})}function o7({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function s7(e){return e.type.startsWith("data-")}function wp(e){return e.type.startsWith("tool-")}function a7(e){return e.type==="dynamic-tool"}function L_(e){return wp(e)||a7(e)}function j_(e){return e.type.split("-").slice(1).join("-")}function i7({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function l7({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var f,p,h,m;function _(g){const b=c.message.parts.filter(L_).find(k=>k.toolCallId===g);if(b==null)throw new Xo({chunkType:"tool-invocation",chunkId:g,message:`No tool invocation found for tool call ID "${g}".`});return b}function y(g){var S;const b=c.message.parts.find(R=>wp(R)&&R.toolCallId===g.toolCallId),k=g,C=b;if(b!=null){b.state=g.state,C.input=k.input,C.output=k.output,C.errorText=k.errorText,C.rawInput=k.rawInput,C.preliminary=k.preliminary,g.title!==void 0&&(C.title=g.title),C.providerExecuted=(S=k.providerExecuted)!=null?S:b.providerExecuted;const R=k.providerMetadata;if(R!=null)if(g.state==="output-available"||g.state==="output-error"){const I=b;I.resultProviderMetadata=R}else b.callProviderMetadata=R}else c.message.parts.push({type:`tool-${g.toolName}`,toolCallId:g.toolCallId,state:g.state,title:g.title,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null&&(g.state==="output-available"||g.state==="output-error")?{resultProviderMetadata:k.providerMetadata}:{},...k.providerMetadata!=null&&!(g.state==="output-available"||g.state==="output-error")?{callProviderMetadata:k.providerMetadata}:{}})}function w(g){var S,b;const k=c.message.parts.find(I=>I.type==="dynamic-tool"&&I.toolCallId===g.toolCallId),C=g,R=k;if(k!=null){k.state=g.state,R.toolName=g.toolName,R.input=C.input,R.output=C.output,R.errorText=C.errorText,R.rawInput=(S=C.rawInput)!=null?S:R.rawInput,R.preliminary=C.preliminary,g.title!==void 0&&(R.title=g.title),R.providerExecuted=(b=C.providerExecuted)!=null?b:k.providerExecuted;const I=C.providerMetadata;if(I!=null)if(g.state==="output-available"||g.state==="output-error"){const j=k;j.resultProviderMetadata=I}else k.callProviderMetadata=I}else c.message.parts.push({type:"dynamic-tool",toolName:g.toolName,toolCallId:g.toolCallId,state:g.state,input:C.input,output:C.output,errorText:C.errorText,preliminary:C.preliminary,providerExecuted:C.providerExecuted,title:g.title,...C.providerMetadata!=null&&(g.state==="output-available"||g.state==="output-error")?{resultProviderMetadata:C.providerMetadata}:{},...C.providerMetadata!=null&&!(g.state==="output-available"||g.state==="output-error")?{callProviderMetadata:C.providerMetadata}:{}})}async function v(g){if(g!=null){const S=c.message.metadata!=null?Al(c.message.metadata,g):g;t!=null&&await _t({value:S,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=S}}switch(i.type){case"text-start":{const g={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=g,c.message.parts.push(g),u();break}case"text-delta":{const g=c.activeTextParts[i.id];if(g==null)throw new Xo({chunkType:"text-delta",chunkId:i.id,message:`Received text-delta for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});g.text+=i.delta,g.providerMetadata=(f=i.providerMetadata)!=null?f:g.providerMetadata,u();break}case"text-end":{const g=c.activeTextParts[i.id];if(g==null)throw new Xo({chunkType:"text-end",chunkId:i.id,message:`Received text-end for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});g.state="done",g.providerMetadata=(p=i.providerMetadata)!=null?p:g.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const g={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=g,c.message.parts.push(g),u();break}case"reasoning-delta":{const g=c.activeReasoningParts[i.id];if(g==null)throw new Xo({chunkType:"reasoning-delta",chunkId:i.id,message:`Received reasoning-delta for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});g.text+=i.delta,g.providerMetadata=(h=i.providerMetadata)!=null?h:g.providerMetadata,u();break}case"reasoning-end":{const g=c.activeReasoningParts[i.id];if(g==null)throw new Xo({chunkType:"reasoning-end",chunkId:i.id,message:`Received reasoning-end for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});g.providerMetadata=(m=i.providerMetadata)!=null?m:g.providerMetadata,g.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}}),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 g=c.message.parts.filter(wp);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:g.length,dynamic:i.dynamic,title:i.title},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"tool-input-delta":{const g=c.partialToolCalls[i.toolCallId];if(g==null)throw new Xo({chunkType:"tool-input-delta",chunkId:i.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${i.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});g.text+=i.inputTextDelta;const{value:S}=await _a(g.text);g.dynamic?w({toolCallId:i.toolCallId,toolName:g.toolName,state:"input-streaming",input:S,title:g.title}):y({toolCallId:i.toolCallId,toolName:g.toolName,state:"input-streaming",input:S,title:g.title}),u();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{const g=c.message.parts.filter(L_).find(b=>b.toolCallId===i.toolCallId);(g!=null?g.type==="dynamic-tool":!!i.dynamic)?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-approval-request":{const g=_(i.toolCallId);g.state="approval-requested",g.approval={id:i.approvalId},u();break}case"tool-output-denied":{const g=_(i.toolCallId);g.state="output-denied",u();break}case"tool-output-available":{const g=_(i.toolCallId);g.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:g.toolName,state:"output-available",input:g.input,output:i.output,preliminary:i.preliminary,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:g.title}):y({toolCallId:i.toolCallId,toolName:j_(g),state:"output-available",input:g.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary,providerMetadata:i.providerMetadata,title:g.title}),u();break}case"tool-output-error":{const g=_(i.toolCallId);g.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:g.toolName,state:"output-error",input:g.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:g.title}):y({toolCallId:i.toolCallId,toolName:j_(g),state:"output-error",input:g.input,rawInput:g.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:g.title}),u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await v(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await v(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await v(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(s7(i)){if(r?.[i.type]!=null){const b=c.message.parts.findIndex(C=>"id"in C&&"data"in C&&C.id===i.id&&C.type===i.type),k=b>=0?b:c.message.parts.length;await _t({value:i.data,schema:r[i.type],context:{field:`message.parts[${k}].data`,entityName:i.type,entityId:i.id}})}const g=i;if(g.transient){a?.(g);break}const S=g.id!=null?c.message.parts.find(b=>g.type===b.type&&g.id===b.id):void 0;S!=null?S.data=g.data:c.message.parts.push(g),a?.(g),u()}}l.enqueue(i)})}}))}function c7({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:s}){let a=t?.[t.length-1];a?.role!=="assistant"?a=void 0:e=a.id;let i=!1;const l=s.pipeThrough(new TransformStream({transform(m,_){if(m.type==="start"){const y=m;y.messageId==null&&e!=null&&(y.messageId=e)}m.type==="abort"&&(i=!0),_.enqueue(m)}}));if(n==null&&r==null)return l;const c=i7({lastMessage:a?structuredClone(a):void 0,messageId:e??""}),u=async m=>{await m({state:c,write:()=>{}})};let f=!1;const p=async()=>{if(f||!n)return;f=!0;const m=c.message.id===a?.id;await n({isAborted:i,isContinuation:m,responseMessage:c.message,messages:[...m?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},h=async()=>{if(!r)return;const m=c.message.id===a?.id;try{await r({isContinuation:m,responseMessage:structuredClone(c.message),messages:[...m?t.slice(0,-1):t,structuredClone(c.message)]})}catch(_){o(_)}};return l7({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(m,_){m.type==="finish-step"&&await h(),_.enqueue(m)},async cancel(){await p()},async flush(){await p()}}))}function u7({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new A_);if(s){const[i,l]=a.tee();a=i,s({stream:l})}O_({response:e,status:t,statusText:r,headers:Object.fromEntries(jl(n,q_).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function wa(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(s){var a;if(!n){n=!0;try{s&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:s,value:a}=await r.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function d7({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function D_(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function p7(){let e=[],t=null,r=!1,n=D_();const o=()=>{r=!0,n.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},s=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=D_(),await n.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length===0&&r?t?.close():await s()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),o()}};return{stream:new ReadableStream({start(a){t=a},pull:s,async cancel(){for(const a of e)await a.cancel();e=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function f7({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l,generateId:c,stepNumber:u,model:f,onToolCallStart:p,onToolCallFinish:h}){let m=null;const _=new ReadableStream({start(C){m=C}}),y=new Set,w=new Map,v=new Map;let g=!1,S;function b(){g&&y.size===0&&(S!=null&&m.enqueue(S),m.close())}const k=new TransformStream({async transform(C,R){const I=C.type;switch(I){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{R.enqueue(C);break}case"file":{R.enqueue({type:"file",file:new H$({data:C.data,mediaType:C.mediaType}),...C.providerMetadata!=null?{providerMetadata:C.providerMetadata}:{}});break}case"finish":{S={type:"finish",finishReason:C.finishReason.unified,rawFinishReason:C.finishReason.raw,usage:mp(C.usage),providerMetadata:C.providerMetadata};break}case"tool-approval-request":{const j=v.get(C.toolCallId);if(j==null){m.enqueue({type:"error",error:new up({toolCallId:C.toolCallId,approvalId:C.approvalId})});break}R.enqueue({type:"tool-approval-request",approvalId:C.approvalId,toolCall:j});break}case"tool-call":{try{const j=await C_({toolCall:C,tools:e,repairToolCall:i,system:o,messages:s});if(v.set(j.toolCallId,j),R.enqueue(j),j.invalid){m.enqueue({type:"tool-error",toolCallId:j.toolCallId,toolName:j.toolName,input:j.input,error:zd(j.error),dynamic:!0,title:j.title});break}const N=e?.[j.toolName];if(N==null)break;if(N.onInputAvailable!=null&&await N.onInputAvailable({input:j.input,toolCallId:j.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await S_({tool:N,toolCall:j,messages:s,experimental_context:l})){m.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:j});break}if(w.set(j.toolCallId,j.input),N.execute!=null&&j.providerExecuted!==!0){const L=c();y.add(L),yp({toolCall:j,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:a,experimental_context:l,stepNumber:u,model:f,onToolCallStart:p,onToolCallFinish:h,onPreliminaryToolResult:z=>{m.enqueue(z)}}).then(z=>{m.enqueue(z)}).catch(z=>{m.enqueue({type:"error",error:z})}).finally(()=>{y.delete(L),b()})}}catch(j){m.enqueue({type:"error",error:j})}break}case"tool-result":{const j=C.toolName;C.isError?m.enqueue({type:"tool-error",toolCallId:C.toolCallId,toolName:j,input:w.get(C.toolCallId),providerExecuted:!0,error:C.result,dynamic:C.dynamic,...C.providerMetadata!=null?{providerMetadata:C.providerMetadata}:{}}):R.enqueue({type:"tool-result",toolCallId:C.toolCallId,toolName:j,input:w.get(C.toolCallId),output:C.result,providerExecuted:!0,dynamic:C.dynamic,...C.providerMetadata!=null?{providerMetadata:C.providerMetadata}:{}});break}default:{const j=I;throw new Error(`Unhandled chunk type: ${j}`)}}},flush(){g=!0,b()}});return new ReadableStream({async start(C){return Promise.all([t.pipeThrough(k).pipeTo(new WritableStream({write(R){C.enqueue(R)},close(){}})),_.pipeTo(new WritableStream({write(R){C.enqueue(R)},close(){C.close()}}))])}})}var h7=ia({prefix:"aitxt",size:24});function bp({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=vp(1),experimental_output:f,output:p=f,experimental_telemetry:h,prepareStep:m,providerOptions:_,experimental_activeTools:y,activeTools:w=y,experimental_repairToolCall:v,experimental_transform:g,experimental_download:S,includeRawChunks:b=!1,onChunk:k,onError:C=({error:D})=>{console.error(D)},onFinish:R,onAbort:I,onStepFinish:j,experimental_onStart:N,experimental_onStepStart:L,experimental_onToolCallStart:z,experimental_onToolCallFinish:H,experimental_context:ee,experimental_include:te,_internal:{now:X=ql,generateId:V=h7}={},...se}){const D=fp(l),E=Xv(l),U=g$(l),Z=E!=null?new AbortController:void 0,x=U!=null?new AbortController:void 0;return new g7({model:Nl(e),telemetry:h,headers:c,settings:se,maxRetries:a,abortSignal:R_(i,D!=null?AbortSignal.timeout(D):void 0,Z?.signal,x?.signal),stepTimeoutMs:E,stepAbortController:Z,chunkTimeoutMs:U,chunkAbortController:x,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:go(g),activeTools:w,repairToolCall:v,stopConditions:go(u),output:p,providerOptions:_,prepareStep:m,includeRawChunks:b,timeout:l,stopWhen:u,originalAbortSignal:i,onChunk:k,onError:C,onFinish:R,onAbort:I,onStepFinish:j,onStart:N,onStepStart:L,onToolCallStart:z,onToolCallFinish:H,now:X,generateId:V,experimental_context:ee,download:S,include:te})}function m7(e){let t,r="",n="",o,s="";function a({controller:i,partialOutput:l=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(i,l){var c;if(i.type==="finish-step"&&n.length>0&&a({controller:l}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){l.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){n.length>0&&a({controller:l}),l.enqueue({part:i,partialOutput:void 0});return}r+=i.text,n+=i.text,o=(c=i.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const f=JSON.stringify(u.partial);f!==s&&(a({controller:l,partialOutput:u.partial}),s=f)}}})}var g7=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:a,stepAbortController:i,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:f,messages:p,tools:h,toolChoice:m,transforms:_,activeTools:y,repairToolCall:w,stopConditions:v,output:g,providerOptions:S,prepareStep:b,includeRawChunks:k,now:C,generateId:R,timeout:I,stopWhen:j,originalAbortSignal:N,onChunk:L,onError:z,onFinish:H,onAbort:ee,onStepFinish:te,onStart:X,onStepStart:V,onToolCallStart:se,onToolCallFinish:D,experimental_context:E,download:U,include:Z}){this._totalUsage=new aa,this._finishReason=new aa,this._rawFinishReason=new aa,this._steps=new aa,this.outputSpecification=g,this.includeRawChunks=k,this.tools=h;const M=g_()(t?.integrations);let W,oe=[];const ne=[];let we,K,A,F={},G=[];const Q=[],pe=new Map;let Ie,Ge={},dt={};const wt=new TransformStream({async transform($e,lt){var kt,Yt,gr,yr;lt.enqueue($e);const{part:ie}=$e;if((ie.type==="text-delta"||ie.type==="reasoning-delta"||ie.type==="source"||ie.type==="tool-call"||ie.type==="tool-result"||ie.type==="tool-input-start"||ie.type==="tool-input-delta"||ie.type==="raw")&&await L?.({chunk:ie}),ie.type==="error"&&await z({error:d_(ie.error)}),ie.type==="text-start"&&(Ge[ie.id]={type:"text",text:"",providerMetadata:ie.providerMetadata},oe.push(Ge[ie.id])),ie.type==="text-delta"){const Je=Ge[ie.id];if(Je==null){lt.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}Je.text+=ie.text,Je.providerMetadata=(kt=ie.providerMetadata)!=null?kt:Je.providerMetadata}if(ie.type==="text-end"){const Je=Ge[ie.id];if(Je==null){lt.enqueue({part:{type:"error",error:`text part ${ie.id} not found`},partialOutput:void 0});return}Je.providerMetadata=(Yt=ie.providerMetadata)!=null?Yt:Je.providerMetadata,delete Ge[ie.id]}if(ie.type==="reasoning-start"&&(dt[ie.id]={type:"reasoning",text:"",providerMetadata:ie.providerMetadata},oe.push(dt[ie.id])),ie.type==="reasoning-delta"){const Je=dt[ie.id];if(Je==null){lt.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}Je.text+=ie.text,Je.providerMetadata=(gr=ie.providerMetadata)!=null?gr:Je.providerMetadata}if(ie.type==="reasoning-end"){const Je=dt[ie.id];if(Je==null){lt.enqueue({part:{type:"error",error:`reasoning part ${ie.id} not found`},partialOutput:void 0});return}Je.providerMetadata=(yr=ie.providerMetadata)!=null?yr:Je.providerMetadata,delete dt[ie.id]}if(ie.type==="file"&&oe.push({type:"file",file:ie.file,...ie.providerMetadata!=null?{providerMetadata:ie.providerMetadata}:{}}),ie.type==="source"&&oe.push(ie),ie.type==="tool-call"&&oe.push(ie),ie.type==="tool-result"&&!ie.preliminary&&oe.push(ie),ie.type==="tool-approval-request"&&oe.push(ie),ie.type==="tool-error"&&oe.push(ie),ie.type==="start-step"&&(oe=[],dt={},Ge={},F=ie.request,G=ie.warnings),ie.type==="finish-step"){const Je=await _p({content:oe,tools:h}),Ue=new E_({stepNumber:Q.length,model:Y,...je,experimental_context:E,content:oe,finishReason:ie.finishReason,rawFinishReason:ie.rawFinishReason,usage:ie.usage,warnings:G,request:F,response:{...ie.response,messages:[...ne,...Je]},providerMetadata:ie.providerMetadata});await Fr({event:Ue,callbacks:[te,M.onStepFinish]}),pp({warnings:G,provider:Y.provider,model:Y.modelId}),Q.push(Ue),ne.push(...Je),W.resolve()}ie.type==="finish"&&(A=ie.totalUsage,we=ie.finishReason,K=ie.rawFinishReason)},async flush($e){var lt,kt,Yt,gr,yr,ie,Je;try{if(Q.length===0){const ze=s?.aborted?s.reason:new Nv({message:"No output generated. Check the stream for errors."});$._finishReason.reject(ze),$._rawFinishReason.reject(ze),$._totalUsage.reject(ze),$._steps.reject(ze);return}const Ue=we??"other",gt=A??gp();$._finishReason.resolve(Ue),$._rawFinishReason.resolve(K),$._totalUsage.resolve(gt),$._steps.resolve(Q);const Me=Q[Q.length-1];await Fr({event:{stepNumber:Me.stepNumber,model:Me.model,functionId:Me.functionId,metadata:Me.metadata,experimental_context:Me.experimental_context,finishReason:Me.finishReason,rawFinishReason:Me.rawFinishReason,totalUsage:gt,usage:Me.usage,content:Me.content,text:Me.text,reasoningText:Me.reasoningText,reasoning:Me.reasoning,files:Me.files,sources:Me.sources,toolCalls:Me.toolCalls,staticToolCalls:Me.staticToolCalls,dynamicToolCalls:Me.dynamicToolCalls,toolResults:Me.toolResults,staticToolResults:Me.staticToolResults,dynamicToolResults:Me.dynamicToolResults,request:Me.request,response:Me.response,warnings:Me.warnings,providerMetadata:Me.providerMetadata,steps:Q},callbacks:[H,M.onFinish]}),Ie.setAttributes(await Er({telemetry:t,attributes:{"ai.response.finishReason":Ue,"ai.response.text":{output:()=>Me.text},"ai.response.reasoning":{output:()=>Me.reasoningText},"ai.response.toolCalls":{output:()=>{var ze;return(ze=Me.toolCalls)!=null&&ze.length?JSON.stringify(Me.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Me.providerMetadata),"ai.usage.inputTokens":gt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(lt=gt.inputTokenDetails)==null?void 0:lt.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(kt=gt.inputTokenDetails)==null?void 0:kt.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(Yt=gt.inputTokenDetails)==null?void 0:Yt.cacheWriteTokens,"ai.usage.outputTokens":gt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(gr=gt.outputTokenDetails)==null?void 0:gr.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(yr=gt.outputTokenDetails)==null?void 0:yr.reasoningTokens,"ai.usage.totalTokens":gt.totalTokens,"ai.usage.reasoningTokens":(ie=gt.outputTokenDetails)==null?void 0:ie.reasoningTokens,"ai.usage.cachedInputTokens":(Je=gt.inputTokenDetails)==null?void 0:Je.cacheReadTokens}}))}catch(Ue){$e.error(Ue)}finally{Ie.end()}}}),st=p7();this.addStream=st.addStream,this.closeStream=st.close;const it=st.stream.getReader();let zt=new ReadableStream({async start($e){$e.enqueue({type:"start"})},async pull($e){function lt(){ee?.({steps:Q}),$e.enqueue({type:"abort",...s?.reason!==void 0?{reason:ao(s.reason)}:{}}),$e.close()}try{const{done:kt,value:Yt}=await it.read();if(kt){$e.close();return}if(s?.aborted){lt();return}$e.enqueue(Yt)}catch(kt){co(kt)&&s?.aborted?lt():$e.error(kt)}},cancel($e){return st.stream.cancel($e)}});for(const $e of _)zt=zt.pipeThrough($e({tools:h,stopStream(){st.terminate()}}));this.baseStream=zt.pipeThrough(m7(g??Ll())).pipeThrough(wt);const{maxRetries:bt,retry:Br}=__({maxRetries:o,abortSignal:s}),ar=f_(t),et=hp(n),$r=p_({model:e,telemetry:t,headers:r,settings:{...et,maxRetries:bt}}),$=this,Y={provider:e.provider,modelId:e.modelId},je={functionId:t?.functionId,metadata:t?.metadata};va({name:"ai.streamText",attributes:Er({telemetry:t,attributes:{...ya({operationId:"ai.streamText",telemetry:t}),...$r,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:f,messages:p})}}}),tracer:ar,endWhenDone:!1,fn:async $e=>{Ie=$e;const lt=await u_({system:u,prompt:f,messages:p});await Fr({event:{model:Y,system:u,prompt:f,messages:p,tools:h,toolChoice:m,activeTools:y,maxOutputTokens:et.maxOutputTokens,temperature:et.temperature,topP:et.topP,topK:et.topK,presencePenalty:et.presencePenalty,frequencyPenalty:et.frequencyPenalty,stopSequences:et.stopSequences,seed:et.seed,maxRetries:bt,timeout:I,headers:r,providerOptions:S,stopWhen:j,output:g,abortSignal:N,include:Z,...je,experimental_context:E},callbacks:[X,M.onStart]});const kt=lt.messages,Yt=[],{approvedToolApprovals:gr,deniedToolApprovals:yr}=w_({messages:kt});if(yr.length>0||gr.length>0){const Je=[...gr,...yr].filter(Ee=>Ee.toolCall.providerExecuted),Ue=gr.filter(Ee=>!Ee.toolCall.providerExecuted),gt=yr.filter(Ee=>!Ee.toolCall.providerExecuted),Me=yr.filter(Ee=>Ee.toolCall.providerExecuted);let ze;const jn=new ReadableStream({start(Ee){ze=Ee}});$.addStream(jn);try{for(const nt of[...gt,...Me])ze?.enqueue({type:"tool-output-denied",toolCallId:nt.toolCall.toolCallId,toolName:nt.toolCall.toolName});const Ee=[];if(await Promise.all(Ue.map(async nt=>{const yt=await yp({toolCall:nt.toolCall,tools:h,tracer:ar,telemetry:t,messages:kt,abortSignal:s,experimental_context:E,stepNumber:Q.length,model:Y,onToolCallStart:[se,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish],onPreliminaryToolResult:vt=>{ze?.enqueue(vt)}});yt!=null&&(ze?.enqueue(yt),Ee.push(yt))})),Je.length>0&&Yt.push({role:"tool",content:Je.map(nt=>({type:"tool-approval-response",approvalId:nt.approvalResponse.approvalId,approved:nt.approvalResponse.approved,reason:nt.approvalResponse.reason,providerExecuted:!0}))}),Ee.length>0||gt.length>0){const nt=[];for(const yt of Ee)nt.push({type:"tool-result",toolCallId:yt.toolCallId,toolName:yt.toolName,output:await ma({toolCallId:yt.toolCallId,input:yt.input,tool:h?.[yt.toolName],output:yt.type==="tool-result"?yt.output:yt.error,errorMode:yt.type==="tool-error"?"text":"none"})});for(const yt of gt)nt.push({type:"tool-result",toolCallId:yt.toolCall.toolCallId,toolName:yt.toolCall.toolName,output:{type:"execution-denied",reason:yt.approvalResponse.reason}});Yt.push({role:"tool",content:nt})}}finally{ze?.close()}}ne.push(...Yt);async function ie({currentStep:Je,responseMessages:Ue,usage:gt}){var Me,ze,jn,Ee,nt,yt,vt,Zt,Ae;const ir=$.includeRawChunks,Dn=a!=null?setTimeout(()=>i.abort(),a):void 0;let bn;function ac(){l!=null&&(bn!=null&&clearTimeout(bn),bn=setTimeout(()=>c.abort(),l))}function vo(){bn!=null&&(clearTimeout(bn),bn=void 0)}function as(){Dn!=null&&clearTimeout(Dn)}try{W=new aa;const Un=[...kt,...Ue],St=await b?.({model:e,steps:Q,stepNumber:Q.length,messages:Un,experimental_context:E}),Wr=Nl((Me=St?.model)!=null?Me:e),zn={provider:Wr.provider,modelId:Wr.modelId},is=await n_({prompt:{system:(ze=St?.system)!=null?ze:lt.system,messages:(jn=St?.messages)!=null?jn:Un},supportedUrls:await Wr.supportedUrls,download:U}),ic=(Ee=St?.activeTools)!=null?Ee:y,{toolChoice:_o,tools:Pa}=await a_({tools:h,toolChoice:(nt=St?.toolChoice)!=null?nt:m,activeTools:ic});E=(yt=St?.experimental_context)!=null?yt:E;const Wp=(vt=St?.messages)!=null?vt:Un,Gp=(Zt=St?.system)!=null?Zt:lt.system,Ma=Al(S,St?.providerOptions);await Fr({event:{stepNumber:Q.length,model:zn,system:Gp,messages:Wp,tools:h,toolChoice:_o,activeTools:ic,steps:[...Q],providerOptions:Ma,timeout:I,headers:r,stopWhen:j,output:g,abortSignal:N,include:Z,...je,experimental_context:E},callbacks:[V,M.onStepStart]});const{result:{stream:qe,response:Ft,request:wo},doStreamSpan:vr,startTimestampMs:Na}=await Br(()=>va({name:"ai.streamText.doStream",attributes:Er({telemetry:t,attributes:{...ya({operationId:"ai.streamText.doStream",telemetry:t}),...$r,"ai.model.provider":Wr.provider,"ai.model.id":Wr.modelId,"ai.prompt.messages":{input:()=>m_(is)},"ai.prompt.tools":{input:()=>Pa?.map(Se=>JSON.stringify(Se))},"ai.prompt.toolChoice":{input:()=>_o!=null?JSON.stringify(_o):void 0},"gen_ai.system":Wr.provider,"gen_ai.request.model":Wr.modelId,"gen_ai.request.frequency_penalty":et.frequencyPenalty,"gen_ai.request.max_tokens":et.maxOutputTokens,"gen_ai.request.presence_penalty":et.presencePenalty,"gen_ai.request.stop_sequences":et.stopSequences,"gen_ai.request.temperature":et.temperature,"gen_ai.request.top_k":et.topK,"gen_ai.request.top_p":et.topP}}),tracer:ar,endWhenDone:!1,fn:async Se=>({startTimestampMs:C(),doStreamSpan:Se,result:await Wr.doStream({...et,tools:Pa,toolChoice:_o,responseFormat:await g?.responseFormat,prompt:is,providerOptions:Ma,abortSignal:s,headers:r,includeRawChunks:ir})})})),lc=f7({tools:h,generatorStream:qe,tracer:ar,telemetry:t,system:u,messages:Un,repairToolCall:w,abortSignal:s,experimental_context:E,generateId:R,stepNumber:Q.length,model:zn,onToolCallStart:[se,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish]}),cc=(Ae=Z?.requestBody)==null||Ae?wo??{}:{...wo,body:void 0},Zn=[],Fn=[];let ls;const ot={};let _r="other",Oa,xt=gp(),Fw,Vw=!0,rn={id:R(),timestamp:new Date,modelId:Y.modelId},UN="";$.addStream(lc.pipeThrough(new TransformStream({async transform(Se,Pt){var Aa,qa,La,ja,Da;if(ac(),Se.type==="stream-start"){ls=Se.warnings;return}if(Vw){const Et=C()-Na;Vw=!1,vr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Et}),vr.setAttributes({"ai.response.msToFirstChunk":Et}),Pt.enqueue({type:"start-step",request:cc,warnings:ls??[]})}const Ua=Se.type;switch(Ua){case"tool-approval-request":case"text-start":case"text-end":{Pt.enqueue(Se);break}case"text-delta":{Se.delta.length>0&&(Pt.enqueue({type:"text-delta",id:Se.id,text:Se.delta,providerMetadata:Se.providerMetadata}),UN+=Se.delta);break}case"reasoning-start":case"reasoning-end":{Pt.enqueue(Se);break}case"reasoning-delta":{Pt.enqueue({type:"reasoning-delta",id:Se.id,text:Se.delta,providerMetadata:Se.providerMetadata});break}case"tool-call":{Pt.enqueue(Se),Zn.push(Se);break}case"tool-result":{Pt.enqueue(Se),Se.preliminary||Fn.push(Se);break}case"tool-error":{Pt.enqueue(Se),Fn.push(Se);break}case"response-metadata":{rn={id:(Aa=Se.id)!=null?Aa:rn.id,timestamp:(qa=Se.timestamp)!=null?qa:rn.timestamp,modelId:(La=Se.modelId)!=null?La:rn.modelId};break}case"finish":{xt=Se.usage,_r=Se.finishReason,Oa=Se.rawFinishReason,Fw=Se.providerMetadata;const Et=C()-Na;vr.addEvent("ai.stream.finish"),vr.setAttributes({"ai.response.msToFinish":Et,"ai.response.avgOutputTokensPerSecond":1e3*((ja=xt.outputTokens)!=null?ja:0)/Et});break}case"file":{Pt.enqueue(Se);break}case"source":{Pt.enqueue(Se);break}case"tool-input-start":{ot[Se.id]=Se.toolName;const Et=h?.[Se.toolName];Et?.onInputStart!=null&&await Et.onInputStart({toolCallId:Se.id,messages:Un,abortSignal:s,experimental_context:E}),Pt.enqueue({...Se,dynamic:(Da=Se.dynamic)!=null?Da:Et?.type==="dynamic",title:Et?.title});break}case"tool-input-end":{delete ot[Se.id],Pt.enqueue(Se);break}case"tool-input-delta":{const Et=ot[Se.id],cs=h?.[Et];cs?.onInputDelta!=null&&await cs.onInputDelta({inputTextDelta:Se.delta,toolCallId:Se.id,messages:Un,abortSignal:s,experimental_context:E}),Pt.enqueue(Se);break}case"error":{Pt.enqueue(Se),_r="error";break}case"raw":{ir&&Pt.enqueue(Se);break}default:{const Et=Ua;throw new Error(`Unknown chunk type: ${Et}`)}}},async flush(Se){var Pt,Aa,qa,La,ja,Da,Ua;const Et=Zn.length>0?JSON.stringify(Zn):void 0;try{vr.setAttributes(await Er({telemetry:t,attributes:{"ai.response.finishReason":_r,"ai.response.toolCalls":{output:()=>Et},"ai.response.id":rn.id,"ai.response.model":rn.modelId,"ai.response.timestamp":rn.timestamp.toISOString(),"ai.usage.inputTokens":xt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Pt=xt.inputTokenDetails)==null?void 0:Pt.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Aa=xt.inputTokenDetails)==null?void 0:Aa.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(qa=xt.inputTokenDetails)==null?void 0:qa.cacheWriteTokens,"ai.usage.outputTokens":xt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(La=xt.outputTokenDetails)==null?void 0:La.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(ja=xt.outputTokenDetails)==null?void 0:ja.reasoningTokens,"ai.usage.totalTokens":xt.totalTokens,"ai.usage.reasoningTokens":(Da=xt.outputTokenDetails)==null?void 0:Da.reasoningTokens,"ai.usage.cachedInputTokens":(Ua=xt.inputTokenDetails)==null?void 0:Ua.cacheReadTokens,"gen_ai.response.finish_reasons":[_r],"gen_ai.response.id":rn.id,"gen_ai.response.model":rn.modelId,"gen_ai.usage.input_tokens":xt.inputTokens,"gen_ai.usage.output_tokens":xt.outputTokens}}))}catch{}Se.enqueue({type:"finish-step",finishReason:_r,rawFinishReason:Oa,usage:xt,providerMetadata:Fw,response:{...rn,headers:Ft?.headers}});const cs=y_(gt,xt);await W.promise;const Jp=Q[Q.length-1];try{vr.setAttributes(await Er({telemetry:t,attributes:{"ai.response.text":{output:()=>Jp.text},"ai.response.reasoning":{output:()=>Jp.reasoningText},"ai.response.providerMetadata":JSON.stringify(Jp.providerMetadata)}}))}catch{}finally{vr.end()}const Hw=Zn.filter(Lt=>Lt.providerExecuted!==!0),zN=Fn.filter(Lt=>Lt.providerExecuted!==!0);for(const Lt of Zn){if(Lt.providerExecuted!==!0)continue;const Kp=h?.[Lt.toolName];Kp?.type==="provider"&&Kp.supportsDeferredResults&&(Fn.some(Yp=>(Yp.type==="tool-result"||Yp.type==="tool-error")&&Yp.toolCallId===Lt.toolCallId)||pe.set(Lt.toolCallId,{toolName:Lt.toolName}))}for(const Lt of Fn)(Lt.type==="tool-result"||Lt.type==="tool-error")&&pe.delete(Lt.toolCallId);if(as(),vo(),(Hw.length>0&&zN.length===Hw.length||pe.size>0)&&!await $_({stopConditions:v,steps:Q})){Ue.push(...await _p({content:Q[Q.length-1].content,tools:h}));try{await ie({currentStep:Je+1,responseMessages:Ue,usage:cs})}catch(Lt){Se.enqueue({type:"error",error:Lt}),$.closeStream()}}else Se.enqueue({type:"finish",finishReason:_r,rawFinishReason:Oa,totalUsage:cs}),$.closeStream()}})))}finally{as(),vo()}}await ie({currentStep:0,responseMessages:Yt,usage:gp()})}}).catch($e=>{$.addStream(new ReadableStream({start(lt){lt.enqueue({type:"error",error:$e}),lt.close()}})),$.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return wa(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return wa(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await d7({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return wa(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new Qr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return wa(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Ll()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=ao}={}){const c=t!=null?o7({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var h;const m=(h=this.tools)==null?void 0:h[p.toolName];return m==null?p.dynamic:m?.type==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,h)=>{const m=n?.({part:p}),_=p.type;switch(_){case"text-start":{h.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{h.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&h.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{h.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"source":{s&&p.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),s&&p.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{const y=u(p);h.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const y=u(p);p.invalid?h.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):h.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{h.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId});break}case"tool-result":{const y=u(p);h.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...y!=null?{dynamic:y}:{}});break}case"tool-error":{const y=u(p);h.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:p.providerExecuted?typeof p.error=="string"?p.error:JSON.stringify(p.error):l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...y!=null?{dynamic:y}:{}});break}case"tool-output-denied":{h.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{h.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{a&&h.enqueue({type:"start",...m!=null?{messageMetadata:m}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&h.enqueue({type:"finish",finishReason:p.finishReason,...m!=null?{messageMetadata:m}:{}});break}case"abort":{h.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const y=_;throw new Error(`Unknown chunk type: ${y}`)}}m!=null&&_!=="start"&&_!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:m})}}));return wa(c7({stream:f,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){u7({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){r7({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...c}={}){return n7({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...c})}toTextStreamResponse(e){return t7({textStream:this.textStream,...e})}};ia({prefix:"aiobj",size:24}),ia({prefix:"aiobj",size:24});var y7="AI_MCPClientError",U_=`vercel.ai.error.${y7}`,v7=Symbol.for(U_),z_,Z_,He=class extends(Z_=ke,z_=v7,Z_){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[z_]=!0,this.data=n,this.code=o}static isInstance(e){return ke.hasMarker(e,U_)}},es="2025-11-25",_7=[es,"2025-06-18","2025-03-26","2024-11-05"],w7=he(_e(d(),xe())),b7=ft({name:d(),version:d()}),Dl=ft({_meta:he(T({}).loose())}),vn=Dl,F_=T({method:d(),params:he(Dl)}),V_=T({applyDefaults:he(ve())}).loose(),T7=ft({experimental:he(T({}).loose()),logging:he(T({}).loose()),prompts:he(ft({listChanged:he(ve())})),resources:he(ft({subscribe:he(ve()),listChanged:he(ve())})),tools:he(ft({listChanged:he(ve())})),elicitation:he(V_)});T({elicitation:he(V_)}).loose();var k7=vn.extend({protocolVersion:d(),capabilities:T7,serverInfo:b7,instructions:he(d())}),Tp=vn.extend({nextCursor:he(d())}),S7=T({name:d(),title:he(d()),description:he(d()),inputSchema:T({type:P("object"),properties:he(T({}).loose())}).loose(),outputSchema:he(T({}).loose()),annotations:he(T({title:he(d())}).loose()),_meta:w7}).loose(),C7=Tp.extend({tools:q(S7)}),H_=T({type:P("text"),text:d()}).loose(),B_=T({type:P("image"),data:Pm(),mimeType:d()}).loose(),I7=T({uri:d(),name:d(),title:he(d()),description:he(d()),mimeType:he(d()),size:he(O())}).loose(),x7=Tp.extend({resources:q(I7)}),W_=T({uri:d(),name:he(d()),title:he(d()),mimeType:he(d())}).loose(),G_=W_.extend({text:d()}),J_=W_.extend({blob:Pm()}),K_=T({type:P("resource"),resource:ae([G_,J_])}).loose(),E7=vn.extend({content:q(ae([H_,B_,K_])),structuredContent:he(xe()),isError:ve().default(!1).optional()}).or(vn.extend({toolResult:xe()})),$7=T({uriTemplate:d(),name:d(),title:he(d()),description:he(d()),mimeType:he(d())}).loose(),R7=vn.extend({resourceTemplates:q($7)}),P7=vn.extend({contents:q(ae([G_,J_]))}),M7=T({name:d(),description:he(d()),required:he(ve())}).loose(),N7=T({name:d(),title:he(d()),description:he(d()),arguments:he(q(M7))}).loose(),O7=Tp.extend({prompts:q(N7)}),A7=T({role:ae([P("user"),P("assistant")]),content:ae([H_,B_,K_])}).loose(),q7=vn.extend({description:he(d()),messages:q(A7)}),L7=Dl.extend({message:d(),requestedSchema:xe()}),Y_=F_.extend({method:P("elicitation/create"),params:L7}),j7=vn.extend({action:ae([P("accept"),P("decline"),P("cancel")]),content:he(_e(d(),xe()))}),Ul="2.0",D7=T({jsonrpc:P(Ul),id:ae([d(),O().int()])}).merge(F_).strict(),U7=T({jsonrpc:P(Ul),id:ae([d(),O().int()]),result:vn}).strict(),z7=T({jsonrpc:P(Ul),id:ae([d(),O().int()]),error:T({code:O().int(),message:d(),data:he(xe())})}).strict(),Z7=T({jsonrpc:P(Ul)}).merge(T({method:d(),params:he(Dl)})).strict(),ba=ae([D7,Z7,U7,z7]),Q_=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",X_=T({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:O().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),sr=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:zm.custom,message:"URL must be parseable",fatal:!0}),jh}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),F7=T({resource:d().url(),authorization_servers:q(sr).optional(),jwks_uri:d().url().optional(),scopes_supported:q(d()).optional(),bearer_methods_supported:q(d()).optional(),resource_signing_alg_values_supported:q(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:ve().optional(),authorization_details_types_supported:q(d()).optional(),dpop_signing_alg_values_supported:q(d()).optional(),dpop_bound_access_tokens_required:ve().optional()}).passthrough(),e1=T({issuer:d(),authorization_endpoint:sr,token_endpoint:sr,registration_endpoint:sr.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),code_challenge_methods_supported:q(d()),token_endpoint_auth_methods_supported:q(d()).optional(),token_endpoint_auth_signing_alg_values_supported:q(d()).optional()}).passthrough(),V7=T({issuer:d(),authorization_endpoint:sr,token_endpoint:sr,userinfo_endpoint:sr.optional(),jwks_uri:sr,registration_endpoint:sr.optional(),scopes_supported:q(d()).optional(),response_types_supported:q(d()),grant_types_supported:q(d()).optional(),subject_types_supported:q(d()),id_token_signing_alg_values_supported:q(d()),claims_supported:q(d()).optional(),token_endpoint_auth_methods_supported:q(d()).optional()}).passthrough(),H7=V7.merge(e1.pick({code_challenge_methods_supported:!0})),B7=T({client_id:d(),client_secret:d().optional(),client_id_issued_at:O().optional(),client_secret_expires_at:O().optional()}).strip(),W7=T({redirect_uris:q(sr),token_endpoint_auth_method:d().optional(),grant_types:q(d()).optional(),response_types:q(d()).optional(),client_name:d().optional(),client_uri:sr.optional(),logo_uri:sr.optional(),scope:d().optional(),contacts:q(d()).optional(),tos_uri:sr.optional(),policy_uri:d().optional(),jwks_uri:sr.optional(),jwks:Tt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),G7=T({error:d(),error_description:d().optional(),error_uri:d().optional()}),J7=W7.merge(B7),K7="AI_MCPClientOAuthError",t1=`vercel.ai.error.${K7}`,Y7=Symbol.for(t1),r1,n1,Ta=class extends(n1=ke,r1=Y7,n1){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[r1]=!0}static isInstance(e){return ke.hasMarker(e,t1)}},ts=class extends Ta{};ts.errorCode="server_error";var zl=class extends Ta{};zl.errorCode="invalid_client";var Zl=class extends Ta{};Zl.errorCode="invalid_grant";var Fl=class extends Ta{};Fl.errorCode="unauthorized_client";var Q7={[ts.errorCode]:ts,[zl.errorCode]:zl,[Zl.errorCode]:Zl,[Fl.errorCode]:Fl};function X7(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function eR({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var Vl=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function Hl(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,o]=r.split(" ");if(n.toLowerCase()!=="bearer"||!o)return;const s=/resource_metadata="([^"]*)"/,a=r.match(s);if(a)try{return new URL(a[1])}catch{return}}function tR(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function kp(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?kp(e,void 0,r):void 0;throw n}}async function o1(e,t,r=fetch){return await kp(e,{"MCP-Protocol-Version":t},r)}function rR(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function nR(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:es;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=tR(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await o1(l,i,r);if(!n?.metadataUrl&&rR(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await o1(u,i,r)}return c}async function oR(e,t,r=fetch){const n=await nR(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return F7.parse(await n.json())}function sR(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function aR(e,{fetchFn:t=fetch,protocolVersion:r=es}={}){var n;const o={"MCP-Protocol-Version":r},s=sR(e);for(const{url:a,type:i}of s){const l=await kp(a,o,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return e1.parse(await l.json());{const c=H7.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 iR(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){const i="code",l="S256";let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else c=new URL("/authorize",e);const u=await H0(),f=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",a.href),{authorizationUrl:c,codeVerifier:f}}function s1(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function a1(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":lR(o,s,r);return;case"client_secret_post":cR(o,s,n);return;case"none":uR(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function lR(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function cR(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function uR(e,t){t.set("client_id",e)}async function Sp(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=G7.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=Q7[o]||ts;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ts({message:o})}}async function dR(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",f=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(i)i(p,h,e,t);else{const _=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],y=s1(r,_);a1(y,r,p,h)}a&&h.set("resource",a.href);const m=await(l??fetch)(f,{method:"POST",headers:p,body:h});if(!m.ok)throw await Sp(m);return X_.parse(await m.json())}async function pR(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,f,e,t);else{const h=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],m=s1(r,h);a1(m,r,u,f)}o&&f.set("resource",o.href);const p=await(a??fetch)(c,{method:"POST",headers:u,body:f});if(!p.ok)throw await Sp(p);return X_.parse({refresh_token:n,...await p.json()})}async function fR(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Sp(s);return J7.parse(await s.json())}async function Bl(e,t){var r,n;try{return await Cp(e,t)}catch(o){if(o instanceof zl||o instanceof Fl)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Cp(e,t);if(o instanceof Zl)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Cp(e,t);throw o}}async function hR(e,t,r){const n=X7(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!eR({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 Cp(e,{serverUrl:t,authorizationCode:r,callbackState:n,scope:o,resourceMetadataUrl:s,fetchFn:a}){let i,l;try{i=await oR(t,{resourceMetadataUrl:s},a),i.authorization_servers&&i.authorization_servers.length>0&&(l=i.authorization_servers[0])}catch{}l||(l=t);const c=await hR(t,e,i),u=await aR(l,{fetchFn:a});let f=await Promise.resolve(e.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const y=await fR(l,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(y),f=y}if(r!==void 0){if(e.storedState){const v=await e.storedState();if(v!==void 0&&v!==n)throw new Error("OAuth state parameter mismatch - possible CSRF attack")}const y=await e.codeVerifier(),w=await dR(l,{metadata:u,clientInformation:f,authorizationCode:r,codeVerifier:y,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(w),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const y=await pR(l,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(y),"AUTHORIZED"}catch(y){if(!(!(y instanceof Ta)||y instanceof ts))throw y}const h=e.state?await e.state():void 0;h&&e.saveState&&await e.saveState(h);const{authorizationUrl:m,codeVerifier:_}=await iR(l,{metadata:u,clientInformation:f,state:h,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(_),await e.redirectToAuthorization(m),"REDIRECT"}var mR=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow"}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r,this.redirectMode=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":es};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return qn(t,`ai-sdk/${Q_}`,la())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,s,a,i,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:c,signal:(o=this.abortController)==null?void 0:o.signal,redirect:this.redirectMode});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Hl(u);try{if(await Bl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new Vl;return(s=this.onerror)==null||s.call(this,_),t(_)}}catch(m){return(a=this.onerror)==null||a.call(this,m),t(m)}return r(!0)}if(!u.ok||!u.body){let m=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(m+=". This server does not support SSE transport. Try using `http` transport instead");const _=new He({message:m});return(i=this.onerror)==null||i.call(this,_),t(_)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Fo).getReader(),h=async()=>{var m,_,y;try{for(;;){const{done:w,value:v}=await p.read();if(w){if(this.connected)throw this.connected=!1,new He({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:g,data:S}=v;if(g==="endpoint"){if(this.endpoint=new URL(S,this.url),this.endpoint.origin!==this.url.origin)throw new He({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(g==="message")try{const b=ba.parse(JSON.parse(S));(m=this.onmessage)==null||m.call(this,b)}catch(b){const k=new He({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(_=this.onerror)==null||_.call(this,k)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(y=this.onerror)==null||y.call(this,w),t(w)}};this.sseConnection={close:()=>p.cancel()},h()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),t(c)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new He({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,a,i,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal,redirect:this.redirectMode},f=await fetch(t,u);if(f.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Hl(f);try{if(await Bl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new Vl;(s=this.onerror)==null||s.call(this,h);return}}catch(p){(a=this.onerror)==null||a.call(this,p);return}return r(!0)}if(!f.ok){const p=await f.text().catch(()=>null),h=new He({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${f.status}): ${p}`});(i=this.onerror)==null||i.call(this,h);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},gR=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow"}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r,this.redirectMode=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":es};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return qn(t,`ai-sdk/${Q_}`,la())}async start(){if(this.abortController)throw new He({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,a,i,l,c;try{const f={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal,redirect:this.redirectMode},p=await fetch(this.url,f),h=p.headers.get("mcp-session-id");if(h&&(this.sessionId=h),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Hl(p);try{if(await Bl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Vl}catch(w){throw(o=this.onerror)==null||o.call(this,w),w}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const w=await p.text().catch(()=>null);let v=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${w}`;p.status===404&&(v+=". This server does not support HTTP transport. Try using `sse` transport instead");const g=new He({message:v});throw(s=this.onerror)==null||s.call(this,g),g}if(!("id"in e))return;const _=p.headers.get("content-type")||"";if(_.includes("application/json")){const w=await p.json(),v=Array.isArray(w)?w.map(g=>ba.parse(g)):[ba.parse(w)];for(const g of v)(a=this.onmessage)==null||a.call(this,g);return}if(_.includes("text/event-stream")){if(!p.body){const S=new He({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,S),S}const v=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Fo).getReader();(async()=>{var S,b,k;try{for(;;){const{done:C,value:R}=await v.read();if(C)return;const{event:I,data:j}=R;if(I==="message")try{const N=ba.parse(JSON.parse(j));(S=this.onmessage)==null||S.call(this,N)}catch(N){const L=new He({message:"MCP HTTP Transport Error: Failed to parse message",cause:N});(b=this.onerror)==null||b.call(this,L)}}}catch(C){if(C instanceof Error&&C.name==="AbortError")return;(k=this.onerror)==null||k.call(this,C)}})();return}const y=new He({message:`MCP HTTP Transport Error: Unexpected content type: ${_}`});throw(l=this.onerror)==null||l.call(this,y),y}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new He({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,o,s,a,i;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const c=await fetch(this.url.href,{method:"GET",headers:l,signal:(r=this.abortController)==null?void 0:r.signal,redirect:this.redirectMode}),u=c.headers.get("mcp-session-id");if(u&&(this.sessionId=u),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=Hl(c);try{if(await Bl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new Vl;(n=this.onerror)==null||n.call(this,_);return}}catch(m){(o=this.onerror)==null||o.call(this,m);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const m=new He({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,m);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Fo).getReader(),h=async()=>{var m,_,y,w;try{for(;;){const{done:v,value:g}=await p.read();if(v)return;const{event:S,data:b,id:k}=g;if(k&&(this.lastInboundEventId=k),S==="message")try{const C=ba.parse(JSON.parse(b));(m=this.onmessage)==null||m.call(this,C)}catch(C){const R=new He({message:"MCP HTTP Transport Error: Failed to parse message",cause:C});(_=this.onerror)==null||_.call(this,R)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(y=this.onerror)==null||y.call(this,v),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,h()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function yR(e){switch(e.type){case"sse":return new mR(e);case"http":return new gR(e);default:throw new He({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function vR(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var _R="1.0.0";function i1({output:e}){const t=e;return!("content"in t)||!Array.isArray(t.content)?{type:"json",value:t}:{type:"content",value:t.content.map(n=>n.type==="text"&&"text"in n?{type:"text",text:n.text}:n.type==="image"&&"data"in n&&"mimeType"in n?{type:"image-data",data:n.data,mediaType:n.mimeType}:{type:"text",text:JSON.stringify(n)})}}async function wR(e){const t=new bR(e);return await t.init(),t}var bR=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=_R,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},vR(e)?this.transport=e:this.transport=yR(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=s=>this.onError(s),this.transport.onmessage=s=>{if("method"in s){"id"in s?this.onRequestMessage(s):this.onError(new He({message:"Unsupported message type"}));return}this.onResponse(s)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:es,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:k7});if(e===void 0)throw new He({message:"Server sent invalid initialize result"});if(!_7.includes(e.protocolVersion))throw new He({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new He({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new He({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new He({message:"Server does not support prompts"});break;default:throw new He({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new He({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=r?.signal;s?.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(s?.aborted)return o(new He({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const f=new He({message:"Failed to parse server response",cause:u});o(f)}}),this.transport.send(i).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:C7,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:E7,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:x7,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:P7,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:R7,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:O7,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:q7,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){const t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t="automatic"}={}){var r,n;const o={};for(const{name:s,title:a,description:i,inputSchema:l,annotations:c,_meta:u}of e.tools){const f=a??c?.title;if(t!=="automatic"&&!(s in t))continue;const p=this,h=t!=="automatic"?(r=t[s])==null?void 0:r.outputSchema:void 0,m=async(y,w)=>{var v;(v=w?.abortSignal)==null||v.throwIfAborted();const g=await p.callTool({name:s,args:y,options:w});return h!=null?p.extractStructuredContent(g,h,s):g},_=t==="automatic"?fy({description:i,title:f,inputSchema:Qo({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:m,toModelOutput:i1}):{description:i,title:f,inputSchema:t[s].inputSchema,...h!=null?{outputSchema:h}:{},execute:m,toModelOutput:i1};o[s]={..._,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await Cr({value:e.structuredContent,schema:po(t)});if(!n.success)throw new He({message:`Tool "${r}" returned structuredContent that does not match the expected outputSchema`,cause:n.error});return n.value}if("content"in e&&Array.isArray(e.content)){const n=e.content.find(o=>o.type==="text");if(n&&"text"in n){const o=await Ir({text:n.text,schema:t});if(!o.success)throw new He({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new He({message:`Tool "${r}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==Y_)throw new He({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=Y_.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const r=await this.elicitationRequestHandler(t.data),n=j7.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new He({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),r=this.responseHandlers.get(t);if(r===void 0)throw new He({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new He({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Ip=T({error:T({message:d(),type:d().nullish(),param:Tt().nullish(),code:ae([d(),O()]).nullish()})}),Hr=Xr({errorSchema:Ip,errorToMessage:e=>e.error.message});function l1(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),r=e.startsWith("gpt-4")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")&&!e.startsWith("gpt-5.4-nano")||e.startsWith("o3")||e.startsWith("o4-mini"),n=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2")||e.startsWith("gpt-5.3")||e.startsWith("gpt-5.4");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function c1(e){var t,r,n,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const i=(t=e.prompt_tokens)!=null?t:0,l=(r=e.completion_tokens)!=null?r:0,c=(o=(n=e.prompt_tokens_details)==null?void 0:n.cached_tokens)!=null?o:0,u=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:i,noCache:i-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function TR({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{n.push({role:"system",content:a});break}case"developer":{n.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const i=t;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text});break}n.push({role:"user",content:a.map((i,l)=>{var c,u,f;switch(i.type){case"text":return{type:"text",text:i.text};case"file":if(i.mediaType.startsWith("image/")){const p=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${p};base64,${Ko(i.data)}`,detail:(u=(c=i.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(i.mediaType.startsWith("audio/")){if(i.data instanceof URL)throw new Qr({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Ko(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Ko(i.data),format:"mp3"}};default:throw new Qr({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new Qr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(f=i.filename)!=null?f:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${Ko(i.data)}`}}}else throw new Qr({functionality:`file part media type ${i.mediaType}`})}})});break}case"assistant":{let i="";const l=[];for(const c of a)switch(c.type){case"text":{i+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}n.push({role:"assistant",content:i,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const i of a){if(i.type==="tool-approval-response")continue;const l=i.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(r=l.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}n.push({role:"tool",tool_call_id:i.toolCallId,content:c})}break}default:{const i=s;throw new Error(`Unsupported role: ${i}`)}}return{messages:n,warnings:o}}function xp({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function u1(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var kR=Te(()=>be(T({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(T({message:T({role:P("assistant").nullish(),content:d().nullish(),tool_calls:q(T({id:d().nullish(),type:P("function"),function:T({name:d(),arguments:d()})})).nullish(),annotations:q(T({type:P("url_citation"),url_citation:T({start_index:O(),end_index:O(),url:d(),title:d()})})).nullish()}),index:O(),logprobs:T({content:q(T({token:d(),logprob:O(),top_logprobs:q(T({token:d(),logprob:O()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:T({prompt_tokens:O().nullish(),completion_tokens:O().nullish(),total_tokens:O().nullish(),prompt_tokens_details:T({cached_tokens:O().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:O().nullish(),accepted_prediction_tokens:O().nullish(),rejected_prediction_tokens:O().nullish()}).nullish()}).nullish()}))),SR=Te(()=>be(ae([T({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(T({delta:T({role:de(["assistant"]).nullish(),content:d().nullish(),tool_calls:q(T({index:O(),id:d().nullish(),type:P("function").nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:q(T({type:P("url_citation"),url_citation:T({start_index:O(),end_index:O(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:T({content:q(T({token:d(),logprob:O(),top_logprobs:q(T({token:d(),logprob:O()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:O()})),usage:T({prompt_tokens:O().nullish(),completion_tokens:O().nullish(),total_tokens:O().nullish(),prompt_tokens_details:T({cached_tokens:O().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:O().nullish(),accepted_prediction_tokens:O().nullish(),rejected_prediction_tokens:O().nullish()}).nullish()}).nullish()}),Ip]))),CR=Te(()=>be(T({logitBias:_e(Zm(),O()).optional(),logprobs:ae([ve(),O()]).optional(),parallelToolCalls:ve().optional(),user:d().optional(),reasoningEffort:de(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:O().optional(),store:ve().optional(),metadata:_e(d().max(64),d().max(512)).optional(),prediction:_e(d(),Tt()).optional(),serviceTier:de(["auto","flex","priority","default"]).optional(),strictJsonSchema:ve().optional(),textVerbosity:de(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:de(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:de(["system","developer","remove"]).optional(),forceReasoning:ve().optional()})));function IR({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:r.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new Qr({functionality:`tool choice type: ${s}`})}}}var xR=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:f,providerOptions:p}){var h,m,_,y,w;const v=[],g=(h=await gn({provider:"openai",providerOptions:p,schema:CR}))!=null?h:{},S=l1(this.modelId),b=(m=g.forceReasoning)!=null?m:S.isReasoningModel;o!=null&&v.push({type:"unsupported",feature:"topK"});const{messages:k,warnings:C}=TR({prompt:e,systemMessageMode:(_=g.systemMessageMode)!=null?_:b?"developer":S.systemMessageMode});v.push(...C);const R=(y=g.strictJsonSchema)!=null?y:!0,I={model:this.modelId,logit_bias:g.logitBias,logprobs:g.logprobs===!0||typeof g.logprobs=="number"?!0:void 0,top_logprobs:typeof g.logprobs=="number"?g.logprobs:typeof g.logprobs=="boolean"&&g.logprobs?0:void 0,user:g.user,parallel_tool_calls:g.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:R,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:g.textVerbosity,max_completion_tokens:g.maxCompletionTokens,store:g.store,metadata:g.metadata,prediction:g.prediction,reasoning_effort:g.reasoningEffort,service_tier:g.serviceTier,prompt_cache_key:g.promptCacheKey,prompt_cache_retention:g.promptCacheRetention,safety_identifier:g.safetyIdentifier,messages:k};b?((g.reasoningEffort!=="none"||!S.supportsNonReasoningParameters)&&(I.temperature!=null&&(I.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),I.top_p!=null&&(I.top_p=void 0,v.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),I.logprobs!=null&&(I.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"}))),I.frequency_penalty!=null&&(I.frequency_penalty=void 0,v.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),I.presence_penalty!=null&&(I.presence_penalty=void 0,v.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),I.logit_bias!=null&&(I.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),I.top_logprobs!=null&&(I.top_logprobs=void 0,v.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),I.max_tokens!=null&&(I.max_completion_tokens==null&&(I.max_completion_tokens=I.max_tokens),I.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&I.temperature!=null&&(I.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),g.serviceTier==="flex"&&!S.supportsFlexProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),I.service_tier=void 0),g.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),I.service_tier=void 0);const{tools:j,toolChoice:N,toolWarnings:L}=IR({tools:u,toolChoice:f});return{args:{...I,tools:j,tool_choice:N},warnings:[...v,...L]}}async doGenerate(e){var t,r,n,o,s,a,i;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:f,rawValue:p}=await nr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:l,failedResponseHandler:Hr,successfulResponseHandler:or(kR),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.choices[0],m=[],_=h.message.content;_!=null&&_.length>0&&m.push({type:"text",text:_});for(const v of(t=h.message.tool_calls)!=null?t:[])m.push({type:"tool-call",toolCallId:(r=v.id)!=null?r:Wt(),toolName:v.function.name,input:v.function.arguments});for(const v of(n=h.message.annotations)!=null?n:[])m.push({type:"source",sourceType:"url",id:Wt(),url:v.url_citation.url,title:v.url_citation.title});const y=(o=f.usage)==null?void 0:o.completion_tokens_details;(s=f.usage)==null||s.prompt_tokens_details;const w={openai:{}};return y?.accepted_prediction_tokens!=null&&(w.openai.acceptedPredictionTokens=y?.accepted_prediction_tokens),y?.rejected_prediction_tokens!=null&&(w.openai.rejectedPredictionTokens=y?.rejected_prediction_tokens),((a=h.logprobs)==null?void 0:a.content)!=null&&(w.openai.logprobs=h.logprobs.content),{content:m,finishReason:{unified:u1(h.finish_reason),raw:(i=h.finish_reason)!=null?i:void 0},usage:c1(f.usage),request:{body:l},response:{...xp(f),headers:u,body:p},warnings:c,providerMetadata:w}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await nr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:n,failedResponseHandler:Hr,successfulResponseHandler:$l(SR),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i={unified:"other",raw:void 0},l,c=!1,u=!1;const f={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,h){var m,_,y,w,v,g,S,b,k,C,R,I,j,N,L,z,H;if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:p.error});return}const ee=p.value;if("error"in ee){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:ee.error});return}if(!c){const V=xp(ee);Object.values(V).some(Boolean)&&(c=!0,h.enqueue({type:"response-metadata",...xp(ee)}))}ee.usage!=null&&(l=ee.usage,((m=ee.usage.completion_tokens_details)==null?void 0:m.accepted_prediction_tokens)!=null&&(f.openai.acceptedPredictionTokens=(_=ee.usage.completion_tokens_details)==null?void 0:_.accepted_prediction_tokens),((y=ee.usage.completion_tokens_details)==null?void 0:y.rejected_prediction_tokens)!=null&&(f.openai.rejectedPredictionTokens=(w=ee.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const te=ee.choices[0];if(te?.finish_reason!=null&&(i={unified:u1(te.finish_reason),raw:te.finish_reason}),((v=te?.logprobs)==null?void 0:v.content)!=null&&(f.openai.logprobs=te.logprobs.content),te?.delta==null)return;const X=te.delta;if(X.content!=null&&(u||(h.enqueue({type:"text-start",id:"0"}),u=!0),h.enqueue({type:"text-delta",id:"0",delta:X.content})),X.tool_calls!=null)for(const V of X.tool_calls){const se=V.index;if(a[se]==null){if(V.type!=null&&V.type!=="function")throw new jd({data:V,message:"Expected 'function' type."});if(V.id==null)throw new jd({data:V,message:"Expected 'id' to be a string."});if(((g=V.function)==null?void 0:g.name)==null)throw new jd({data:V,message:"Expected 'function.name' to be a string."});h.enqueue({type:"tool-input-start",id:V.id,toolName:V.function.name}),a[se]={id:V.id,type:"function",function:{name:V.function.name,arguments:(S=V.function.arguments)!=null?S:""},hasFinished:!1};const E=a[se];((b=E.function)==null?void 0:b.name)!=null&&((k=E.function)==null?void 0:k.arguments)!=null&&(E.function.arguments.length>0&&h.enqueue({type:"tool-input-delta",id:E.id,delta:E.function.arguments}),cy(E.function.arguments)&&(h.enqueue({type:"tool-input-end",id:E.id}),h.enqueue({type:"tool-call",toolCallId:(C=E.id)!=null?C:Wt(),toolName:E.function.name,input:E.function.arguments}),E.hasFinished=!0));continue}const D=a[se];D.hasFinished||(((R=V.function)==null?void 0:R.arguments)!=null&&(D.function.arguments+=(j=(I=V.function)==null?void 0:I.arguments)!=null?j:""),h.enqueue({type:"tool-input-delta",id:D.id,delta:(N=V.function.arguments)!=null?N:""}),((L=D.function)==null?void 0:L.name)!=null&&((z=D.function)==null?void 0:z.arguments)!=null&&cy(D.function.arguments)&&(h.enqueue({type:"tool-input-end",id:D.id}),h.enqueue({type:"tool-call",toolCallId:(H=D.id)!=null?H:Wt(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0))}if(X.annotations!=null)for(const V of X.annotations)h.enqueue({type:"source",sourceType:"url",id:Wt(),url:V.url_citation.url,title:V.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:i,usage:c1(l),...f!=null?{providerMetadata:f}:{}})}})),request:{body:n},response:{headers:o}}}};function d1(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(r=e.completion_tokens)!=null?r:0;return{inputTokens:{total:(n=e.prompt_tokens)!=null?n:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}function ER({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
584
+ `)}})}},L_={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function fR({status:e,statusText:t,headers:r,stream:n,consumeSseStream:o}){let s=n.pipeThrough(new j_);if(o){const[a,i]=s.tee();s=a,o({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Fl(r,L_)})}function hR({originalMessages:e,responseMessageId:t}){if(e==null)return;const r=e[e.length-1];return r?.role==="assistant"?r.id:typeof t=="function"?t():t}function mR(e){return e.type.startsWith("data-")}function Cp(e){return e.type.startsWith("tool-")}function gR(e){return e.type==="dynamic-tool"}function D_(e){return Cp(e)||gR(e)}function U_(e){return e.type.split("-").slice(1).join("-")}function yR({lastMessage:e,messageId:t}){return{message:e?.role==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function vR({stream:e,messageMetadataSchema:t,dataPartSchemas:r,runUpdateMessageJob:n,onError:o,onToolCall:s,onData:a}){return e.pipeThrough(new TransformStream({async transform(i,l){await n(async({state:c,write:u})=>{var f,p,h,m;function _(y){const b=c.message.parts.filter(D_).find(T=>T.toolCallId===y);if(b==null)throw new as({chunkType:"tool-invocation",chunkId:y,message:`No tool invocation found for tool call ID "${y}".`});return b}function g(y){var S;const b=c.message.parts.find(R=>Cp(R)&&R.toolCallId===y.toolCallId),T=y,x=b;if(b!=null){b.state=y.state,x.input=T.input,x.output=T.output,x.errorText=T.errorText,x.rawInput=T.rawInput,x.preliminary=T.preliminary,y.title!==void 0&&(x.title=y.title),x.providerExecuted=(S=T.providerExecuted)!=null?S:b.providerExecuted;const R=T.providerMetadata;if(R!=null)if(y.state==="output-available"||y.state==="output-error"){const C=b;C.resultProviderMetadata=R}else b.callProviderMetadata=R}else c.message.parts.push({type:`tool-${y.toolName}`,toolCallId:y.toolCallId,state:y.state,title:y.title,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null&&(y.state==="output-available"||y.state==="output-error")?{resultProviderMetadata:T.providerMetadata}:{},...T.providerMetadata!=null&&!(y.state==="output-available"||y.state==="output-error")?{callProviderMetadata:T.providerMetadata}:{}})}function w(y){var S,b;const T=c.message.parts.find(C=>C.type==="dynamic-tool"&&C.toolCallId===y.toolCallId),x=y,R=T;if(T!=null){T.state=y.state,R.toolName=y.toolName,R.input=x.input,R.output=x.output,R.errorText=x.errorText,R.rawInput=(S=x.rawInput)!=null?S:R.rawInput,R.preliminary=x.preliminary,y.title!==void 0&&(R.title=y.title),R.providerExecuted=(b=x.providerExecuted)!=null?b:T.providerExecuted;const C=x.providerMetadata;if(C!=null)if(y.state==="output-available"||y.state==="output-error"){const L=T;L.resultProviderMetadata=C}else T.callProviderMetadata=C}else c.message.parts.push({type:"dynamic-tool",toolName:y.toolName,toolCallId:y.toolCallId,state:y.state,input:x.input,output:x.output,errorText:x.errorText,preliminary:x.preliminary,providerExecuted:x.providerExecuted,title:y.title,...x.providerMetadata!=null&&(y.state==="output-available"||y.state==="output-error")?{resultProviderMetadata:x.providerMetadata}:{},...x.providerMetadata!=null&&!(y.state==="output-available"||y.state==="output-error")?{callProviderMetadata:x.providerMetadata}:{}})}async function v(y){if(y!=null){const S=c.message.metadata!=null?Ul(c.message.metadata,y):y;t!=null&&await Ct({value:S,schema:t,context:{field:"message.metadata",entityId:c.message.id}}),c.message.metadata=S}}switch(i.type){case"text-start":{const y={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=y,c.message.parts.push(y),u();break}case"text-delta":{const y=c.activeTextParts[i.id];if(y==null)throw new as({chunkType:"text-delta",chunkId:i.id,message:`Received text-delta for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});y.text+=i.delta,y.providerMetadata=(f=i.providerMetadata)!=null?f:y.providerMetadata,u();break}case"text-end":{const y=c.activeTextParts[i.id];if(y==null)throw new as({chunkType:"text-end",chunkId:i.id,message:`Received text-end for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});y.state="done",y.providerMetadata=(p=i.providerMetadata)!=null?p:y.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const y={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=y,c.message.parts.push(y),u();break}case"reasoning-delta":{const y=c.activeReasoningParts[i.id];if(y==null)throw new as({chunkType:"reasoning-delta",chunkId:i.id,message:`Received reasoning-delta for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});y.text+=i.delta,y.providerMetadata=(h=i.providerMetadata)!=null?h:y.providerMetadata,u();break}case"reasoning-end":{const y=c.activeReasoningParts[i.id];if(y==null)throw new as({chunkType:"reasoning-end",chunkId:i.id,message:`Received reasoning-end for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});y.providerMetadata=(m=i.providerMetadata)!=null?m:y.providerMetadata,y.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url,...i.providerMetadata!=null?{providerMetadata:i.providerMetadata}:{}}),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 y=c.message.parts.filter(Cp);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:y.length,dynamic:i.dynamic,title:i.title},i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}):g({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"tool-input-delta":{const y=c.partialToolCalls[i.toolCallId];if(y==null)throw new as({chunkType:"tool-input-delta",chunkId:i.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${i.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});y.text+=i.inputTextDelta;const{value:S}=await Sa(y.text);y.dynamic?w({toolCallId:i.toolCallId,toolName:y.toolName,state:"input-streaming",input:S,title:y.title}):g({toolCallId:i.toolCallId,toolName:y.toolName,state:"input-streaming",input:S,title:y.title}),u();break}case"tool-input-available":{i.dynamic?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}):g({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:i.title}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{const y=c.message.parts.filter(D_).find(b=>b.toolCallId===i.toolCallId);(y!=null?y.type==="dynamic-tool":!!i.dynamic)?w({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}):g({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-approval-request":{const y=_(i.toolCallId);y.state="approval-requested",y.approval={id:i.approvalId},u();break}case"tool-output-denied":{const y=_(i.toolCallId);y.state="output-denied",u();break}case"tool-output-available":{const y=_(i.toolCallId);y.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:y.toolName,state:"output-available",input:y.input,output:i.output,preliminary:i.preliminary,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:y.title}):g({toolCallId:i.toolCallId,toolName:U_(y),state:"output-available",input:y.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary,providerMetadata:i.providerMetadata,title:y.title}),u();break}case"tool-output-error":{const y=_(i.toolCallId);y.type==="dynamic-tool"?w({toolCallId:i.toolCallId,toolName:y.toolName,state:"output-error",input:y.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:y.title}):g({toolCallId:i.toolCallId,toolName:U_(y),state:"output-error",input:y.input,rawInput:y.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata,title:y.title}),u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await v(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{i.finishReason!=null&&(c.finishReason=i.finishReason),await v(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await v(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{o?.(new Error(i.errorText));break}default:if(mR(i)){if(r?.[i.type]!=null){const b=c.message.parts.findIndex(x=>"id"in x&&"data"in x&&x.id===i.id&&x.type===i.type),T=b>=0?b:c.message.parts.length;await Ct({value:i.data,schema:r[i.type],context:{field:`message.parts[${T}].data`,entityName:i.type,entityId:i.id}})}const y=i;if(y.transient){a?.(y);break}const S=y.id!=null?c.message.parts.find(b=>y.type===b.type&&y.id===b.id):void 0;S!=null?S.data=y.data:c.message.parts.push(y),a?.(y),u()}}l.enqueue(i)})}}))}function _R({messageId:e,originalMessages:t=[],onStepFinish:r,onFinish:n,onError:o,stream:s}){let a=t?.[t.length-1];a?.role!=="assistant"?a=void 0:e=a.id;let i=!1;const l=s.pipeThrough(new TransformStream({transform(m,_){if(m.type==="start"){const g=m;g.messageId==null&&e!=null&&(g.messageId=e)}m.type==="abort"&&(i=!0),_.enqueue(m)}}));if(n==null&&r==null)return l;const c=yR({lastMessage:a?structuredClone(a):void 0,messageId:e??""}),u=async m=>{await m({state:c,write:()=>{}})};let f=!1;const p=async()=>{if(f||!n)return;f=!0;const m=c.message.id===a?.id;await n({isAborted:i,isContinuation:m,responseMessage:c.message,messages:[...m?t.slice(0,-1):t,c.message],finishReason:c.finishReason})},h=async()=>{if(!r)return;const m=c.message.id===a?.id;try{await r({isContinuation:m,responseMessage:structuredClone(c.message),messages:[...m?t.slice(0,-1):t,structuredClone(c.message)]})}catch(_){o(_)}};return vR({stream:l,runUpdateMessageJob:u,onError:o}).pipeThrough(new TransformStream({async transform(m,_){m.type==="finish-step"&&await h(),_.enqueue(m)},async cancel(){await p()},async flush(){await p()}}))}function wR({response:e,status:t,statusText:r,headers:n,stream:o,consumeSseStream:s}){let a=o.pipeThrough(new j_);if(s){const[i,l]=a.tee();a=i,s({stream:l})}q_({response:e,status:t,statusText:r,headers:Object.fromEntries(Fl(n,L_).entries()),stream:a.pipeThrough(new TextEncoderStream)})}function Ca(e){const t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){const r=this.getReader();let n=!1;async function o(s){var a;if(!n){n=!0;try{s&&await((a=r.cancel)==null?void 0:a.call(r))}finally{try{r.releaseLock()}catch{}}}}return{async next(){if(n)return{done:!0,value:void 0};const{done:s,value:a}=await r.read();return s?(await o(!0),{done:!0,value:void 0}):{done:!1,value:a}},async return(){return await o(!0),{done:!0,value:void 0}},async throw(s){throw await o(!0),s}}},t}async function bR({stream:e,onError:t}){const r=e.getReader();try{for(;;){const{done:n}=await r.read();if(n)break}}catch(n){t?.(n)}finally{r.releaseLock()}}function z_(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}function kR(){let e=[],t=null,r=!1,n=z_();const o=()=>{r=!0,n.resolve(),e.forEach(a=>a.cancel()),e=[],t?.close()},s=async()=>{if(r&&e.length===0){t?.close();return}if(e.length===0)return n=z_(),await n.promise,s();try{const{value:a,done:i}=await e[0].read();i?(e.shift(),e.length===0&&r?t?.close():await s()):t?.enqueue(a)}catch(a){t?.error(a),e.shift(),o()}};return{stream:new ReadableStream({start(a){t=a},pull:s,async cancel(){for(const a of e)await a.cancel();e=[],r=!0}}),addStream:a=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");e.push(a.getReader()),n.resolve()},close:()=>{r=!0,n.resolve(),e.length===0&&t?.close()},terminate:o}}function TR({tools:e,generatorStream:t,tracer:r,telemetry:n,system:o,messages:s,abortSignal:a,repairToolCall:i,experimental_context:l,generateId:c,stepNumber:u,model:f,onToolCallStart:p,onToolCallFinish:h}){let m=null;const _=new ReadableStream({start(x){m=x}}),g=new Set,w=new Map,v=new Map;let y=!1,S;function b(){y&&g.size===0&&(S!=null&&m.enqueue(S),m.close())}const T=new TransformStream({async transform(x,R){const C=x.type;switch(C){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":{R.enqueue(x);break}case"file":{R.enqueue({type:"file",file:new tR({data:x.data,mediaType:x.mediaType}),...x.providerMetadata!=null?{providerMetadata:x.providerMetadata}:{}});break}case"finish":{S={type:"finish",finishReason:x.finishReason.unified,rawFinishReason:x.finishReason.raw,usage:wp(x.usage),providerMetadata:x.providerMetadata};break}case"tool-approval-request":{const L=v.get(x.toolCallId);if(L==null){m.enqueue({type:"error",error:new mp({toolCallId:x.toolCallId,approvalId:x.approvalId})});break}R.enqueue({type:"tool-approval-request",approvalId:x.approvalId,toolCall:L});break}case"tool-call":{try{const L=await I_({toolCall:x,tools:e,repairToolCall:i,system:o,messages:s});if(v.set(L.toolCallId,L),R.enqueue(L),L.invalid){m.enqueue({type:"tool-error",toolCallId:L.toolCallId,toolName:L.toolName,input:L.input,error:Hd(L.error),dynamic:!0,title:L.title});break}const O=e?.[L.toolName];if(O==null)break;if(O.onInputAvailable!=null&&await O.onInputAvailable({input:L.input,toolCallId:L.toolCallId,messages:s,abortSignal:a,experimental_context:l}),await x_({tool:O,toolCall:L,messages:s,experimental_context:l})){m.enqueue({type:"tool-approval-request",approvalId:c(),toolCall:L});break}if(w.set(L.toolCallId,L.input),O.execute!=null&&L.providerExecuted!==!0){const q=c();g.add(q),kp({toolCall:L,tools:e,tracer:r,telemetry:n,messages:s,abortSignal:a,experimental_context:l,stepNumber:u,model:f,onToolCallStart:p,onToolCallFinish:h,onPreliminaryToolResult:z=>{m.enqueue(z)}}).then(z=>{m.enqueue(z)}).catch(z=>{m.enqueue({type:"error",error:z})}).finally(()=>{g.delete(q),b()})}}catch(L){m.enqueue({type:"error",error:L})}break}case"tool-result":{const L=x.toolName;x.isError?m.enqueue({type:"tool-error",toolCallId:x.toolCallId,toolName:L,input:w.get(x.toolCallId),providerExecuted:!0,error:x.result,dynamic:x.dynamic,...x.providerMetadata!=null?{providerMetadata:x.providerMetadata}:{}}):R.enqueue({type:"tool-result",toolCallId:x.toolCallId,toolName:L,input:w.get(x.toolCallId),output:x.result,providerExecuted:!0,dynamic:x.dynamic,...x.providerMetadata!=null?{providerMetadata:x.providerMetadata}:{}});break}default:{const L=C;throw new Error(`Unhandled chunk type: ${L}`)}}},flush(){y=!0,b()}});return new ReadableStream({async start(x){return Promise.all([t.pipeThrough(T).pipeTo(new WritableStream({write(R){x.enqueue(R)},close(){}})),_.pipeTo(new WritableStream({write(R){x.enqueue(R)},close(){x.close()}}))])}})}var SR=pa({prefix:"aitxt",size:24});function xp({model:e,tools:t,toolChoice:r,system:n,prompt:o,messages:s,maxRetries:a,abortSignal:i,timeout:l,headers:c,stopWhen:u=Tp(1),experimental_output:f,output:p=f,experimental_telemetry:h,prepareStep:m,providerOptions:_,experimental_activeTools:g,activeTools:w=g,experimental_repairToolCall:v,experimental_transform:y,experimental_download:S,includeRawChunks:b=!1,onChunk:T,onError:x=({error:D})=>{console.error(D)},onFinish:R,onAbort:C,onStepFinish:L,experimental_onStart:O,experimental_onStepStart:q,experimental_onToolCallStart:z,experimental_onToolCallFinish:H,experimental_context:ee,experimental_include:re,_internal:{now:X=zl,generateId:V=SR}={},...ie}){const D=vp(l),E=t_(l),U=x8(l),Z=E!=null?new AbortController:void 0,I=U!=null?new AbortController:void 0;return new xR({model:Ll(e),telemetry:h,headers:c,settings:ie,maxRetries:a,abortSignal:M_(i,D!=null?AbortSignal.timeout(D):void 0,Z?.signal,I?.signal),stepTimeoutMs:E,stepAbortController:Z,chunkTimeoutMs:U,chunkAbortController:I,system:n,prompt:o,messages:s,tools:t,toolChoice:r,transforms:bo(y),activeTools:w,repairToolCall:v,stopConditions:bo(u),output:p,providerOptions:_,prepareStep:m,includeRawChunks:b,timeout:l,stopWhen:u,originalAbortSignal:i,onChunk:T,onError:x,onFinish:R,onAbort:C,onStepFinish:L,onStart:O,onStepStart:q,onToolCallStart:z,onToolCallFinish:H,now:X,generateId:V,experimental_context:ee,download:S,include:re})}function CR(e){let t,r="",n="",o,s="";function a({controller:i,partialOutput:l=void 0}){i.enqueue({part:{type:"text-delta",id:t,text:n,providerMetadata:o},partialOutput:l}),n=""}return new TransformStream({async transform(i,l){var c;if(i.type==="finish-step"&&n.length>0&&a({controller:l}),i.type!=="text-delta"&&i.type!=="text-start"&&i.type!=="text-end"){l.enqueue({part:i,partialOutput:void 0});return}if(t==null)t=i.id;else if(i.id!==t){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-start"){l.enqueue({part:i,partialOutput:void 0});return}if(i.type==="text-end"){n.length>0&&a({controller:l}),l.enqueue({part:i,partialOutput:void 0});return}r+=i.text,n+=i.text,o=(c=i.providerMetadata)!=null?c:o;const u=await e.parsePartialOutput({text:r});if(u!==void 0){const f=JSON.stringify(u.partial);f!==s&&(a({controller:l,partialOutput:u.partial}),s=f)}}})}var xR=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:a,stepAbortController:i,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:f,messages:p,tools:h,toolChoice:m,transforms:_,activeTools:g,repairToolCall:w,stopConditions:v,output:y,providerOptions:S,prepareStep:b,includeRawChunks:T,now:x,generateId:R,timeout:C,stopWhen:L,originalAbortSignal:O,onChunk:q,onError:z,onFinish:H,onAbort:ee,onStepFinish:re,onStart:X,onStepStart:V,onToolCallStart:ie,onToolCallFinish:D,experimental_context:E,download:U,include:Z}){this._totalUsage=new da,this._finishReason=new da,this._rawFinishReason=new da,this._steps=new da,this.outputSpecification=y,this.includeRawChunks=T,this.tools=h;const M=v_()(t?.integrations);let B,oe=[];const ne=[];let be,W,A,F={},J=[];const Q=[],he=new Map;let Pe,Ke={},it={};const gt=new TransformStream({async transform(Ae,ft){var It,er,yr,vr;ft.enqueue(Ae);const{part:de}=Ae;if((de.type==="text-delta"||de.type==="reasoning-delta"||de.type==="source"||de.type==="tool-call"||de.type==="tool-result"||de.type==="tool-input-start"||de.type==="tool-input-delta"||de.type==="raw")&&await q?.({chunk:de}),de.type==="error"&&await z({error:f_(de.error)}),de.type==="text-start"&&(Ke[de.id]={type:"text",text:"",providerMetadata:de.providerMetadata},oe.push(Ke[de.id])),de.type==="text-delta"){const nt=Ke[de.id];if(nt==null){ft.enqueue({part:{type:"error",error:`text part ${de.id} not found`},partialOutput:void 0});return}nt.text+=de.text,nt.providerMetadata=(It=de.providerMetadata)!=null?It:nt.providerMetadata}if(de.type==="text-end"){const nt=Ke[de.id];if(nt==null){ft.enqueue({part:{type:"error",error:`text part ${de.id} not found`},partialOutput:void 0});return}nt.providerMetadata=(er=de.providerMetadata)!=null?er:nt.providerMetadata,delete Ke[de.id]}if(de.type==="reasoning-start"&&(it[de.id]={type:"reasoning",text:"",providerMetadata:de.providerMetadata},oe.push(it[de.id])),de.type==="reasoning-delta"){const nt=it[de.id];if(nt==null){ft.enqueue({part:{type:"error",error:`reasoning part ${de.id} not found`},partialOutput:void 0});return}nt.text+=de.text,nt.providerMetadata=(yr=de.providerMetadata)!=null?yr:nt.providerMetadata}if(de.type==="reasoning-end"){const nt=it[de.id];if(nt==null){ft.enqueue({part:{type:"error",error:`reasoning part ${de.id} not found`},partialOutput:void 0});return}nt.providerMetadata=(vr=de.providerMetadata)!=null?vr:nt.providerMetadata,delete it[de.id]}if(de.type==="file"&&oe.push({type:"file",file:de.file,...de.providerMetadata!=null?{providerMetadata:de.providerMetadata}:{}}),de.type==="source"&&oe.push(de),de.type==="tool-call"&&oe.push(de),de.type==="tool-result"&&!de.preliminary&&oe.push(de),de.type==="tool-approval-request"&&oe.push(de),de.type==="tool-error"&&oe.push(de),de.type==="start-step"&&(oe=[],it={},Ke={},F=de.request,J=de.warnings),de.type==="finish-step"){const nt=await Sp({content:oe,tools:h}),Je=new R_({stepNumber:Q.length,model:Y,...Fe,experimental_context:E,content:oe,finishReason:de.finishReason,rawFinishReason:de.rawFinishReason,usage:de.usage,warnings:J,request:F,response:{...de.response,messages:[...ne,...nt]},providerMetadata:de.providerMetadata});await Fr({event:Je,callbacks:[re,M.onStepFinish]}),yp({warnings:J,provider:Y.provider,model:Y.modelId}),Q.push(Je),ne.push(...nt),B.resolve()}de.type==="finish"&&(A=de.totalUsage,be=de.finishReason,W=de.rawFinishReason)},async flush(Ae){var ft,It,er,yr,vr,de,nt;try{if(Q.length===0){const We=s?.aborted?s.reason:new Av({message:"No output generated. Check the stream for errors."});$._finishReason.reject(We),$._rawFinishReason.reject(We),$._totalUsage.reject(We),$._steps.reject(We);return}const Je=be??"other",kt=A??bp();$._finishReason.resolve(Je),$._rawFinishReason.resolve(W),$._totalUsage.resolve(kt),$._steps.resolve(Q);const De=Q[Q.length-1];await Fr({event:{stepNumber:De.stepNumber,model:De.model,functionId:De.functionId,metadata:De.metadata,experimental_context:De.experimental_context,finishReason:De.finishReason,rawFinishReason:De.rawFinishReason,totalUsage:kt,usage:De.usage,content:De.content,text:De.text,reasoningText:De.reasoningText,reasoning:De.reasoning,files:De.files,sources:De.sources,toolCalls:De.toolCalls,staticToolCalls:De.staticToolCalls,dynamicToolCalls:De.dynamicToolCalls,toolResults:De.toolResults,staticToolResults:De.staticToolResults,dynamicToolResults:De.dynamicToolResults,request:De.request,response:De.response,warnings:De.warnings,providerMetadata:De.providerMetadata,steps:Q},callbacks:[H,M.onFinish]}),Pe.setAttributes(await Er({telemetry:t,attributes:{"ai.response.finishReason":Je,"ai.response.text":{output:()=>De.text},"ai.response.reasoning":{output:()=>De.reasoningText},"ai.response.toolCalls":{output:()=>{var We;return(We=De.toolCalls)!=null&&We.length?JSON.stringify(De.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(De.providerMetadata),"ai.usage.inputTokens":kt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ft=kt.inputTokenDetails)==null?void 0:ft.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(It=kt.inputTokenDetails)==null?void 0:It.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(er=kt.inputTokenDetails)==null?void 0:er.cacheWriteTokens,"ai.usage.outputTokens":kt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(yr=kt.outputTokenDetails)==null?void 0:yr.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(vr=kt.outputTokenDetails)==null?void 0:vr.reasoningTokens,"ai.usage.totalTokens":kt.totalTokens,"ai.usage.reasoningTokens":(de=kt.outputTokenDetails)==null?void 0:de.reasoningTokens,"ai.usage.cachedInputTokens":(nt=kt.inputTokenDetails)==null?void 0:nt.cacheReadTokens}}))}catch(Je){Ae.error(Je)}finally{Pe.end()}}}),ae=kR();this.addStream=ae.addStream,this.closeStream=ae.close;const rt=ae.stream.getReader();let _e=new ReadableStream({async start(Ae){Ae.enqueue({type:"start"})},async pull(Ae){function ft(){ee?.({steps:Q}),Ae.enqueue({type:"abort",...s?.reason!==void 0?{reason:uo(s.reason)}:{}}),Ae.close()}try{const{done:It,value:er}=await rt.read();if(It){Ae.close();return}if(s?.aborted){ft();return}Ae.enqueue(er)}catch(It){ho(It)&&s?.aborted?ft():Ae.error(It)}},cancel(Ae){return ae.stream.cancel(Ae)}});for(const Ae of _)_e=_e.pipeThrough(Ae({tools:h,stopStream(){ae.terminate()}}));this.baseStream=_e.pipeThrough(CR(y??Zl())).pipeThrough(gt);const{maxRetries:ue,retry:Ie}=b_({maxRetries:o,abortSignal:s}),ce=m_(t),te=_p(n),Ce=h_({model:e,telemetry:t,headers:r,settings:{...te,maxRetries:ue}}),$=this,Y={provider:e.provider,modelId:e.modelId},Fe={functionId:t?.functionId,metadata:t?.metadata};Ta({name:"ai.streamText",attributes:Er({telemetry:t,attributes:{...ka({operationId:"ai.streamText",telemetry:t}),...Ce,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:f,messages:p})}}}),tracer:ce,endWhenDone:!1,fn:async Ae=>{Pe=Ae;const ft=await p_({system:u,prompt:f,messages:p});await Fr({event:{model:Y,system:u,prompt:f,messages:p,tools:h,toolChoice:m,activeTools:g,maxOutputTokens:te.maxOutputTokens,temperature:te.temperature,topP:te.topP,topK:te.topK,presencePenalty:te.presencePenalty,frequencyPenalty:te.frequencyPenalty,stopSequences:te.stopSequences,seed:te.seed,maxRetries:ue,timeout:C,headers:r,providerOptions:S,stopWhen:L,output:y,abortSignal:O,include:Z,...Fe,experimental_context:E},callbacks:[X,M.onStart]});const It=ft.messages,er=[],{approvedToolApprovals:yr,deniedToolApprovals:vr}=k_({messages:It});if(vr.length>0||yr.length>0){const nt=[...yr,...vr].filter(qe=>qe.toolCall.providerExecuted),Je=yr.filter(qe=>!qe.toolCall.providerExecuted),kt=vr.filter(qe=>!qe.toolCall.providerExecuted),De=vr.filter(qe=>qe.toolCall.providerExecuted);let We;const Zn=new ReadableStream({start(qe){We=qe}});$.addStream(Zn);try{for(const ut of[...kt,...De])We?.enqueue({type:"tool-output-denied",toolCallId:ut.toolCall.toolCallId,toolName:ut.toolCall.toolName});const qe=[];if(await Promise.all(Je.map(async ut=>{const Tt=await kp({toolCall:ut.toolCall,tools:h,tracer:ce,telemetry:t,messages:It,abortSignal:s,experimental_context:E,stepNumber:Q.length,model:Y,onToolCallStart:[ie,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish],onPreliminaryToolResult:St=>{We?.enqueue(St)}});Tt!=null&&(We?.enqueue(Tt),qe.push(Tt))})),nt.length>0&&er.push({role:"tool",content:nt.map(ut=>({type:"tool-approval-response",approvalId:ut.approvalResponse.approvalId,approved:ut.approvalResponse.approved,reason:ut.approvalResponse.reason,providerExecuted:!0}))}),qe.length>0||kt.length>0){const ut=[];for(const Tt of qe)ut.push({type:"tool-result",toolCallId:Tt.toolCallId,toolName:Tt.toolName,output:await wa({toolCallId:Tt.toolCallId,input:Tt.input,tool:h?.[Tt.toolName],output:Tt.type==="tool-result"?Tt.output:Tt.error,errorMode:Tt.type==="tool-error"?"text":"none"})});for(const Tt of kt)ut.push({type:"tool-result",toolCallId:Tt.toolCall.toolCallId,toolName:Tt.toolCall.toolName,output:{type:"execution-denied",reason:Tt.approvalResponse.reason}});er.push({role:"tool",content:ut})}}finally{We?.close()}}ne.push(...er);async function de({currentStep:nt,responseMessages:Je,usage:kt}){var De,We,Zn,qe,ut,Tt,St,Bt,Ze;const cr=$.includeRawChunks,Fn=a!=null?setTimeout(()=>i.abort(),a):void 0;let Sn;function uc(){l!=null&&(Sn!=null&&clearTimeout(Sn),Sn=setTimeout(()=>c.abort(),l))}function xo(){Sn!=null&&(clearTimeout(Sn),Sn=void 0)}function ds(){Fn!=null&&clearTimeout(Fn)}try{B=new da;const Vn=[...It,...Je],$t=await b?.({model:e,steps:Q,stepNumber:Q.length,messages:Vn,experimental_context:E}),Jr=Ll((De=$t?.model)!=null?De:e),Hn={provider:Jr.provider,modelId:Jr.modelId},ps=await s_({prompt:{system:(We=$t?.system)!=null?We:ft.system,messages:(Zn=$t?.messages)!=null?Zn:Vn},supportedUrls:await Jr.supportedUrls,download:U}),dc=(qe=$t?.activeTools)!=null?qe:g,{toolChoice:Io,tools:qa}=await l_({tools:h,toolChoice:(ut=$t?.toolChoice)!=null?ut:m,activeTools:dc});E=(Tt=$t?.experimental_context)!=null?Tt:E;const Kp=(St=$t?.messages)!=null?St:Vn,Yp=(Bt=$t?.system)!=null?Bt:ft.system,ja=Ul(S,$t?.providerOptions);await Fr({event:{stepNumber:Q.length,model:Hn,system:Yp,messages:Kp,tools:h,toolChoice:Io,activeTools:dc,steps:[...Q],providerOptions:ja,timeout:C,headers:r,stopWhen:L,output:y,abortSignal:O,include:Z,...Fe,experimental_context:E},callbacks:[V,M.onStepStart]});const{result:{stream:Ve,response:Jt,request:$o},doStreamSpan:_r,startTimestampMs:La}=await Ie(()=>Ta({name:"ai.streamText.doStream",attributes:Er({telemetry:t,attributes:{...ka({operationId:"ai.streamText.doStream",telemetry:t}),...Ce,"ai.model.provider":Jr.provider,"ai.model.id":Jr.modelId,"ai.prompt.messages":{input:()=>y_(ps)},"ai.prompt.tools":{input:()=>qa?.map(Me=>JSON.stringify(Me))},"ai.prompt.toolChoice":{input:()=>Io!=null?JSON.stringify(Io):void 0},"gen_ai.system":Jr.provider,"gen_ai.request.model":Jr.modelId,"gen_ai.request.frequency_penalty":te.frequencyPenalty,"gen_ai.request.max_tokens":te.maxOutputTokens,"gen_ai.request.presence_penalty":te.presencePenalty,"gen_ai.request.stop_sequences":te.stopSequences,"gen_ai.request.temperature":te.temperature,"gen_ai.request.top_k":te.topK,"gen_ai.request.top_p":te.topP}}),tracer:ce,endWhenDone:!1,fn:async Me=>({startTimestampMs:x(),doStreamSpan:Me,result:await Jr.doStream({...te,tools:qa,toolChoice:Io,responseFormat:await y?.responseFormat,prompt:ps,providerOptions:ja,abortSignal:s,headers:r,includeRawChunks:cr})})})),pc=TR({tools:h,generatorStream:Ve,tracer:ce,telemetry:t,system:u,messages:Vn,repairToolCall:w,abortSignal:s,experimental_context:E,generateId:R,stepNumber:Q.length,model:Hn,onToolCallStart:[ie,M.onToolCallStart],onToolCallFinish:[D,M.onToolCallFinish]}),fc=(Ze=Z?.requestBody)==null||Ze?$o??{}:{...$o,body:void 0},Bn=[],Jn=[];let fs;const dt={};let wr="other",Da,Pt=bp(),Qw,Xw=!0,sn={id:R(),timestamp:new Date,modelId:Y.modelId},PN="";$.addStream(pc.pipeThrough(new TransformStream({async transform(Me,At){var Ua,za,Za,Fa,Va;if(uc(),Me.type==="stream-start"){fs=Me.warnings;return}if(Xw){const Mt=x()-La;Xw=!1,_r.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Mt}),_r.setAttributes({"ai.response.msToFirstChunk":Mt}),At.enqueue({type:"start-step",request:fc,warnings:fs??[]})}const Ha=Me.type;switch(Ha){case"tool-approval-request":case"text-start":case"text-end":{At.enqueue(Me);break}case"text-delta":{Me.delta.length>0&&(At.enqueue({type:"text-delta",id:Me.id,text:Me.delta,providerMetadata:Me.providerMetadata}),PN+=Me.delta);break}case"reasoning-start":case"reasoning-end":{At.enqueue(Me);break}case"reasoning-delta":{At.enqueue({type:"reasoning-delta",id:Me.id,text:Me.delta,providerMetadata:Me.providerMetadata});break}case"tool-call":{At.enqueue(Me),Bn.push(Me);break}case"tool-result":{At.enqueue(Me),Me.preliminary||Jn.push(Me);break}case"tool-error":{At.enqueue(Me),Jn.push(Me);break}case"response-metadata":{sn={id:(Ua=Me.id)!=null?Ua:sn.id,timestamp:(za=Me.timestamp)!=null?za:sn.timestamp,modelId:(Za=Me.modelId)!=null?Za:sn.modelId};break}case"finish":{Pt=Me.usage,wr=Me.finishReason,Da=Me.rawFinishReason,Qw=Me.providerMetadata;const Mt=x()-La;_r.addEvent("ai.stream.finish"),_r.setAttributes({"ai.response.msToFinish":Mt,"ai.response.avgOutputTokensPerSecond":1e3*((Fa=Pt.outputTokens)!=null?Fa:0)/Mt});break}case"file":{At.enqueue(Me);break}case"source":{At.enqueue(Me);break}case"tool-input-start":{dt[Me.id]=Me.toolName;const Mt=h?.[Me.toolName];Mt?.onInputStart!=null&&await Mt.onInputStart({toolCallId:Me.id,messages:Vn,abortSignal:s,experimental_context:E}),At.enqueue({...Me,dynamic:(Va=Me.dynamic)!=null?Va:Mt?.type==="dynamic",title:Mt?.title});break}case"tool-input-end":{delete dt[Me.id],At.enqueue(Me);break}case"tool-input-delta":{const Mt=dt[Me.id],hs=h?.[Mt];hs?.onInputDelta!=null&&await hs.onInputDelta({inputTextDelta:Me.delta,toolCallId:Me.id,messages:Vn,abortSignal:s,experimental_context:E}),At.enqueue(Me);break}case"error":{At.enqueue(Me),wr="error";break}case"raw":{cr&&At.enqueue(Me);break}default:{const Mt=Ha;throw new Error(`Unknown chunk type: ${Mt}`)}}},async flush(Me){var At,Ua,za,Za,Fa,Va,Ha;const Mt=Bn.length>0?JSON.stringify(Bn):void 0;try{_r.setAttributes(await Er({telemetry:t,attributes:{"ai.response.finishReason":wr,"ai.response.toolCalls":{output:()=>Mt},"ai.response.id":sn.id,"ai.response.model":sn.modelId,"ai.response.timestamp":sn.timestamp.toISOString(),"ai.usage.inputTokens":Pt.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(At=Pt.inputTokenDetails)==null?void 0:At.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(Ua=Pt.inputTokenDetails)==null?void 0:Ua.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(za=Pt.inputTokenDetails)==null?void 0:za.cacheWriteTokens,"ai.usage.outputTokens":Pt.outputTokens,"ai.usage.outputTokenDetails.textTokens":(Za=Pt.outputTokenDetails)==null?void 0:Za.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Fa=Pt.outputTokenDetails)==null?void 0:Fa.reasoningTokens,"ai.usage.totalTokens":Pt.totalTokens,"ai.usage.reasoningTokens":(Va=Pt.outputTokenDetails)==null?void 0:Va.reasoningTokens,"ai.usage.cachedInputTokens":(Ha=Pt.inputTokenDetails)==null?void 0:Ha.cacheReadTokens,"gen_ai.response.finish_reasons":[wr],"gen_ai.response.id":sn.id,"gen_ai.response.model":sn.modelId,"gen_ai.usage.input_tokens":Pt.inputTokens,"gen_ai.usage.output_tokens":Pt.outputTokens}}))}catch{}Me.enqueue({type:"finish-step",finishReason:wr,rawFinishReason:Da,usage:Pt,providerMetadata:Qw,response:{...sn,headers:Jt?.headers}});const hs=__(kt,Pt);await B.promise;const Qp=Q[Q.length-1];try{_r.setAttributes(await Er({telemetry:t,attributes:{"ai.response.text":{output:()=>Qp.text},"ai.response.reasoning":{output:()=>Qp.reasoningText},"ai.response.providerMetadata":JSON.stringify(Qp.providerMetadata)}}))}catch{}finally{_r.end()}const eb=Bn.filter(Zt=>Zt.providerExecuted!==!0),MN=Jn.filter(Zt=>Zt.providerExecuted!==!0);for(const Zt of Bn){if(Zt.providerExecuted!==!0)continue;const Xp=h?.[Zt.toolName];Xp?.type==="provider"&&Xp.supportsDeferredResults&&(Jn.some(ef=>(ef.type==="tool-result"||ef.type==="tool-error")&&ef.toolCallId===Zt.toolCallId)||he.set(Zt.toolCallId,{toolName:Zt.toolName}))}for(const Zt of Jn)(Zt.type==="tool-result"||Zt.type==="tool-error")&&he.delete(Zt.toolCallId);if(ds(),xo(),(eb.length>0&&MN.length===eb.length||he.size>0)&&!await P_({stopConditions:v,steps:Q})){Je.push(...await Sp({content:Q[Q.length-1].content,tools:h}));try{await de({currentStep:nt+1,responseMessages:Je,usage:hs})}catch(Zt){Me.enqueue({type:"error",error:Zt}),$.closeStream()}}else Me.enqueue({type:"finish",finishReason:wr,rawFinishReason:Da,totalUsage:hs}),$.closeStream()}})))}finally{ds(),xo()}}await de({currentStep:0,responseMessages:er,usage:bp()})}}).catch(Ae=>{$.addStream(new ReadableStream({start(ft){ft.enqueue({type:"error",error:Ae}),ft.close()}})),$.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Ca(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Ca(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await bR({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return Ca(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new Qr({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Ca(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:Zl()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:a=!0,sendFinish:i=!0,onError:l=uo}={}){const c=t!=null?hR({originalMessages:e,responseMessageId:t}):void 0,u=p=>{var h;const m=(h=this.tools)==null?void 0:h[p.toolName];return m==null?p.dynamic:m?.type==="dynamic"?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(p,h)=>{const m=n?.({part:p}),_=p.type;switch(_){case"text-start":{h.enqueue({type:"text-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-start":{h.enqueue({type:"reasoning-start",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-delta":{o&&h.enqueue({type:"reasoning-delta",id:p.id,delta:p.text,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"reasoning-end":{h.enqueue({type:"reasoning-end",id:p.id,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:p.file.mediaType,url:`data:${p.file.mediaType};base64,${p.file.base64}`,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"source":{s&&p.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:p.id,url:p.url,title:p.title,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}}),s&&p.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:p.id,mediaType:p.mediaType,title:p.title,filename:p.filename,...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{}});break}case"tool-input-start":{const g=u(p);h.enqueue({type:"tool-input-start",toolCallId:p.id,toolName:p.toolName,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...g!=null?{dynamic:g}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:p.id,inputTextDelta:p.delta});break}case"tool-call":{const g=u(p);p.invalid?h.enqueue({type:"tool-input-error",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...g!=null?{dynamic:g}:{},errorText:l(p.error),...p.title!=null?{title:p.title}:{}}):h.enqueue({type:"tool-input-available",toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...g!=null?{dynamic:g}:{},...p.title!=null?{title:p.title}:{}});break}case"tool-approval-request":{h.enqueue({type:"tool-approval-request",approvalId:p.approvalId,toolCallId:p.toolCall.toolCallId});break}case"tool-result":{const g=u(p);h.enqueue({type:"tool-output-available",toolCallId:p.toolCallId,output:p.output,...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...p.preliminary!=null?{preliminary:p.preliminary}:{},...g!=null?{dynamic:g}:{}});break}case"tool-error":{const g=u(p);h.enqueue({type:"tool-output-error",toolCallId:p.toolCallId,errorText:p.providerExecuted?typeof p.error=="string"?p.error:JSON.stringify(p.error):l(p.error),...p.providerExecuted!=null?{providerExecuted:p.providerExecuted}:{},...p.providerMetadata!=null?{providerMetadata:p.providerMetadata}:{},...g!=null?{dynamic:g}:{}});break}case"tool-output-denied":{h.enqueue({type:"tool-output-denied",toolCallId:p.toolCallId});break}case"error":{h.enqueue({type:"error",errorText:l(p.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{a&&h.enqueue({type:"start",...m!=null?{messageMetadata:m}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&h.enqueue({type:"finish",finishReason:p.finishReason,...m!=null?{messageMetadata:m}:{}});break}case"abort":{h.enqueue(p);break}case"tool-input-end":break;case"raw":break;default:{const g=_;throw new Error(`Unknown chunk type: ${g}`)}}m!=null&&_!=="start"&&_!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:m})}}));return Ca(_R({stream:f,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c,...u}={}){wR({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:a,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){pR({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l,...c}={}){return fR({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:a,sendStart:i,onError:l}),...c})}toTextStreamResponse(e){return dR({textStream:this.textStream,...e})}};pa({prefix:"aiobj",size:24}),pa({prefix:"aiobj",size:24});var IR="AI_MCPClientError",Z_=`vercel.ai.error.${IR}`,$R=Symbol.for(Z_),F_,V_,Xe=class extends(V_=Re,F_=$R,V_){constructor({name:e="MCPClientError",message:t,cause:r,data:n,code:o}){super({name:e,message:t,cause:r}),this[F_]=!0,this.data=n,this.code=o}static isInstance(e){return Re.hasMarker(e,Z_)}},is="2025-11-25",ER=[is,"2025-06-18","2025-03-26","2024-11-05"],RR=ve(Se(d(),Ne())),PR=vt({name:d(),version:d()}),Vl=vt({_meta:ve(k({}).loose())}),bn=Vl,H_=k({method:d(),params:ve(Vl)}),B_=k({applyDefaults:ve(Te())}).loose(),MR=vt({experimental:ve(k({}).loose()),logging:ve(k({}).loose()),prompts:ve(vt({listChanged:ve(Te())})),resources:ve(vt({subscribe:ve(Te()),listChanged:ve(Te())})),tools:ve(vt({listChanged:ve(Te())})),elicitation:ve(B_)});k({elicitation:ve(B_)}).loose();var OR=bn.extend({protocolVersion:d(),capabilities:MR,serverInfo:PR,instructions:ve(d())}),Ip=bn.extend({nextCursor:ve(d())}),NR=k({name:d(),title:ve(d()),description:ve(d()),inputSchema:k({type:P("object"),properties:ve(k({}).loose())}).loose(),outputSchema:ve(k({}).loose()),annotations:ve(k({title:ve(d())}).loose()),_meta:RR}).loose(),AR=Ip.extend({tools:j(NR)}),J_=k({type:P("text"),text:d()}).loose(),W_=k({type:P("image"),data:Nm(),mimeType:d()}).loose(),qR=k({uri:d(),name:d(),title:ve(d()),description:ve(d()),mimeType:ve(d()),size:ve(N())}).loose(),jR=Ip.extend({resources:j(qR)}),G_=k({uri:d(),name:ve(d()),title:ve(d()),mimeType:ve(d())}).loose(),K_=G_.extend({text:d()}),Y_=G_.extend({blob:Nm()}),Q_=k({type:P("resource"),resource:le([K_,Y_])}).loose(),LR=bn.extend({content:j(le([J_,W_,Q_])),structuredContent:ve(Ne()),isError:Te().default(!1).optional()}).or(bn.extend({toolResult:Ne()})),DR=k({uriTemplate:d(),name:d(),title:ve(d()),description:ve(d()),mimeType:ve(d())}).loose(),UR=bn.extend({resourceTemplates:j(DR)}),zR=bn.extend({contents:j(le([K_,Y_]))}),ZR=k({name:d(),description:ve(d()),required:ve(Te())}).loose(),FR=k({name:d(),title:ve(d()),description:ve(d()),arguments:ve(j(ZR))}).loose(),VR=Ip.extend({prompts:j(FR)}),HR=k({role:le([P("user"),P("assistant")]),content:le([J_,W_,Q_])}).loose(),BR=bn.extend({description:ve(d()),messages:j(HR)}),JR=Vl.extend({message:d(),requestedSchema:Ne()}),X_=H_.extend({method:P("elicitation/create"),params:JR}),WR=bn.extend({action:le([P("accept"),P("decline"),P("cancel")]),content:ve(Se(d(),Ne()))}),Hl="2.0",GR=k({jsonrpc:P(Hl),id:le([d(),N().int()])}).merge(H_).strict(),KR=k({jsonrpc:P(Hl),id:le([d(),N().int()]),result:bn}).strict(),YR=k({jsonrpc:P(Hl),id:le([d(),N().int()]),error:k({code:N().int(),message:d(),data:ve(Ne())})}).strict(),QR=k({jsonrpc:P(Hl)}).merge(k({method:d(),params:ve(Vl)})).strict(),xa=le([GR,QR,KR,YR]),e1=typeof __PACKAGE_VERSION__<"u"?__PACKAGE_VERSION__:"0.0.0-test",t1=k({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:N().optional(),scope:d().optional(),refresh_token:d().optional()}).strip(),lr=d().url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Vm.custom,message:"URL must be parseable",fatal:!0}),zh}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),XR=k({resource:d().url(),authorization_servers:j(lr).optional(),jwks_uri:d().url().optional(),scopes_supported:j(d()).optional(),bearer_methods_supported:j(d()).optional(),resource_signing_alg_values_supported:j(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:Te().optional(),authorization_details_types_supported:j(d()).optional(),dpop_signing_alg_values_supported:j(d()).optional(),dpop_bound_access_tokens_required:Te().optional()}).passthrough(),r1=k({issuer:d(),authorization_endpoint:lr,token_endpoint:lr,registration_endpoint:lr.optional(),scopes_supported:j(d()).optional(),response_types_supported:j(d()),grant_types_supported:j(d()).optional(),code_challenge_methods_supported:j(d()),token_endpoint_auth_methods_supported:j(d()).optional(),token_endpoint_auth_signing_alg_values_supported:j(d()).optional()}).passthrough(),e7=k({issuer:d(),authorization_endpoint:lr,token_endpoint:lr,userinfo_endpoint:lr.optional(),jwks_uri:lr,registration_endpoint:lr.optional(),scopes_supported:j(d()).optional(),response_types_supported:j(d()),grant_types_supported:j(d()).optional(),subject_types_supported:j(d()),id_token_signing_alg_values_supported:j(d()),claims_supported:j(d()).optional(),token_endpoint_auth_methods_supported:j(d()).optional()}).passthrough(),t7=e7.merge(r1.pick({code_challenge_methods_supported:!0})),r7=k({client_id:d(),client_secret:d().optional(),client_id_issued_at:N().optional(),client_secret_expires_at:N().optional()}).strip(),n7=k({redirect_uris:j(lr),token_endpoint_auth_method:d().optional(),grant_types:j(d()).optional(),response_types:j(d()).optional(),client_name:d().optional(),client_uri:lr.optional(),logo_uri:lr.optional(),scope:d().optional(),contacts:j(d()).optional(),tos_uri:lr.optional(),policy_uri:d().optional(),jwks_uri:lr.optional(),jwks:xt().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),o7=k({error:d(),error_description:d().optional(),error_uri:d().optional()}),s7=n7.merge(r7),a7="AI_MCPClientOAuthError",n1=`vercel.ai.error.${a7}`,i7=Symbol.for(n1),o1,s1,Ia=class extends(s1=Re,o1=i7,s1){constructor({name:e="MCPClientOAuthError",message:t,cause:r}){super({name:e,message:t,cause:r}),this[o1]=!0}static isInstance(e){return Re.hasMarker(e,n1)}},ls=class extends Ia{};ls.errorCode="server_error";var Bl=class extends Ia{};Bl.errorCode="invalid_client";var Jl=class extends Ia{};Jl.errorCode="invalid_grant";var Wl=class extends Ia{};Wl.errorCode="unauthorized_client";var l7={[ls.errorCode]:ls,[Bl.errorCode]:Bl,[Jl.errorCode]:Jl,[Wl.errorCode]:Wl};function c7(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function $p(e){const t=e.href;return e.pathname==="/"&&t.endsWith("/")?t.slice(0,-1):t}function u7({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var Gl=class extends Error{constructor(e="Unauthorized"){super(e),this.name="UnauthorizedError"}};function Kl(e){var t;const r=(t=e.headers.get("www-authenticate"))!=null?t:e.headers.get("WWW-Authenticate");if(!r)return;const[n,o]=r.split(" ");if(n.toLowerCase()!=="bearer"||!o)return;const s=/resource_metadata="([^"]*)"/,a=r.match(s);if(a)try{return new URL(a[1])}catch{return}}function d7(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Ep(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Ep(e,void 0,r):void 0;throw n}}async function a1(e,t,r=fetch){return await Ep(e,{"MCP-Protocol-Version":t},r)}function p7(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function f7(e,t,r,n){var o,s;const a=new URL(e),i=(o=n?.protocolVersion)!=null?o:is;let l;if(n?.metadataUrl)l=new URL(n.metadataUrl);else{const u=d7(t,a.pathname);l=new URL(u,(s=n?.metadataServerUrl)!=null?s:a),l.search=a.search}let c=await a1(l,i,r);if(!n?.metadataUrl&&p7(c,a.pathname)){const u=new URL(`/.well-known/${t}`,a);c=await a1(u,i,r)}return c}async function h7(e,t,r=fetch){const n=await f7(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return XR.parse(await n.json())}function m7(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function g7(e,{fetchFn:t=fetch,protocolVersion:r=is}={}){var n;const o={"MCP-Protocol-Version":r},s=m7(e);for(const{url:a,type:i}of s){const l=await Ep(a,o,t);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}if(i==="oauth")return r1.parse(await l.json());{const c=t7.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 y7(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:a}){const i="code",l="S256";let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!t.code_challenge_methods_supported||!t.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else c=new URL("/authorize",e);const u=await W0(),f=u.code_verifier,p=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(n)),s&&c.searchParams.set("state",s),o&&c.searchParams.set("scope",o),o?.includes("offline_access")&&c.searchParams.append("prompt","consent"),a&&c.searchParams.set("resource",$p(a)),{authorizationUrl:c,codeVerifier:f}}function i1(e,t){const r=e.client_secret!==void 0;return t.length===0?r?"client_secret_post":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function l1(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":v7(o,s,r);return;case"client_secret_post":_7(o,s,n);return;case"none":w7(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function v7(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function _7(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function w7(e,t){t.set("client_id",e)}async function Rp(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=o7.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:a}=n,i=l7[o]||ls;return new i({message:s||"",cause:a})}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ls({message:o})}}async function b7(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:o,redirectUri:s,resource:a,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",f=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e);if(t?.grant_types_supported&&!t.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),h=new URLSearchParams({grant_type:u,code:n,code_verifier:o,redirect_uri:String(s)});if(i)i(p,h,e,t);else{const _=(c=t?.token_endpoint_auth_methods_supported)!=null?c:[],g=i1(r,_);l1(g,r,p,h)}a&&h.set("resource",$p(a));const m=await(l??fetch)(f,{method:"POST",headers:p,body:h});if(!m.ok)throw await Rp(m);return t1.parse(await m.json())}async function k7(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:a}){var i;const l="refresh_token";let c;if(t){if(c=new URL(t.token_endpoint),t.grant_types_supported&&!t.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",e);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),f=new URLSearchParams({grant_type:l,refresh_token:n});if(s)s(u,f,e,t);else{const h=(i=t?.token_endpoint_auth_methods_supported)!=null?i:[],m=i1(r,h);l1(m,r,u,f)}o&&f.set("resource",$p(o));const p=await(a??fetch)(c,{method:"POST",headers:u,body:f});if(!p.ok)throw await Rp(p);return t1.parse({refresh_token:n,...await p.json()})}async function T7(e,{metadata:t,clientMetadata:r,fetchFn:n}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await(n??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Rp(s);return s7.parse(await s.json())}async function Yl(e,t){var r,n;try{return await Pp(e,t)}catch(o){if(o instanceof Bl||o instanceof Wl)return await((r=e.invalidateCredentials)==null?void 0:r.call(e,"all")),await Pp(e,t);if(o instanceof Jl)return await((n=e.invalidateCredentials)==null?void 0:n.call(e,"tokens")),await Pp(e,t);throw o}}async function S7(e,t,r){const n=c7(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!u7({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 Pp(e,{serverUrl:t,authorizationCode:r,callbackState:n,scope:o,resourceMetadataUrl:s,fetchFn:a}){let i,l;try{i=await h7(t,{resourceMetadataUrl:s},a),i.authorization_servers&&i.authorization_servers.length>0&&(l=i.authorization_servers[0])}catch{}l||(l=t);const c=await S7(t,e,i),u=await g7(l,{fetchFn:a});let f=await Promise.resolve(e.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const g=await T7(l,{metadata:u,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(g),f=g}if(r!==void 0){if(e.storedState){const v=await e.storedState();if(v!==void 0&&v!==n)throw new Error("OAuth state parameter mismatch - possible CSRF attack")}const g=await e.codeVerifier(),w=await b7(l,{metadata:u,clientInformation:f,authorizationCode:r,codeVerifier:g,redirectUri:e.redirectUrl,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(w),"AUTHORIZED"}const p=await e.tokens();if(p?.refresh_token)try{const g=await k7(l,{metadata:u,clientInformation:f,refreshToken:p.refresh_token,resource:c,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(g),"AUTHORIZED"}catch(g){if(!(!(g instanceof Ia)||g instanceof ls))throw g}const h=e.state?await e.state():void 0;h&&e.saveState&&await e.saveState(h);const{authorizationUrl:m,codeVerifier:_}=await y7(l,{metadata:u,clientInformation:f,state:h,redirectUrl:e.redirectUrl,scope:o||e.clientMetadata.scope,resource:c});return await e.saveCodeVerifier(_),await e.redirectToAuthorization(m),"REDIRECT"}var C7=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow"}){this.connected=!1,this.url=new URL(e),this.headers=t,this.authProvider=r,this.redirectMode=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":is};if(this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return Dn(t,`ai-sdk/${e1}`,fa())}async start(){return new Promise((e,t)=>{if(this.connected)return e();this.abortController=new AbortController;const r=async(n=!1)=>{var o,s,a,i,l;try{const c=await this.commonHeaders({Accept:"text/event-stream"}),u=await fetch(this.url.href,{headers:c,signal:(o=this.abortController)==null?void 0:o.signal,redirect:this.redirectMode});if(u.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Kl(u);try{if(await Yl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new Gl;return(s=this.onerror)==null||s.call(this,_),t(_)}}catch(m){return(a=this.onerror)==null||a.call(this,m),t(m)}return r(!0)}if(!u.ok||!u.body){let m=`MCP SSE Transport Error: ${u.status} ${u.statusText}`;u.status===405&&(m+=". This server does not support SSE transport. Try using `http` transport instead");const _=new Xe({message:m});return(i=this.onerror)==null||i.call(this,_),t(_)}const p=u.body.pipeThrough(new TextDecoderStream).pipeThrough(new Yo).getReader(),h=async()=>{var m,_,g;try{for(;;){const{done:w,value:v}=await p.read();if(w){if(this.connected)throw this.connected=!1,new Xe({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:y,data:S}=v;if(y==="endpoint"){if(this.endpoint=new URL(S,this.url),this.endpoint.origin!==this.url.origin)throw new Xe({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,e()}else if(y==="message")try{const b=xa.parse(JSON.parse(S));(m=this.onmessage)==null||m.call(this,b)}catch(b){const T=new Xe({message:"MCP SSE Transport Error: Failed to parse message",cause:b});(_=this.onerror)==null||_.call(this,T)}}}catch(w){if(w instanceof Error&&w.name==="AbortError")return;(g=this.onerror)==null||g.call(this,w),t(w)}};this.sseConnection={close:()=>p.cancel()},h()}catch(c){if(c instanceof Error&&c.name==="AbortError")return;(l=this.onerror)==null||l.call(this,c),t(c)}};r()})}async close(){var e,t,r;this.connected=!1,(e=this.sseConnection)==null||e.close(),(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){if(!this.endpoint||!this.connected)throw new Xe({message:"MCP SSE Transport Error: Not connected"});const t=this.endpoint,r=async(n=!1)=>{var o,s,a,i,l;try{const u={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:(o=this.abortController)==null?void 0:o.signal,redirect:this.redirectMode},f=await fetch(t,u);if(f.status===401&&this.authProvider&&!n){this.resourceMetadataUrl=Kl(f);try{if(await Yl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const h=new Gl;(s=this.onerror)==null||s.call(this,h);return}}catch(p){(a=this.onerror)==null||a.call(this,p);return}return r(!0)}if(!f.ok){const p=await f.text().catch(()=>null),h=new Xe({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${f.status}): ${p}`});(i=this.onerror)==null||i.call(this,h);return}}catch(c){(l=this.onerror)==null||l.call(this,c);return}};await r()}},x7=class{constructor({url:e,headers:t,authProvider:r,redirect:n="follow"}){this.inboundReconnectAttempts=0,this.reconnectionOptions={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},this.url=new URL(e),this.headers=t,this.authProvider=r,this.redirectMode=n}async commonHeaders(e){const t={...this.headers,...e,"mcp-protocol-version":is};if(this.sessionId&&(t["mcp-session-id"]=this.sessionId),this.authProvider){const r=await this.authProvider.tokens();r?.access_token&&(t.Authorization=`Bearer ${r.access_token}`)}return Dn(t,`ai-sdk/${e1}`,fa())}async start(){if(this.abortController)throw new Xe({message:"MCP HTTP Transport Error: Transport already started. Note: client.connect() calls start() automatically."});this.abortController=new AbortController,this.openInboundSse()}async close(){var e,t,r;(e=this.inboundSseConnection)==null||e.close();try{if(this.sessionId&&this.abortController&&!this.abortController.signal.aborted){const n=await this.commonHeaders({});await fetch(this.url,{method:"DELETE",headers:n,signal:this.abortController.signal,redirect:this.redirectMode}).catch(()=>{})}}catch{}(t=this.abortController)==null||t.abort(),(r=this.onclose)==null||r.call(this)}async send(e){const t=async(r=!1)=>{var n,o,s,a,i,l,c;try{const f={method:"POST",headers:await this.commonHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(e),signal:(n=this.abortController)==null?void 0:n.signal,redirect:this.redirectMode},p=await fetch(this.url,f),h=p.headers.get("mcp-session-id");if(h&&(this.sessionId=h),p.status===401&&this.authProvider&&!r){this.resourceMetadataUrl=Kl(p);try{if(await Yl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED")throw new Gl}catch(w){throw(o=this.onerror)==null||o.call(this,w),w}return t(!0)}if(p.status===202){this.inboundSseConnection||this.openInboundSse();return}if(!p.ok){const w=await p.text().catch(()=>null);let v=`MCP HTTP Transport Error: POSTing to endpoint (HTTP ${p.status}): ${w}`;p.status===404&&(v+=". This server does not support HTTP transport. Try using `sse` transport instead");const y=new Xe({message:v});throw(s=this.onerror)==null||s.call(this,y),y}if(!("id"in e))return;const _=p.headers.get("content-type")||"";if(_.includes("application/json")){const w=await p.json(),v=Array.isArray(w)?w.map(y=>xa.parse(y)):[xa.parse(w)];for(const y of v)(a=this.onmessage)==null||a.call(this,y);return}if(_.includes("text/event-stream")){if(!p.body){const S=new Xe({message:"MCP HTTP Transport Error: text/event-stream response without body"});throw(i=this.onerror)==null||i.call(this,S),S}const v=p.body.pipeThrough(new TextDecoderStream).pipeThrough(new Yo).getReader();(async()=>{var S,b,T;try{for(;;){const{done:x,value:R}=await v.read();if(x)return;const{event:C,data:L}=R;if(C==="message")try{const O=xa.parse(JSON.parse(L));(S=this.onmessage)==null||S.call(this,O)}catch(O){const q=new Xe({message:"MCP HTTP Transport Error: Failed to parse message",cause:O});(b=this.onerror)==null||b.call(this,q)}}}catch(x){if(x instanceof Error&&x.name==="AbortError")return;(T=this.onerror)==null||T.call(this,x)}})();return}const g=new Xe({message:`MCP HTTP Transport Error: Unexpected content type: ${_}`});throw(l=this.onerror)==null||l.call(this,g),g}catch(u){throw(c=this.onerror)==null||c.call(this,u),u}};await t()}getNextReconnectionDelay(e){const{initialReconnectionDelay:t,reconnectionDelayGrowFactor:r,maxReconnectionDelay:n}=this.reconnectionOptions;return Math.min(t*Math.pow(r,e),n)}scheduleInboundSseReconnection(){var e;const{maxRetries:t}=this.reconnectionOptions;if(t>0&&this.inboundReconnectAttempts>=t){(e=this.onerror)==null||e.call(this,new Xe({message:`MCP HTTP Transport Error: Maximum reconnection attempts (${t}) exceeded.`}));return}const r=this.getNextReconnectionDelay(this.inboundReconnectAttempts);this.inboundReconnectAttempts+=1,setTimeout(async()=>{var n;(n=this.abortController)!=null&&n.signal.aborted||await this.openInboundSse(!1,this.lastInboundEventId)},r)}async openInboundSse(e=!1,t){var r,n,o,s,a,i;try{const l=await this.commonHeaders({Accept:"text/event-stream"});t&&(l["last-event-id"]=t);const c=await fetch(this.url.href,{method:"GET",headers:l,signal:(r=this.abortController)==null?void 0:r.signal,redirect:this.redirectMode}),u=c.headers.get("mcp-session-id");if(u&&(this.sessionId=u),c.status===401&&this.authProvider&&!e){this.resourceMetadataUrl=Kl(c);try{if(await Yl(this.authProvider,{serverUrl:this.url,resourceMetadataUrl:this.resourceMetadataUrl})!=="AUTHORIZED"){const _=new Gl;(n=this.onerror)==null||n.call(this,_);return}}catch(m){(o=this.onerror)==null||o.call(this,m);return}return this.openInboundSse(!0,t)}if(c.status===405)return;if(!c.ok||!c.body){const m=new Xe({message:`MCP HTTP Transport Error: GET SSE failed: ${c.status} ${c.statusText}`});(s=this.onerror)==null||s.call(this,m);return}const p=c.body.pipeThrough(new TextDecoderStream).pipeThrough(new Yo).getReader(),h=async()=>{var m,_,g,w;try{for(;;){const{done:v,value:y}=await p.read();if(v)return;const{event:S,data:b,id:T}=y;if(T&&(this.lastInboundEventId=T),S==="message")try{const x=xa.parse(JSON.parse(b));(m=this.onmessage)==null||m.call(this,x)}catch(x){const R=new Xe({message:"MCP HTTP Transport Error: Failed to parse message",cause:x});(_=this.onerror)==null||_.call(this,R)}}}catch(v){if(v instanceof Error&&v.name==="AbortError")return;(g=this.onerror)==null||g.call(this,v),(w=this.abortController)!=null&&w.signal.aborted||this.scheduleInboundSseReconnection()}};this.inboundSseConnection={close:()=>p.cancel()},this.inboundReconnectAttempts=0,h()}catch(l){if(l instanceof Error&&l.name==="AbortError")return;(a=this.onerror)==null||a.call(this,l),(i=this.abortController)!=null&&i.signal.aborted||this.scheduleInboundSseReconnection()}}};function I7(e){switch(e.type){case"sse":return new C7(e);case"http":return new x7(e);default:throw new Xe({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."})}}function $7(e){return"start"in e&&typeof e.start=="function"&&"send"in e&&typeof e.send=="function"&&"close"in e&&typeof e.close=="function"}var E7="1.0.0";function c1({output:e}){const t=e;return!("content"in t)||!Array.isArray(t.content)?{type:"json",value:t}:{type:"content",value:t.content.map(n=>n.type==="text"&&"text"in n?{type:"text",text:n.text}:n.type==="image"&&"data"in n&&"mimeType"in n?{type:"image-data",data:n.data,mediaType:n.mimeType}:{type:"text",text:JSON.stringify(n)})}}async function R7(e){const t=new P7(e);return await t.init(),t}var P7=class{constructor({transport:e,name:t="ai-sdk-mcp-client",version:r=E7,onUncaughtError:n,capabilities:o}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=n,this.clientCapabilities=o??{},$7(e)?this.transport=e:this.transport=I7(e),this.transport.onclose=()=>this.onClose(),this.transport.onerror=s=>this.onError(s),this.transport.onmessage=s=>{if("method"in s){"id"in s?this.onRequestMessage(s):this.onError(new Xe({message:"Unsupported message type"}));return}this.onResponse(s)},this.clientInfo={name:t,version:r}}async init(){try{await this.transport.start(),this.isClosed=!1;const e=await this.request({request:{method:"initialize",params:{protocolVersion:is,capabilities:this.clientCapabilities,clientInfo:this.clientInfo}},resultSchema:OR});if(e===void 0)throw new Xe({message:"Server sent invalid initialize result"});if(!ER.includes(e.protocolVersion))throw new Xe({message:`Server's protocol version is not supported: ${e.protocolVersion}`});return this.serverCapabilities=e.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(e){throw await this.close(),e}}async close(){var e;this.isClosed||(await((e=this.transport)==null?void 0:e.close()),this.onClose())}assertCapability(e){switch(e){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new Xe({message:"Server does not support tools"});break;case"resources/list":case"resources/read":case"resources/templates/list":if(!this.serverCapabilities.resources)throw new Xe({message:"Server does not support resources"});break;case"prompts/list":case"prompts/get":if(!this.serverCapabilities.prompts)throw new Xe({message:"Server does not support prompts"});break;default:throw new Xe({message:`Unsupported method: ${e}`})}}async request({request:e,resultSchema:t,options:r}){return new Promise((n,o)=>{if(this.isClosed)return o(new Xe({message:"Attempted to send a request from a closed client"}));this.assertCapability(e.method);const s=r?.signal;s?.throwIfAborted();const a=this.requestMessageId++,i={...e,jsonrpc:"2.0",id:a},l=()=>{this.responseHandlers.delete(a)};this.responseHandlers.set(a,c=>{if(s?.aborted)return o(new Xe({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return o(c);try{const u=t.parse(c.result);n(u)}catch(u){const f=new Xe({message:"Failed to parse server response",cause:u});o(f)}}),this.transport.send(i).catch(c=>{l(),o(c)})})}async listTools({params:e,options:t}={}){return this.request({request:{method:"tools/list",params:e},resultSchema:AR,options:t})}async callTool({name:e,args:t,options:r}){try{return this.request({request:{method:"tools/call",params:{name:e,arguments:t}},resultSchema:LR,options:{signal:r?.abortSignal}})}catch(n){throw n}}async listResourcesInternal({params:e,options:t}={}){try{return this.request({request:{method:"resources/list",params:e},resultSchema:jR,options:t})}catch(r){throw r}}async readResourceInternal({uri:e,options:t}){try{return this.request({request:{method:"resources/read",params:{uri:e}},resultSchema:zR,options:t})}catch(r){throw r}}async listResourceTemplatesInternal({options:e}={}){try{return this.request({request:{method:"resources/templates/list"},resultSchema:UR,options:e})}catch(t){throw t}}async listPromptsInternal({params:e,options:t}={}){try{return this.request({request:{method:"prompts/list",params:e},resultSchema:VR,options:t})}catch(r){throw r}}async getPromptInternal({name:e,args:t,options:r}){try{return this.request({request:{method:"prompts/get",params:{name:e,arguments:t}},resultSchema:BR,options:r})}catch(n){throw n}}async notification(e){const t={...e,jsonrpc:"2.0"};await this.transport.send(t)}async tools({schemas:e="automatic"}={}){const t=await this.listTools();return this.toolsFromDefinitions(t,{schemas:e})}toolsFromDefinitions(e,{schemas:t="automatic"}={}){var r,n;const o={};for(const{name:s,title:a,description:i,inputSchema:l,annotations:c,_meta:u}of e.tools){const f=a??c?.title;if(t!=="automatic"&&!(s in t))continue;const p=this,h=t!=="automatic"?(r=t[s])==null?void 0:r.outputSchema:void 0,m=async(g,w)=>{var v;(v=w?.abortSignal)==null||v.throwIfAborted();const y=await p.callTool({name:s,args:g,options:w});return h!=null?p.extractStructuredContent(y,h,s):y},_=t==="automatic"?Qd({description:i,title:f,inputSchema:go({...l,properties:(n=l.properties)!=null?n:{},additionalProperties:!1}),execute:m,toModelOutput:c1}):{description:i,title:f,inputSchema:t[s].inputSchema,...h!=null?{outputSchema:h}:{},execute:m,toModelOutput:c1};o[s]={..._,_meta:u}}return o}async extractStructuredContent(e,t,r){if("structuredContent"in e&&e.structuredContent!=null){const n=await xr({value:e.structuredContent,schema:yo(t)});if(!n.success)throw new Xe({message:`Tool "${r}" returned structuredContent that does not match the expected outputSchema`,cause:n.error});return n.value}if("content"in e&&Array.isArray(e.content)){const n=e.content.find(o=>o.type==="text");if(n&&"text"in n){const o=await Ir({text:n.text,schema:t});if(!o.success)throw new Xe({message:`Tool "${r}" returned content that does not match the expected outputSchema`,cause:o.error});return o.value}}throw new Xe({message:`Tool "${r}" did not return structuredContent or parseable text content`})}listResources({params:e,options:t}={}){return this.listResourcesInternal({params:e,options:t})}readResource({uri:e,options:t}){return this.readResourceInternal({uri:e,options:t})}listResourceTemplates({options:e}={}){return this.listResourceTemplatesInternal({options:e})}experimental_listPrompts({params:e,options:t}={}){return this.listPromptsInternal({params:e,options:t})}experimental_getPrompt({name:e,arguments:t,options:r}){return this.getPromptInternal({name:e,args:t,options:r})}onElicitationRequest(e,t){if(e!==X_)throw new Xe({message:"Unsupported request schema. Only ElicitationRequestSchema is supported."});this.elicitationRequestHandler=t}async onRequestMessage(e){try{if(e.method!=="elicitation/create"){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Unsupported request method: ${e.method}`}});return}if(!this.elicitationRequestHandler){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32601,message:"No elicitation handler registered on client"}});return}const t=X_.safeParse({method:e.method,params:e.params});if(!t.success){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid elicitation request: ${t.error.message}`,data:t.error.issues}});return}try{const r=await this.elicitationRequestHandler(t.data),n=WR.parse(r);await this.transport.send({jsonrpc:"2.0",id:e.id,result:n})}catch(r){await this.transport.send({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Failed to handle elicitation request"}}),this.onError(r)}}catch(t){this.onError(t)}}onClose(){if(this.isClosed)return;this.isClosed=!0;const e=new Xe({message:"Connection closed"});for(const t of this.responseHandlers.values())t(e);this.responseHandlers.clear()}onError(e){this.onUncaughtError&&this.onUncaughtError(e)}onResponse(e){const t=Number(e.id),r=this.responseHandlers.get(t);if(r===void 0)throw new Xe({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(e)}`});this.responseHandlers.delete(t),r("result"in e?e:new Xe({message:e.error.message,code:e.error.code,data:e.error.data,cause:e.error}))}},Mp=k({error:k({message:d(),type:d().nullish(),param:xt().nullish(),code:le([d(),N()]).nullish()})}),Hr=Xr({errorSchema:Mp,errorToMessage:e=>e.error.message});function u1(e){const t=e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),r=e.startsWith("gpt-4")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-nano")&&!e.startsWith("gpt-5-chat")&&!e.startsWith("gpt-5.4-nano")||e.startsWith("o3")||e.startsWith("o4-mini"),n=e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4-mini")||e.startsWith("gpt-5")&&!e.startsWith("gpt-5-chat"),o=e.startsWith("gpt-5.1")||e.startsWith("gpt-5.2")||e.startsWith("gpt-5.3")||e.startsWith("gpt-5.4");return{supportsFlexProcessing:t,supportsPriorityProcessing:r,isReasoningModel:n,systemMessageMode:n?"developer":"system",supportsNonReasoningParameters:o}}function d1(e){var t,r,n,o,s,a;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const i=(t=e.prompt_tokens)!=null?t:0,l=(r=e.completion_tokens)!=null?r:0,c=(o=(n=e.prompt_tokens_details)==null?void 0:n.cached_tokens)!=null?o:0,u=(a=(s=e.completion_tokens_details)==null?void 0:s.reasoning_tokens)!=null?a:0;return{inputTokens:{total:i,noCache:i-c,cacheRead:c,cacheWrite:void 0},outputTokens:{total:l,text:l-u,reasoning:u},raw:e}}function M7({prompt:e,systemMessageMode:t="system"}){var r;const n=[],o=[];for(const{role:s,content:a}of e)switch(s){case"system":{switch(t){case"system":{n.push({role:"system",content:a});break}case"developer":{n.push({role:"developer",content:a});break}case"remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{const i=t;throw new Error(`Unsupported system message mode: ${i}`)}}break}case"user":{if(a.length===1&&a[0].type==="text"){n.push({role:"user",content:a[0].text});break}n.push({role:"user",content:a.map((i,l)=>{var c,u,f;switch(i.type){case"text":return{type:"text",text:i.text};case"file":if(i.mediaType.startsWith("image/")){const p=i.mediaType==="image/*"?"image/jpeg":i.mediaType;return{type:"image_url",image_url:{url:i.data instanceof URL?i.data.toString():`data:${p};base64,${os(i.data)}`,detail:(u=(c=i.providerOptions)==null?void 0:c.openai)==null?void 0:u.imageDetail}}}else if(i.mediaType.startsWith("audio/")){if(i.data instanceof URL)throw new Qr({functionality:"audio file parts with URLs"});switch(i.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:os(i.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:os(i.data),format:"mp3"}};default:throw new Qr({functionality:`audio content parts with media type ${i.mediaType}`})}}else if(i.mediaType==="application/pdf"){if(i.data instanceof URL)throw new Qr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof i.data=="string"&&i.data.startsWith("file-")?{file_id:i.data}:{filename:(f=i.filename)!=null?f:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${os(i.data)}`}}}else throw new Qr({functionality:`file part media type ${i.mediaType}`})}})});break}case"assistant":{let i="";const l=[];for(const c of a)switch(c.type){case"text":{i+=c.text;break}case"tool-call":{l.push({id:c.toolCallId,type:"function",function:{name:c.toolName,arguments:JSON.stringify(c.input)}});break}}n.push({role:"assistant",content:i,tool_calls:l.length>0?l:void 0});break}case"tool":{for(const i of a){if(i.type==="tool-approval-response")continue;const l=i.output;let c;switch(l.type){case"text":case"error-text":c=l.value;break;case"execution-denied":c=(r=l.reason)!=null?r:"Tool execution denied.";break;case"content":case"json":case"error-json":c=JSON.stringify(l.value);break}n.push({role:"tool",tool_call_id:i.toolCallId,content:c})}break}default:{const i=s;throw new Error(`Unsupported role: ${i}`)}}return{messages:n,warnings:o}}function Op({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r?new Date(r*1e3):void 0}}function p1(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var O7=$e(()=>xe(k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:j(k({message:k({role:P("assistant").nullish(),content:d().nullish(),tool_calls:j(k({id:d().nullish(),type:P("function"),function:k({name:d(),arguments:d()})})).nullish(),annotations:j(k({type:P("url_citation"),url_citation:k({start_index:N(),end_index:N(),url:d(),title:d()})})).nullish()}),index:N(),logprobs:k({content:j(k({token:d(),logprob:N(),top_logprobs:j(k({token:d(),logprob:N()}))})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:k({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:k({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:k({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish()}))),N7=$e(()=>xe(le([k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:j(k({delta:k({role:ge(["assistant"]).nullish(),content:d().nullish(),tool_calls:j(k({index:N(),id:d().nullish(),type:P("function").nullish(),function:k({name:d().nullish(),arguments:d().nullish()})})).nullish(),annotations:j(k({type:P("url_citation"),url_citation:k({start_index:N(),end_index:N(),url:d(),title:d()})})).nullish()}).nullish(),logprobs:k({content:j(k({token:d(),logprob:N(),top_logprobs:j(k({token:d(),logprob:N()}))})).nullish()}).nullish(),finish_reason:d().nullish(),index:N()})),usage:k({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:k({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:k({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish()}),Mp]))),A7=$e(()=>xe(k({logitBias:Se(Hm(),N()).optional(),logprobs:le([Te(),N()]).optional(),parallelToolCalls:Te().optional(),user:d().optional(),reasoningEffort:ge(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:N().optional(),store:Te().optional(),metadata:Se(d().max(64),d().max(512)).optional(),prediction:Se(d(),xt()).optional(),serviceTier:ge(["auto","flex","priority","default"]).optional(),strictJsonSchema:Te().optional(),textVerbosity:ge(["low","medium","high"]).optional(),promptCacheKey:d().optional(),promptCacheRetention:ge(["in_memory","24h"]).optional(),safetyIdentifier:d().optional(),systemMessageMode:ge(["system","developer","remove"]).optional(),forceReasoning:Te().optional()})));function q7({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)switch(s.type){case"function":n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema,...s.strict!=null?{strict:s.strict}:{}}});break;default:r.push({type:"unsupported",feature:`tool type: ${s.type}`});break}if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new Qr({functionality:`tool choice type: ${s}`})}}}var j7=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:f,providerOptions:p}){var h,m,_,g,w;const v=[],y=(h=await _n({provider:"openai",providerOptions:p,schema:A7}))!=null?h:{},S=u1(this.modelId),b=(m=y.forceReasoning)!=null?m:S.isReasoningModel;o!=null&&v.push({type:"unsupported",feature:"topK"});const{messages:T,warnings:x}=M7({prompt:e,systemMessageMode:(_=y.systemMessageMode)!=null?_:b?"developer":S.systemMessageMode});v.push(...x);const R=(g=y.strictJsonSchema)!=null?g:!0,C={model:this.modelId,logit_bias:y.logitBias,logprobs:y.logprobs===!0||typeof y.logprobs=="number"?!0:void 0,top_logprobs:typeof y.logprobs=="number"?y.logprobs:typeof y.logprobs=="boolean"&&y.logprobs?0:void 0,user:y.user,parallel_tool_calls:y.parallelToolCalls,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:l?.type==="json"?l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:R,name:(w=l.name)!=null?w:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:y.textVerbosity,max_completion_tokens:y.maxCompletionTokens,store:y.store,metadata:y.metadata,prediction:y.prediction,reasoning_effort:y.reasoningEffort,service_tier:y.serviceTier,prompt_cache_key:y.promptCacheKey,prompt_cache_retention:y.promptCacheRetention,safety_identifier:y.safetyIdentifier,messages:T};b?((y.reasoningEffort!=="none"||!S.supportsNonReasoningParameters)&&(C.temperature!=null&&(C.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),C.top_p!=null&&(C.top_p=void 0,v.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),C.logprobs!=null&&(C.logprobs=void 0,v.push({type:"other",message:"logprobs is not supported for reasoning models"}))),C.frequency_penalty!=null&&(C.frequency_penalty=void 0,v.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),C.presence_penalty!=null&&(C.presence_penalty=void 0,v.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),C.logit_bias!=null&&(C.logit_bias=void 0,v.push({type:"other",message:"logitBias is not supported for reasoning models"})),C.top_logprobs!=null&&(C.top_logprobs=void 0,v.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),C.max_tokens!=null&&(C.max_completion_tokens==null&&(C.max_completion_tokens=C.max_tokens),C.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&C.temperature!=null&&(C.temperature=void 0,v.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),y.serviceTier==="flex"&&!S.supportsFlexProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),C.service_tier=void 0),y.serviceTier==="priority"&&!S.supportsPriorityProcessing&&(v.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),C.service_tier=void 0);const{tools:L,toolChoice:O,toolWarnings:q}=q7({tools:u,toolChoice:f});return{args:{...C,tools:L,tool_choice:O},warnings:[...v,...q]}}async doGenerate(e){var t,r,n,o,s,a,i;const{args:l,warnings:c}=await this.getArgs(e),{responseHeaders:u,value:f,rawValue:p}=await ar({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Vt(this.config.headers(),e.headers),body:l,failedResponseHandler:Hr,successfulResponseHandler:ir(O7),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.choices[0],m=[],_=h.message.content;_!=null&&_.length>0&&m.push({type:"text",text:_});for(const v of(t=h.message.tool_calls)!=null?t:[])m.push({type:"tool-call",toolCallId:(r=v.id)!=null?r:Yt(),toolName:v.function.name,input:v.function.arguments});for(const v of(n=h.message.annotations)!=null?n:[])m.push({type:"source",sourceType:"url",id:Yt(),url:v.url_citation.url,title:v.url_citation.title});const g=(o=f.usage)==null?void 0:o.completion_tokens_details;(s=f.usage)==null||s.prompt_tokens_details;const w={openai:{}};return g?.accepted_prediction_tokens!=null&&(w.openai.acceptedPredictionTokens=g?.accepted_prediction_tokens),g?.rejected_prediction_tokens!=null&&(w.openai.rejectedPredictionTokens=g?.rejected_prediction_tokens),((a=h.logprobs)==null?void 0:a.content)!=null&&(w.openai.logprobs=h.logprobs.content),{content:m,finishReason:{unified:p1(h.finish_reason),raw:(i=h.finish_reason)!=null?i:void 0},usage:d1(f.usage),request:{body:l},response:{...Op(f),headers:u,body:p},warnings:c,providerMetadata:w}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await ar({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Vt(this.config.headers(),e.headers),body:n,failedResponseHandler:Hr,successfulResponseHandler:Nl(N7),abortSignal:e.abortSignal,fetch:this.config.fetch}),a=[];let i={unified:"other",raw:void 0},l,c=!1,u=!1;const f={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(p){p.enqueue({type:"stream-start",warnings:r})},transform(p,h){var m,_,g,w,v,y,S,b,T,x,R,C,L,O,q,z,H;if(e.includeRawChunks&&h.enqueue({type:"raw",rawValue:p.rawValue}),!p.success){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:p.error});return}const ee=p.value;if("error"in ee){i={unified:"error",raw:void 0},h.enqueue({type:"error",error:ee.error});return}if(!c){const V=Op(ee);Object.values(V).some(Boolean)&&(c=!0,h.enqueue({type:"response-metadata",...Op(ee)}))}ee.usage!=null&&(l=ee.usage,((m=ee.usage.completion_tokens_details)==null?void 0:m.accepted_prediction_tokens)!=null&&(f.openai.acceptedPredictionTokens=(_=ee.usage.completion_tokens_details)==null?void 0:_.accepted_prediction_tokens),((g=ee.usage.completion_tokens_details)==null?void 0:g.rejected_prediction_tokens)!=null&&(f.openai.rejectedPredictionTokens=(w=ee.usage.completion_tokens_details)==null?void 0:w.rejected_prediction_tokens));const re=ee.choices[0];if(re?.finish_reason!=null&&(i={unified:p1(re.finish_reason),raw:re.finish_reason}),((v=re?.logprobs)==null?void 0:v.content)!=null&&(f.openai.logprobs=re.logprobs.content),re?.delta==null)return;const X=re.delta;if(X.content!=null&&(u||(h.enqueue({type:"text-start",id:"0"}),u=!0),h.enqueue({type:"text-delta",id:"0",delta:X.content})),X.tool_calls!=null)for(const V of X.tool_calls){const ie=V.index;if(a[ie]==null){if(V.type!=null&&V.type!=="function")throw new Zd({data:V,message:"Expected 'function' type."});if(V.id==null)throw new Zd({data:V,message:"Expected 'id' to be a string."});if(((y=V.function)==null?void 0:y.name)==null)throw new Zd({data:V,message:"Expected 'function.name' to be a string."});h.enqueue({type:"tool-input-start",id:V.id,toolName:V.function.name}),a[ie]={id:V.id,type:"function",function:{name:V.function.name,arguments:(S=V.function.arguments)!=null?S:""},hasFinished:!1};const E=a[ie];((b=E.function)==null?void 0:b.name)!=null&&((T=E.function)==null?void 0:T.arguments)!=null&&(E.function.arguments.length>0&&h.enqueue({type:"tool-input-delta",id:E.id,delta:E.function.arguments}),py(E.function.arguments)&&(h.enqueue({type:"tool-input-end",id:E.id}),h.enqueue({type:"tool-call",toolCallId:(x=E.id)!=null?x:Yt(),toolName:E.function.name,input:E.function.arguments}),E.hasFinished=!0));continue}const D=a[ie];D.hasFinished||(((R=V.function)==null?void 0:R.arguments)!=null&&(D.function.arguments+=(L=(C=V.function)==null?void 0:C.arguments)!=null?L:""),h.enqueue({type:"tool-input-delta",id:D.id,delta:(O=V.function.arguments)!=null?O:""}),((q=D.function)==null?void 0:q.name)!=null&&((z=D.function)==null?void 0:z.arguments)!=null&&py(D.function.arguments)&&(h.enqueue({type:"tool-input-end",id:D.id}),h.enqueue({type:"tool-call",toolCallId:(H=D.id)!=null?H:Yt(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0))}if(X.annotations!=null)for(const V of X.annotations)h.enqueue({type:"source",sourceType:"url",id:Yt(),url:V.url_citation.url,title:V.url_citation.title})},flush(p){u&&p.enqueue({type:"text-end",id:"0"}),p.enqueue({type:"finish",finishReason:i,usage:d1(l),...f!=null?{providerMetadata:f}:{}})}})),request:{body:n},response:{headers:o}}}};function f1(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=(t=e.prompt_tokens)!=null?t:0,a=(r=e.completion_tokens)!=null?r:0;return{inputTokens:{total:(n=e.prompt_tokens)!=null?n:void 0,noCache:s,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(o=e.completion_tokens)!=null?o:void 0,text:a,reasoning:void 0},raw:e}}function L7({prompt:e,user:t="user",assistant:r="assistant"}){let n="";e[0].role==="system"&&(n+=`${e[0].content}
585
585
 
586
- `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new io({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");n+=`${t}:
586
+ `,e=e.slice(1));for(const{role:o,content:s}of e)switch(o){case"system":throw new po({message:"Unexpected system message in prompt: ${content}",prompt:e});case"user":{const a=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");n+=`${t}:
587
587
  ${a}
588
588
 
589
589
  `;break}case"assistant":{const a=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Qr({functionality:"tool-call messages"})}}).join("");n+=`${r}:
@@ -591,9 +591,9 @@ ${a}
591
591
 
592
592
  `;break}case"tool":throw new Qr({functionality:"tool messages"});default:{const a=o;throw new Error(`Unsupported role: ${a}`)}}return n+=`${r}:
593
593
  `,{prompt:n,stopSequences:[`
594
- ${t}:`]}}function p1({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function f1(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var $R=Te(()=>be(T({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d(),logprobs:T({tokens:q(d()),token_logprobs:q(O()),top_logprobs:q(_e(d(),O())).nullish()}).nullish()})),usage:T({prompt_tokens:O(),completion_tokens:O(),total_tokens:O()}).nullish()}))),RR=Te(()=>be(ae([T({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d().nullish(),index:O(),logprobs:T({tokens:q(d()),token_logprobs:q(O()),top_logprobs:q(_e(d(),O())).nullish()}).nullish()})),usage:T({prompt_tokens:O(),completion_tokens:O(),total_tokens:O()}).nullish()}),Ip]))),h1=Te(()=>be(T({echo:ve().optional(),logitBias:_e(d(),O()).optional(),suffix:d().optional(),user:d().optional(),logprobs:ae([ve(),O()]).optional()}))),PR=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:f,providerOptions:p}){const h=[],m={...await gn({provider:"openai",providerOptions:p,schema:h1}),...await gn({provider:this.providerOptionsName,providerOptions:p,schema:h1})};o!=null&&h.push({type:"unsupported",feature:"topK"}),c?.length&&h.push({type:"unsupported",feature:"tools"}),u!=null&&h.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&h.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:_,stopSequences:y}=ER({prompt:e}),w=[...y??[],...i??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:f,prompt:_,stop:w.length>0?w:void 0},warnings:h}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:a}=await nr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:r,failedResponseHandler:Hr,successfulResponseHandler:or($R),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=s.choices[0],l={openai:{}};return i.logprobs!=null&&(l.openai.logprobs=i.logprobs),{content:[{type:"text",text:i.text}],usage:d1(s.usage),finishReason:{unified:f1(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...p1(s),headers:o,body:a},providerMetadata:l,warnings:n}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await nr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:n,failedResponseHandler:Hr,successfulResponseHandler:$l(RR),abortSignal:e.abortSignal,fetch:this.config.fetch});let a={unified:"other",raw:void 0};const i={openai:{}};let l,c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,f){if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...p1(p)}),f.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const h=p.choices[0];h?.finish_reason!=null&&(a={unified:f1(h.finish_reason),raw:h.finish_reason}),h?.logprobs!=null&&(i.openai.logprobs=h.logprobs),h?.text!=null&&h.text.length>0&&f.enqueue({type:"text-delta",id:"0",delta:h.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:d1(l)})}})),request:{body:n},response:{headers:o}}}},MR=Te(()=>be(T({dimensions:O().optional(),user:d().optional()}))),NR=Te(()=>be(T({data:q(T({embedding:q(O())})),usage:T({prompt_tokens:O()}).nullish()}))),OR=class{constructor(e,t){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new v5({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await gn({provider:"openai",providerOptions:n,schema:MR}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await nr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Dt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Hr,successfulResponseHandler:or(NR),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},m1=Te(()=>be(T({created:O().nullish(),data:q(T({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:T({input_tokens:O().nullish(),output_tokens:O().nullish(),total_tokens:O().nullish(),input_tokens_details:T({image_tokens:O().nullish(),text_tokens:O().nullish()}).nullish()}).nullish()}))),AR={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},qR=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function LR(e){return qR.some(t=>e.startsWith(t))}var jR=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=AR[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:r,n,size:o,aspectRatio:s,seed:a,providerOptions:i,headers:l,abortSignal:c}){var u,f,p,h,m,_,y,w,v,g,S;const b=[];s!=null&&b.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&b.push({type:"unsupported",feature:"seed"});const k=(p=(f=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:f.call(u))!=null?p:new Date;if(t!=null){const{value:I,responseHeaders:j}=await dy({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Dt(this.config.headers(),l),formData:C5({model:this.modelId,prompt:e,image:await Promise.all(t.map(N=>N.type==="file"?new Blob([N.data instanceof Uint8Array?new Blob([N.data],{type:N.mediaType}):new Blob([Go(N.data)],{type:N.mediaType})],{type:N.mediaType}):Yg(N.url))),mask:r!=null?await DR(r):void 0,n,size:o,...(h=i.openai)!=null?h:{}}),failedResponseHandler:Hr,successfulResponseHandler:or(m1),abortSignal:c,fetch:this.config.fetch});return{images:I.data.map(N=>N.b64_json),warnings:b,usage:I.usage!=null?{inputTokens:(m=I.usage.input_tokens)!=null?m:void 0,outputTokens:(_=I.usage.output_tokens)!=null?_:void 0,totalTokens:(y=I.usage.total_tokens)!=null?y:void 0}:void 0,response:{timestamp:k,modelId:this.modelId,headers:j},providerMetadata:{openai:{images:I.data.map((N,L)=>{var z,H,ee,te,X,V;return{...N.revised_prompt?{revisedPrompt:N.revised_prompt}:{},created:(z=I.created)!=null?z:void 0,size:(H=I.size)!=null?H:void 0,quality:(ee=I.quality)!=null?ee:void 0,background:(te=I.background)!=null?te:void 0,outputFormat:(X=I.output_format)!=null?X:void 0,...g1((V=I.usage)==null?void 0:V.input_tokens_details,L,I.data.length)}})}}}}const{value:C,responseHeaders:R}=await nr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Dt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=i.openai)!=null?w:{},...LR(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Hr,successfulResponseHandler:or(m1),abortSignal:c,fetch:this.config.fetch});return{images:C.data.map(I=>I.b64_json),warnings:b,usage:C.usage!=null?{inputTokens:(v=C.usage.input_tokens)!=null?v:void 0,outputTokens:(g=C.usage.output_tokens)!=null?g:void 0,totalTokens:(S=C.usage.total_tokens)!=null?S:void 0}:void 0,response:{timestamp:k,modelId:this.modelId,headers:R},providerMetadata:{openai:{images:C.data.map((I,j)=>{var N,L,z,H,ee,te;return{...I.revised_prompt?{revisedPrompt:I.revised_prompt}:{},created:(N=C.created)!=null?N:void 0,size:(L=C.size)!=null?L:void 0,quality:(z=C.quality)!=null?z:void 0,background:(H=C.background)!=null?H:void 0,outputFormat:(ee=C.output_format)!=null?ee:void 0,...g1((te=C.usage)==null?void 0:te.input_tokens_details,j,C.data.length)}})}}}}};function g1(e,t,r){if(e==null)return{};const n={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/r),s=e.image_tokens-o*(r-1);n.imageTokens=t===r-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/r),s=e.text_tokens-o*(r-1);n.textTokens=t===r-1?s:o}return n}async function DR(e){if(!e)return;if(e.type==="url")return Yg(e.url);const t=e.data instanceof Uint8Array?e.data:Go(e.data);return new Blob([t],{type:e.mediaType})}var y1=Te(()=>be(T({callId:d(),operation:Ve("type",[T({type:P("create_file"),path:d(),diff:d()}),T({type:P("delete_file"),path:d()}),T({type:P("update_file"),path:d(),diff:d()})])}))),v1=Te(()=>be(T({status:de(["completed","failed"]),output:d().optional()}))),UR=xr({id:"openai.apply_patch",inputSchema:y1,outputSchema:v1}),zR=UR,ZR=Te(()=>be(T({code:d().nullish(),containerId:d()}))),FR=Te(()=>be(T({outputs:q(Ve("type",[T({type:P("logs"),logs:d()}),T({type:P("image"),url:d()})])).nullish()}))),VR=Te(()=>be(T({container:ae([d(),T({fileIds:q(d()).optional()})]).optional()}))),HR=xr({id:"openai.code_interpreter",inputSchema:ZR,outputSchema:FR}),BR=(e={})=>HR(e),WR=Te(()=>be(T({name:d(),description:d().optional(),format:ae([T({type:P("grammar"),syntax:de(["regex","lark"]),definition:d()}),T({type:P("text")})]).optional()}))),GR=Te(()=>be(d())),JR=Px({id:"openai.custom",inputSchema:GR}),KR=e=>JR(e),_1=T({key:d(),type:de(["eq","ne","gt","gte","lt","lte","in","nin"]),value:ae([d(),O(),ve(),q(d())])}),w1=T({type:de(["and","or"]),filters:q(ae([_1,Gi(()=>w1)]))}),YR=Te(()=>be(T({vectorStoreIds:q(d()),maxNumResults:O().optional(),ranking:T({ranker:d().optional(),scoreThreshold:O().optional()}).optional(),filters:ae([_1,w1]).optional()}))),QR=Te(()=>be(T({queries:q(d()),results:q(T({attributes:_e(d(),xe()),fileId:d(),filename:d(),score:O(),text:d()})).nullable()}))),XR=xr({id:"openai.file_search",inputSchema:T({}),outputSchema:QR}),eP=Te(()=>be(T({background:de(["auto","opaque","transparent"]).optional(),inputFidelity:de(["low","high"]).optional(),inputImageMask:T({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:de(["auto"]).optional(),outputCompression:O().int().min(0).max(100).optional(),outputFormat:de(["png","jpeg","webp"]).optional(),partialImages:O().int().min(0).max(3).optional(),quality:de(["auto","low","medium","high"]).optional(),size:de(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),tP=Te(()=>be(T({}))),rP=Te(()=>be(T({result:d()}))),nP=xr({id:"openai.image_generation",inputSchema:tP,outputSchema:rP}),oP=(e={})=>nP(e),b1=Te(()=>be(T({action:T({type:P("exec"),command:q(d()),timeoutMs:O().optional(),user:d().optional(),workingDirectory:d().optional(),env:_e(d(),d()).optional()})}))),T1=Te(()=>be(T({output:d()}))),sP=xr({id:"openai.local_shell",inputSchema:b1,outputSchema:T1}),k1=Te(()=>be(T({action:T({commands:q(d()),timeoutMs:O().optional(),maxOutputLength:O().optional()})}))),Ep=Te(()=>be(T({output:q(T({stdout:d(),stderr:d(),outcome:Ve("type",[T({type:P("timeout")}),T({type:P("exit"),exitCode:O()})])}))}))),aP=q(Ve("type",[T({type:P("skillReference"),skillId:d(),version:d().optional()}),T({type:P("inline"),name:d(),description:d(),source:T({type:P("base64"),mediaType:P("application/zip"),data:d()})})])).optional(),iP=Te(()=>be(T({environment:ae([T({type:P("containerAuto"),fileIds:q(d()).optional(),memoryLimit:de(["1g","4g","16g","64g"]).optional(),networkPolicy:Ve("type",[T({type:P("disabled")}),T({type:P("allowlist"),allowedDomains:q(d()),domainSecrets:q(T({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:aP}),T({type:P("containerReference"),containerId:d()}),T({type:P("local").optional(),skills:q(T({name:d(),description:d(),path:d()})).optional()})]).optional()}))),lP=xr({id:"openai.shell",inputSchema:k1,outputSchema:Ep}),cP=Te(()=>be(T({execution:de(["server","client"]).optional(),description:d().optional(),parameters:_e(d(),xe()).optional()}))),$p=Te(()=>be(T({arguments:xe().optional(),call_id:d().nullish()}))),Rp=Te(()=>be(T({tools:q(_e(d(),xe()))}))),uP=xr({id:"openai.tool_search",inputSchema:$p,outputSchema:Rp}),dP=(e={})=>uP(e),pP=Te(()=>be(T({externalWebAccess:ve().optional(),filters:T({allowedDomains:q(d()).optional()}).optional(),searchContextSize:de(["low","medium","high"]).optional(),userLocation:T({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),fP=Te(()=>be(T({}))),hP=Te(()=>be(T({action:Ve("type",[T({type:P("search"),query:d().optional()}),T({type:P("openPage"),url:d().nullish()}),T({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:q(Ve("type",[T({type:P("url"),url:d()}),T({type:P("api"),name:d()})])).optional()}))),mP=xr({id:"openai.web_search",inputSchema:fP,outputSchema:hP}),gP=(e={})=>mP(e),yP=Te(()=>be(T({searchContextSize:de(["low","medium","high"]).optional(),userLocation:T({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),vP=Te(()=>be(T({}))),_P=Te(()=>be(T({action:Ve("type",[T({type:P("search"),query:d().optional()}),T({type:P("openPage"),url:d().nullish()}),T({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),wP=xr({id:"openai.web_search_preview",inputSchema:vP,outputSchema:_P}),Pp=Gi(()=>ae([d(),O(),ve(),Ls(),q(Pp),_e(d(),Pp)])),bP=Te(()=>be(T({serverLabel:d(),allowedTools:ae([q(d()),T({readOnly:ve().optional(),toolNames:q(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:_e(d(),d()).optional(),requireApproval:ae([de(["always","never"]),T({never:T({toolNames:q(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),TP=Te(()=>be(T({}))),kP=Te(()=>be(T({type:P("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:ae([d(),Pp]).optional()}))),SP=xr({id:"openai.mcp",inputSchema:TP,outputSchema:kP}),CP=e=>SP(e),IP={applyPatch:zR,customTool:KR,codeInterpreter:BR,fileSearch:XR,imageGeneration:oP,localShell:sP,shell:lP,webSearchPreview:wP,webSearch:gP,mcp:CP,toolSearch:dP};function S1(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,i=(r=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?r:0,l=(o=(n=e.output_tokens_details)==null?void 0:n.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-i,cacheRead:i,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}function C1(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function xP({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:i=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1,customProviderToolNames:u}){var f,p,h,m,_,y,w,v,g,S,b,k,C,R,I,j,N;let L=[];const z=[],H=new Set;for(const{role:ee,content:te}of e)switch(ee){case"system":{switch(r){case"system":{L.push({role:"system",content:te});break}case"developer":{L.push({role:"developer",content:te});break}case"remove":{z.push({type:"other",message:"system messages are removed for this model"});break}default:{const X=r;throw new Error(`Unsupported system message mode: ${X}`)}}break}case"user":{L.push({role:"user",content:te.map((X,V)=>{var se,D,E;switch(X.type){case"text":return{type:"input_text",text:X.text};case"file":if(X.mediaType.startsWith("image/")){const U=X.mediaType==="image/*"?"image/jpeg":X.mediaType;return{type:"input_image",...X.data instanceof URL?{image_url:X.data.toString()}:typeof X.data=="string"&&C1(X.data,o)?{file_id:X.data}:{image_url:`data:${U};base64,${Ko(X.data)}`},detail:(D=(se=X.providerOptions)==null?void 0:se[n])==null?void 0:D.imageDetail}}else{if(X.mediaType==="application/pdf")return X.data instanceof URL?{type:"input_file",file_url:X.data.toString()}:{type:"input_file",...typeof X.data=="string"&&C1(X.data,o)?{file_id:X.data}:{filename:(E=X.filename)!=null?E:`part-${V}.pdf`,file_data:`data:application/pdf;base64,${Ko(X.data)}`}};throw new Qr({functionality:`file part media type ${X.mediaType}`})}}})});break}case"assistant":{const X={};for(const V of te)switch(V.type){case"text":{const se=(f=V.providerOptions)==null?void 0:f[n],D=se?.itemId,E=se?.phase;if(a&&D!=null)break;if(s&&D!=null){L.push({type:"item_reference",id:D});break}L.push({role:"assistant",content:[{type:"output_text",text:V.text}],id:D,...E!=null&&{phase:E}});break}case"tool-call":{const se=(y=(h=(p=V.providerOptions)==null?void 0:p[n])==null?void 0:h.itemId)!=null?y:(_=(m=V.providerMetadata)==null?void 0:m[n])==null?void 0:_.itemId;if(a&&se!=null)break;const D=t.toProviderToolName(V.toolName);if(D==="tool_search"){if(s&&se!=null){L.push({type:"item_reference",id:se});break}const E=typeof V.input=="string"?await ly({text:V.input,schema:$p}):await _t({value:V.input,schema:$p}),U=E.call_id!=null?"client":"server";L.push({type:"tool_search_call",id:se??V.toolCallId,execution:U,call_id:(w=E.call_id)!=null?w:null,status:"completed",arguments:E.arguments});break}if(V.providerExecuted){s&&se!=null&&L.push({type:"item_reference",id:se});break}if(s&&se!=null){L.push({type:"item_reference",id:se});break}if(i&&D==="local_shell"){const E=await _t({value:V.input,schema:b1});L.push({type:"local_shell_call",call_id:V.toolCallId,id:se,action:{type:"exec",command:E.action.command,timeout_ms:E.action.timeoutMs,user:E.action.user,working_directory:E.action.workingDirectory,env:E.action.env}});break}if(l&&D==="shell"){const E=await _t({value:V.input,schema:k1});L.push({type:"shell_call",call_id:V.toolCallId,id:se,status:"completed",action:{commands:E.action.commands,timeout_ms:E.action.timeoutMs,max_output_length:E.action.maxOutputLength}});break}if(c&&D==="apply_patch"){const E=await _t({value:V.input,schema:y1});L.push({type:"apply_patch_call",call_id:E.callId,id:se,status:"completed",operation:E.operation});break}if(u?.has(D)){L.push({type:"custom_tool_call",call_id:V.toolCallId,name:D,input:typeof V.input=="string"?V.input:JSON.stringify(V.input),id:se});break}L.push({type:"function_call",call_id:V.toolCallId,name:D,arguments:JSON.stringify(V.input),id:se});break}case"tool-result":{if(V.output.type==="execution-denied"||V.output.type==="json"&&typeof V.output.value=="object"&&V.output.value!=null&&"type"in V.output.value&&V.output.value.type==="execution-denied"||a)break;const se=t.toProviderToolName(V.toolName);if(se==="tool_search"){const D=(S=(g=(v=V.providerOptions)==null?void 0:v[n])==null?void 0:g.itemId)!=null?S:V.toolCallId;if(s)L.push({type:"item_reference",id:D});else if(V.output.type==="json"){const E=await _t({value:V.output.value,schema:Rp});L.push({type:"tool_search_output",id:D,execution:"server",call_id:null,status:"completed",tools:E.tools})}break}if(l&&se==="shell"){if(V.output.type==="json"){const D=await _t({value:V.output.value,schema:Ep});L.push({type:"shell_call_output",call_id:V.toolCallId,output:D.output.map(E=>({stdout:E.stdout,stderr:E.stderr,outcome:E.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:E.outcome.exitCode}}))})}break}if(s){const D=(C=(k=(b=V.providerOptions)==null?void 0:b[n])==null?void 0:k.itemId)!=null?C:V.toolCallId;L.push({type:"item_reference",id:D})}else z.push({type:"other",message:`Results for OpenAI tool ${V.toolName} are not sent to the API when store is false`});break}case"reasoning":{const se=await gn({provider:n,providerOptions:V.providerOptions,schema:EP}),D=se?.itemId;if(a&&D!=null)break;if(D!=null){const E=X[D];if(s)E===void 0&&(L.push({type:"item_reference",id:D}),X[D]={type:"reasoning",id:D,summary:[]});else{const U=[];V.text.length>0?U.push({type:"summary_text",text:V.text}):E!==void 0&&z.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(V)}.`}),E===void 0?(X[D]={type:"reasoning",id:D,encrypted_content:se?.reasoningEncryptedContent,summary:U},L.push(X[D])):(E.summary.push(...U),se?.reasoningEncryptedContent!=null&&(E.encrypted_content=se.reasoningEncryptedContent))}}else{const E=se?.reasoningEncryptedContent;if(E!=null){const U=[];V.text.length>0&&U.push({type:"summary_text",text:V.text}),L.push({type:"reasoning",encrypted_content:E,summary:U})}else z.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(V)}.`})}break}}break}case"tool":{for(const X of te){if(X.type==="tool-approval-response"){const E=X;if(H.has(E.approvalId))continue;H.add(E.approvalId),s&&L.push({type:"item_reference",id:E.approvalId}),L.push({type:"mcp_approval_response",approval_request_id:E.approvalId,approve:E.approved});continue}const V=X.output;if(V.type==="execution-denied"&&((I=(R=V.providerOptions)==null?void 0:R.openai)==null?void 0:I.approvalId))continue;const se=t.toProviderToolName(X.toolName);if(se==="tool_search"&&V.type==="json"){const E=await _t({value:V.value,schema:Rp});L.push({type:"tool_search_output",execution:"client",call_id:X.toolCallId,status:"completed",tools:E.tools});continue}if(i&&se==="local_shell"&&V.type==="json"){const E=await _t({value:V.value,schema:T1});L.push({type:"local_shell_call_output",call_id:X.toolCallId,output:E.output});continue}if(l&&se==="shell"&&V.type==="json"){const E=await _t({value:V.value,schema:Ep});L.push({type:"shell_call_output",call_id:X.toolCallId,output:E.output.map(U=>({stdout:U.stdout,stderr:U.stderr,outcome:U.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:U.outcome.exitCode}}))});continue}if(c&&X.toolName==="apply_patch"&&V.type==="json"){const E=await _t({value:V.value,schema:v1});L.push({type:"apply_patch_call_output",call_id:X.toolCallId,status:E.status,output:E.output});continue}if(u?.has(se)){let E;switch(V.type){case"text":case"error-text":E=V.value;break;case"execution-denied":E=(j=V.reason)!=null?j:"Tool execution denied.";break;case"json":case"error-json":E=JSON.stringify(V.value);break;case"content":E=V.value.map(U=>{var Z;switch(U.type){case"text":return{type:"input_text",text:U.text};case"image-data":return{type:"input_image",image_url:`data:${U.mediaType};base64,${U.data}`};case"image-url":return{type:"input_image",image_url:U.url};case"file-data":return{type:"input_file",filename:(Z=U.filename)!=null?Z:"data",file_data:`data:${U.mediaType};base64,${U.data}`};default:z.push({type:"other",message:`unsupported custom tool content part type: ${U.type}`});return}}).filter(ey);break;default:E=""}L.push({type:"custom_tool_call_output",call_id:X.toolCallId,output:E});continue}let D;switch(V.type){case"text":case"error-text":D=V.value;break;case"execution-denied":D=(N=V.reason)!=null?N:"Tool execution denied.";break;case"json":case"error-json":D=JSON.stringify(V.value);break;case"content":D=V.value.map(E=>{var U;switch(E.type){case"text":return{type:"input_text",text:E.text};case"image-data":return{type:"input_image",image_url:`data:${E.mediaType};base64,${E.data}`};case"image-url":return{type:"input_image",image_url:E.url};case"file-data":return{type:"input_file",filename:(U=E.filename)!=null?U:"data",file_data:`data:${E.mediaType};base64,${E.data}`};default:{z.push({type:"other",message:`unsupported tool content part type: ${E.type}`});return}}}).filter(ey);break}L.push({type:"function_call_output",call_id:X.toolCallId,output:D})}break}default:{const X=ee;throw new Error(`Unsupported role: ${X}`)}}return!s&&L.some(ee=>"type"in ee&&ee.type==="reasoning"&&ee.encrypted_content==null)&&(z.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),L=L.filter(ee=>!("type"in ee)||ee.type!=="reasoning"||ee.encrypted_content!=null)),{input:L,warnings:z}}var EP=T({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function Mp({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}var ka=Gi(()=>ae([d(),O(),ve(),Ls(),q(ka),_e(d(),ka.optional())])),$P=Te(()=>be(ae([T({type:P("response.output_text.delta"),item_id:d(),delta:d(),logprobs:q(T({token:d(),logprob:O(),top_logprobs:q(T({token:d(),logprob:O()}))})).nullish()}),T({type:de(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:O(),input_tokens_details:T({cached_tokens:O().nullish()}).nullish(),output_tokens:O(),output_tokens_details:T({reasoning_tokens:O().nullish()}).nullish()}),service_tier:d().nullish()})}),T({type:P("response.failed"),response:T({error:T({code:d().nullish(),message:d()}).nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:O(),input_tokens_details:T({cached_tokens:O().nullish()}).nullish(),output_tokens:O(),output_tokens_details:T({reasoning_tokens:O().nullish()}).nullish()}).nullish(),service_tier:d().nullish()})}),T({type:P("response.created"),response:T({id:d(),created_at:O(),model:d(),service_tier:d().nullish()})}),T({type:P("response.output_item.added"),output_index:O(),item:Ve("type",[T({type:P("message"),id:d(),phase:de(["commentary","final_answer"]).nullish()}),T({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),T({type:P("web_search_call"),id:d(),status:d()}),T({type:P("computer_call"),id:d(),status:d()}),T({type:P("file_search_call"),id:d()}),T({type:P("image_generation_call"),id:d()}),T({type:P("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:q(Ve("type",[T({type:P("logs"),logs:d()}),T({type:P("image"),url:d()})])).nullable(),status:d()}),T({type:P("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),T({type:P("mcp_list_tools"),id:d()}),T({type:P("mcp_approval_request"),id:d()}),T({type:P("apply_patch_call"),id:d(),call_id:d(),status:de(["in_progress","completed"]),operation:Ve("type",[T({type:P("create_file"),path:d(),diff:d()}),T({type:P("delete_file"),path:d()}),T({type:P("update_file"),path:d(),diff:d()})])}),T({type:P("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d()}),T({type:P("shell_call"),id:d(),call_id:d(),status:de(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:P("shell_call_output"),id:d(),call_id:d(),status:de(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:Ve("type",[T({type:P("timeout")}),T({type:P("exit"),exit_code:O()})])}))}),T({type:P("tool_search_call"),id:d(),execution:de(["server","client"]),call_id:d().nullable(),status:de(["in_progress","completed","incomplete"]),arguments:xe()}),T({type:P("tool_search_output"),id:d(),execution:de(["server","client"]),call_id:d().nullable(),status:de(["in_progress","completed","incomplete"]),tools:q(_e(d(),ka.optional()))})])}),T({type:P("response.output_item.done"),output_index:O(),item:Ve("type",[T({type:P("message"),id:d(),phase:de(["commentary","final_answer"]).nullish()}),T({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),T({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:P("completed")}),T({type:P("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d(),status:P("completed")}),T({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(Ve("type",[T({type:P("logs"),logs:d()}),T({type:P("image"),url:d()})])).nullable()}),T({type:P("image_generation_call"),id:d(),result:d()}),T({type:P("web_search_call"),id:d(),status:d(),action:Ve("type",[T({type:P("search"),query:d().nullish(),sources:q(Ve("type",[T({type:P("url"),url:d()}),T({type:P("api"),name:d()})])).nullish()}),T({type:P("open_page"),url:d().nullish()}),T({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:P("file_search_call"),id:d(),queries:q(d()),results:q(T({attributes:_e(d(),ae([d(),O(),ve()])),file_id:d(),filename:d(),score:O(),text:d()})).nullish()}),T({type:P("local_shell_call"),id:d(),call_id:d(),action:T({type:P("exec"),command:q(d()),timeout_ms:O().optional(),user:d().optional(),working_directory:d().optional(),env:_e(d(),d()).optional()})}),T({type:P("computer_call"),id:d(),status:P("completed")}),T({type:P("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),T({type:d().optional(),code:ae([O(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:P("mcp_list_tools"),id:d(),server_label:d(),tools:q(T({name:d(),description:d().optional(),input_schema:Tt(),annotations:_e(d(),xe()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([O(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:P("apply_patch_call"),id:d(),call_id:d(),status:de(["in_progress","completed"]),operation:Ve("type",[T({type:P("create_file"),path:d(),diff:d()}),T({type:P("delete_file"),path:d()}),T({type:P("update_file"),path:d(),diff:d()})])}),T({type:P("shell_call"),id:d(),call_id:d(),status:de(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:P("shell_call_output"),id:d(),call_id:d(),status:de(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:Ve("type",[T({type:P("timeout")}),T({type:P("exit"),exit_code:O()})])}))}),T({type:P("tool_search_call"),id:d(),execution:de(["server","client"]),call_id:d().nullable(),status:de(["in_progress","completed","incomplete"]),arguments:xe()}),T({type:P("tool_search_output"),id:d(),execution:de(["server","client"]),call_id:d().nullable(),status:de(["in_progress","completed","incomplete"]),tools:q(_e(d(),ka.optional()))})])}),T({type:P("response.function_call_arguments.delta"),item_id:d(),output_index:O(),delta:d()}),T({type:P("response.custom_tool_call_input.delta"),item_id:d(),output_index:O(),delta:d()}),T({type:P("response.image_generation_call.partial_image"),item_id:d(),output_index:O(),partial_image_b64:d()}),T({type:P("response.code_interpreter_call_code.delta"),item_id:d(),output_index:O(),delta:d()}),T({type:P("response.code_interpreter_call_code.done"),item_id:d(),output_index:O(),code:d()}),T({type:P("response.output_text.annotation.added"),annotation:Ve("type",[T({type:P("url_citation"),start_index:O(),end_index:O(),url:d(),title:d()}),T({type:P("file_citation"),file_id:d(),filename:d(),index:O()}),T({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:O(),end_index:O()}),T({type:P("file_path"),file_id:d(),index:O()})])}),T({type:P("response.reasoning_summary_part.added"),item_id:d(),summary_index:O()}),T({type:P("response.reasoning_summary_text.delta"),item_id:d(),summary_index:O(),delta:d()}),T({type:P("response.reasoning_summary_part.done"),item_id:d(),summary_index:O()}),T({type:P("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:O(),delta:d(),obfuscation:d().nullish()}),T({type:P("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:O(),diff:d()}),T({type:P("error"),sequence_number:O(),error:T({type:d(),code:d(),message:d(),param:d().nullish()})}),T({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),RP=Te(()=>be(T({id:d().optional(),created_at:O().optional(),error:T({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:q(Ve("type",[T({type:P("message"),role:P("assistant"),id:d(),phase:de(["commentary","final_answer"]).nullish(),content:q(T({type:P("output_text"),text:d(),logprobs:q(T({token:d(),logprob:O(),top_logprobs:q(T({token:d(),logprob:O()}))})).nullish(),annotations:q(Ve("type",[T({type:P("url_citation"),start_index:O(),end_index:O(),url:d(),title:d()}),T({type:P("file_citation"),file_id:d(),filename:d(),index:O()}),T({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:O(),end_index:O()}),T({type:P("file_path"),file_id:d(),index:O()})]))}))}),T({type:P("web_search_call"),id:d(),status:d(),action:Ve("type",[T({type:P("search"),query:d().nullish(),sources:q(Ve("type",[T({type:P("url"),url:d()}),T({type:P("api"),name:d()})])).nullish()}),T({type:P("open_page"),url:d().nullish()}),T({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),T({type:P("file_search_call"),id:d(),queries:q(d()),results:q(T({attributes:_e(d(),ae([d(),O(),ve()])),file_id:d(),filename:d(),score:O(),text:d()})).nullish()}),T({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:q(Ve("type",[T({type:P("logs"),logs:d()}),T({type:P("image"),url:d()})])).nullable()}),T({type:P("image_generation_call"),id:d(),result:d()}),T({type:P("local_shell_call"),id:d(),call_id:d(),action:T({type:P("exec"),command:q(d()),timeout_ms:O().optional(),user:d().optional(),working_directory:d().optional(),env:_e(d(),d()).optional()})}),T({type:P("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),T({type:P("custom_tool_call"),call_id:d(),name:d(),input:d(),id:d()}),T({type:P("computer_call"),id:d(),status:d().optional()}),T({type:P("reasoning"),id:d(),encrypted_content:d().nullish(),summary:q(T({type:P("summary_text"),text:d()}))}),T({type:P("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:ae([d(),T({type:d().optional(),code:ae([O(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),T({type:P("mcp_list_tools"),id:d(),server_label:d(),tools:q(T({name:d(),description:d().optional(),input_schema:Tt(),annotations:_e(d(),xe()).optional()})),error:ae([d(),T({type:d().optional(),code:ae([O(),d()]).optional(),message:d().optional()}).loose()]).optional()}),T({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),T({type:P("apply_patch_call"),id:d(),call_id:d(),status:de(["in_progress","completed"]),operation:Ve("type",[T({type:P("create_file"),path:d(),diff:d()}),T({type:P("delete_file"),path:d()}),T({type:P("update_file"),path:d(),diff:d()})])}),T({type:P("shell_call"),id:d(),call_id:d(),status:de(["in_progress","completed","incomplete"]),action:T({commands:q(d())})}),T({type:P("shell_call_output"),id:d(),call_id:d(),status:de(["in_progress","completed","incomplete"]),output:q(T({stdout:d(),stderr:d(),outcome:Ve("type",[T({type:P("timeout")}),T({type:P("exit"),exit_code:O()})])}))}),T({type:P("tool_search_call"),id:d(),execution:de(["server","client"]),call_id:d().nullable(),status:de(["in_progress","completed","incomplete"]),arguments:xe()}),T({type:P("tool_search_output"),id:d(),execution:de(["server","client"]),call_id:d().nullable(),status:de(["in_progress","completed","incomplete"]),tools:q(_e(d(),ka.optional()))})])).optional(),service_tier:d().nullish(),incomplete_details:T({reason:d()}).nullish(),usage:T({input_tokens:O(),input_tokens_details:T({cached_tokens:O().nullish()}).nullish(),output_tokens:O(),output_tokens_details:T({reasoning_tokens:O().nullish()}).nullish()}).optional()}))),I1=20,x1=Te(()=>be(T({conversation:d().nullish(),include:q(de(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:ae([ve(),O().min(1).max(I1)]).optional(),maxToolCalls:O().nullish(),metadata:Tt().nullish(),parallelToolCalls:ve().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:de(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:de(["auto","flex","priority","default"]).nullish(),store:ve().nullish(),strictJsonSchema:ve().nullish(),textVerbosity:de(["low","medium","high"]).nullish(),truncation:de(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:de(["system","developer","remove"]).optional(),forceReasoning:ve().optional()})));async function PP({tools:e,toolChoice:t,toolNameMapping:r,customProviderToolNames:n}){var o,s;e=e?.length?e:void 0;const a=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};const i=[],l=n??new Set;for(const u of e)switch(u.type){case"function":{const f=(o=u.providerOptions)==null?void 0:o.openai,p=f?.deferLoading;i.push({type:"function",name:u.name,description:u.description,parameters:u.inputSchema,...u.strict!=null?{strict:u.strict}:{},...p!=null?{defer_loading:p}:{}});break}case"provider":{switch(u.id){case"openai.file_search":{const f=await _t({value:u.args,schema:YR});i.push({type:"file_search",vector_store_ids:f.vectorStoreIds,max_num_results:f.maxNumResults,ranking_options:f.ranking?{ranker:f.ranking.ranker,score_threshold:f.ranking.scoreThreshold}:void 0,filters:f.filters});break}case"openai.local_shell":{i.push({type:"local_shell"});break}case"openai.shell":{const f=await _t({value:u.args,schema:iP});i.push({type:"shell",...f.environment&&{environment:MP(f.environment)}});break}case"openai.apply_patch":{i.push({type:"apply_patch"});break}case"openai.web_search_preview":{const f=await _t({value:u.args,schema:yP});i.push({type:"web_search_preview",search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.web_search":{const f=await _t({value:u.args,schema:pP});i.push({type:"web_search",filters:f.filters!=null?{allowed_domains:f.filters.allowedDomains}:void 0,external_web_access:f.externalWebAccess,search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.code_interpreter":{const f=await _t({value:u.args,schema:VR});i.push({type:"code_interpreter",container:f.container==null?{type:"auto",file_ids:void 0}:typeof f.container=="string"?f.container:{type:"auto",file_ids:f.container.fileIds}});break}case"openai.image_generation":{const f=await _t({value:u.args,schema:eP});i.push({type:"image_generation",background:f.background,input_fidelity:f.inputFidelity,input_image_mask:f.inputImageMask?{file_id:f.inputImageMask.fileId,image_url:f.inputImageMask.imageUrl}:void 0,model:f.model,moderation:f.moderation,partial_images:f.partialImages,quality:f.quality,output_compression:f.outputCompression,output_format:f.outputFormat,size:f.size});break}case"openai.mcp":{const f=await _t({value:u.args,schema:bP}),p=_=>({tool_names:_.toolNames}),h=f.requireApproval,m=h==null?void 0:typeof h=="string"?h:h.never!=null?{never:p(h.never)}:void 0;i.push({type:"mcp",server_label:f.serverLabel,allowed_tools:Array.isArray(f.allowedTools)?f.allowedTools:f.allowedTools?{read_only:f.allowedTools.readOnly,tool_names:f.allowedTools.toolNames}:void 0,authorization:f.authorization,connector_id:f.connectorId,headers:f.headers,require_approval:m??"never",server_description:f.serverDescription,server_url:f.serverUrl});break}case"openai.custom":{const f=await _t({value:u.args,schema:WR});i.push({type:"custom",name:f.name,description:f.description,format:f.format}),l.add(f.name);break}case"openai.tool_search":{const f=await _t({value:u.args,schema:cP});i.push({type:"tool_search",...f.execution!=null?{execution:f.execution}:{},...f.description!=null?{description:f.description}:{},...f.parameters!=null?{parameters:f.parameters}:{}});break}}break}default:a.push({type:"unsupported",feature:`function tool ${u}`});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:a};const c=t.type;switch(c){case"auto":case"none":case"required":return{tools:i,toolChoice:c,toolWarnings:a};case"tool":{const u=(s=r?.toProviderToolName(t.toolName))!=null?s:t.toolName;return{tools:i,toolChoice:u==="code_interpreter"||u==="file_search"||u==="image_generation"||u==="web_search_preview"||u==="web_search"||u==="mcp"||u==="apply_patch"?{type:u}:l.has(u)?{type:"custom",name:u}:{type:"function",name:u},toolWarnings:a}}default:{const u=c;throw new Qr({functionality:`tool choice type: ${u}`})}}}function MP(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const r=e;return{type:"container_auto",file_ids:r.fileIds,memory_limit:r.memoryLimit,network_policy:r.networkPolicy==null?void 0:r.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:r.networkPolicy.allowedDomains,domain_secrets:r.networkPolicy.domainSecrets},skills:NP(r.skills)}}return{type:"local",skills:e.skills}}function NP(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}function E1(e){var t,r;const n={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(r=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;a!=null&&(n[a]=s.toolCallId)}return n}var OP=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:r,topP:n,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:f,responseFormat:p}){var h,m,_,y,w,v,g,S,b;const k=[],C=l1(this.modelId);o!=null&&k.push({type:"unsupported",feature:"topK"}),i!=null&&k.push({type:"unsupported",feature:"seed"}),s!=null&&k.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&k.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&k.push({type:"unsupported",feature:"stopSequences"});const R=this.config.provider.includes("azure")?"azure":"openai";let I=await gn({provider:R,providerOptions:c,schema:x1});I==null&&R!=="openai"&&(I=await gn({provider:"openai",providerOptions:c,schema:x1}));const j=(h=I?.forceReasoning)!=null?h:C.isReasoningModel;I?.conversation&&I?.previousResponseId&&k.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const N=b5({tools:u,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search"},resolveProviderToolName:ne=>ne.id==="openai.custom"?ne.args.name:void 0}),L=new Set,{tools:z,toolChoice:H,toolWarnings:ee}=await PP({tools:u,toolChoice:f,toolNameMapping:N,customProviderToolNames:L}),{input:te,warnings:X}=await xP({prompt:l,toolNameMapping:N,systemMessageMode:(m=I?.systemMessageMode)!=null?m:j?"developer":C.systemMessageMode,providerOptionsName:R,fileIdPrefixes:this.config.fileIdPrefixes,store:(_=I?.store)!=null?_:!0,hasConversation:I?.conversation!=null,hasLocalShellTool:E("openai.local_shell"),hasShellTool:E("openai.shell"),hasApplyPatchTool:E("openai.apply_patch"),customProviderToolNames:L.size>0?L:void 0});k.push(...X);const V=(y=I?.strictJsonSchema)!=null?y:!0;let se=I?.include;function D(ne){se==null?se=[ne]:se.includes(ne)||(se=[...se,ne])}function E(ne){return u?.find(we=>we.type==="provider"&&we.id===ne)!=null}const U=typeof I?.logprobs=="number"?I?.logprobs:I?.logprobs===!0?I1:void 0;U&&D("message.output_text.logprobs");const Z=(w=u?.find(ne=>ne.type==="provider"&&(ne.id==="openai.web_search"||ne.id==="openai.web_search_preview")))==null?void 0:w.name;Z&&D("web_search_call.action.sources"),E("openai.code_interpreter")&&D("code_interpreter_call.outputs");const x=I?.store;x===!1&&j&&D("reasoning.encrypted_content");const M={model:this.modelId,input:te,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||I?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:V,name:(v=p.name)!=null?v:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...I?.textVerbosity&&{verbosity:I.textVerbosity}}},conversation:I?.conversation,max_tool_calls:I?.maxToolCalls,metadata:I?.metadata,parallel_tool_calls:I?.parallelToolCalls,previous_response_id:I?.previousResponseId,store:x,user:I?.user,instructions:I?.instructions,service_tier:I?.serviceTier,include:se,prompt_cache_key:I?.promptCacheKey,prompt_cache_retention:I?.promptCacheRetention,safety_identifier:I?.safetyIdentifier,top_logprobs:U,truncation:I?.truncation,...j&&(I?.reasoningEffort!=null||I?.reasoningSummary!=null)&&{reasoning:{...I?.reasoningEffort!=null&&{effort:I.reasoningEffort},...I?.reasoningSummary!=null&&{summary:I.reasoningSummary}}}};j?I?.reasoningEffort==="none"&&C.supportsNonReasoningParameters||(M.temperature!=null&&(M.temperature=void 0,k.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,k.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(I?.reasoningEffort!=null&&k.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),I?.reasoningSummary!=null&&k.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),I?.serviceTier==="flex"&&!C.supportsFlexProcessing&&(k.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete M.service_tier),I?.serviceTier==="priority"&&!C.supportsPriorityProcessing&&(k.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete M.service_tier);const W=(b=(S=(g=u?.find(ne=>ne.type==="provider"&&ne.id==="openai.shell"))==null?void 0:g.args)==null?void 0:S.environment)==null?void 0:b.type,oe=W==="containerAuto"||W==="containerReference";return{webSearchToolName:Z,args:{...M,tools:z,tool_choice:H},warnings:[...k,...ee],store:x,toolNameMapping:N,providerOptionsName:R,isShellProviderExecuted:oe}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,f,p,h,m,_,y,w,v,g,S,b,k,C,R,I,j,N,L;const{args:z,warnings:H,webSearchToolName:ee,toolNameMapping:te,providerOptionsName:X,isShellProviderExecuted:V}=await this.getArgs(e),se=this.config.url({path:"/responses",modelId:this.modelId}),D=E1(e.prompt),{responseHeaders:E,value:U,rawValue:Z}=await nr({url:se,headers:Dt(this.config.headers(),e.headers),body:z,failedResponseHandler:Hr,successfulResponseHandler:or(RP),abortSignal:e.abortSignal,fetch:this.config.fetch});if(U.error)throw new ht({message:U.error.message,url:se,requestBodyValues:z,statusCode:400,responseHeaders:E,responseBody:Z,isRetryable:!1});const x=[],M=[];let W=!1;const oe=[];for(const K of U.output)switch(K.type){case"reasoning":{K.summary.length===0&&K.summary.push({type:"summary_text",text:""});for(const A of K.summary)x.push({type:"reasoning",text:A.text,providerMetadata:{[X]:{itemId:K.id,reasoningEncryptedContent:(t=K.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{x.push({type:"tool-call",toolCallId:K.id,toolName:te.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:K.id,toolName:te.toCustomToolName("image_generation"),result:{result:K.result}});break}case"tool_search_call":{const A=(r=K.call_id)!=null?r:K.id,F=K.execution==="server";F&&oe.push(A),x.push({type:"tool-call",toolCallId:A,toolName:te.toCustomToolName("tool_search"),input:JSON.stringify({arguments:K.arguments,call_id:K.call_id}),...F?{providerExecuted:!0}:{},providerMetadata:{[X]:{itemId:K.id}}});break}case"tool_search_output":{const A=(o=(n=K.call_id)!=null?n:oe.shift())!=null?o:K.id;x.push({type:"tool-result",toolCallId:A,toolName:te.toCustomToolName("tool_search"),result:{tools:K.tools},providerMetadata:{[X]:{itemId:K.id}}});break}case"local_shell_call":{x.push({type:"tool-call",toolCallId:K.call_id,toolName:te.toCustomToolName("local_shell"),input:JSON.stringify({action:K.action}),providerMetadata:{[X]:{itemId:K.id}}});break}case"shell_call":{x.push({type:"tool-call",toolCallId:K.call_id,toolName:te.toCustomToolName("shell"),input:JSON.stringify({action:{commands:K.action.commands}}),...V&&{providerExecuted:!0},providerMetadata:{[X]:{itemId:K.id}}});break}case"shell_call_output":{x.push({type:"tool-result",toolCallId:K.call_id,toolName:te.toCustomToolName("shell"),result:{output:K.output.map(A=>({stdout:A.stdout,stderr:A.stderr,outcome:A.outcome.type==="exit"?{type:"exit",exitCode:A.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const A of K.content){(a=(s=e.providerOptions)==null?void 0:s[X])!=null&&a.logprobs&&A.logprobs&&M.push(A.logprobs);const F={itemId:K.id,...K.phase!=null&&{phase:K.phase},...A.annotations.length>0&&{annotations:A.annotations}};x.push({type:"text",text:A.text,providerMetadata:{[X]:F}});for(const G of A.annotations)G.type==="url_citation"?x.push({type:"source",sourceType:"url",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:Wt(),url:G.url,title:G.title}):G.type==="file_citation"?x.push({type:"source",sourceType:"document",id:(p=(f=(u=this.config).generateId)==null?void 0:f.call(u))!=null?p:Wt(),mediaType:"text/plain",title:G.filename,filename:G.filename,providerMetadata:{[X]:{type:G.type,fileId:G.file_id,index:G.index}}}):G.type==="container_file_citation"?x.push({type:"source",sourceType:"document",id:(_=(m=(h=this.config).generateId)==null?void 0:m.call(h))!=null?_:Wt(),mediaType:"text/plain",title:G.filename,filename:G.filename,providerMetadata:{[X]:{type:G.type,fileId:G.file_id,containerId:G.container_id}}}):G.type==="file_path"&&x.push({type:"source",sourceType:"document",id:(v=(w=(y=this.config).generateId)==null?void 0:w.call(y))!=null?v:Wt(),mediaType:"application/octet-stream",title:G.file_id,filename:G.file_id,providerMetadata:{[X]:{type:G.type,fileId:G.file_id,index:G.index}}})}break}case"function_call":{W=!0,x.push({type:"tool-call",toolCallId:K.call_id,toolName:K.name,input:K.arguments,providerMetadata:{[X]:{itemId:K.id}}});break}case"custom_tool_call":{W=!0;const A=te.toCustomToolName(K.name);x.push({type:"tool-call",toolCallId:K.call_id,toolName:A,input:JSON.stringify(K.input),providerMetadata:{[X]:{itemId:K.id}}});break}case"web_search_call":{x.push({type:"tool-call",toolCallId:K.id,toolName:te.toCustomToolName(ee??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:K.id,toolName:te.toCustomToolName(ee??"web_search"),result:R1(K.action)});break}case"mcp_call":{const A=K.approval_request_id!=null&&(g=D[K.approval_request_id])!=null?g:K.id,F=`mcp.${K.name}`;x.push({type:"tool-call",toolCallId:A,toolName:F,input:K.arguments,providerExecuted:!0,dynamic:!0}),x.push({type:"tool-result",toolCallId:A,toolName:F,result:{type:"call",serverLabel:K.server_label,name:K.name,arguments:K.arguments,...K.output!=null?{output:K.output}:{},...K.error!=null?{error:K.error}:{}},providerMetadata:{[X]:{itemId:K.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const A=(S=K.approval_request_id)!=null?S:K.id,F=(C=(k=(b=this.config).generateId)==null?void 0:k.call(b))!=null?C:Wt(),G=`mcp.${K.name}`;x.push({type:"tool-call",toolCallId:F,toolName:G,input:K.arguments,providerExecuted:!0,dynamic:!0}),x.push({type:"tool-approval-request",approvalId:A,toolCallId:F});break}case"computer_call":{x.push({type:"tool-call",toolCallId:K.id,toolName:te.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:K.id,toolName:te.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:K.status||"completed"}});break}case"file_search_call":{x.push({type:"tool-call",toolCallId:K.id,toolName:te.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),x.push({type:"tool-result",toolCallId:K.id,toolName:te.toCustomToolName("file_search"),result:{queries:K.queries,results:(I=(R=K.results)==null?void 0:R.map(A=>({attributes:A.attributes,fileId:A.file_id,filename:A.filename,score:A.score,text:A.text})))!=null?I:null}});break}case"code_interpreter_call":{x.push({type:"tool-call",toolCallId:K.id,toolName:te.toCustomToolName("code_interpreter"),input:JSON.stringify({code:K.code,containerId:K.container_id}),providerExecuted:!0}),x.push({type:"tool-result",toolCallId:K.id,toolName:te.toCustomToolName("code_interpreter"),result:{outputs:K.outputs}});break}case"apply_patch_call":{x.push({type:"tool-call",toolCallId:K.call_id,toolName:te.toCustomToolName("apply_patch"),input:JSON.stringify({callId:K.call_id,operation:K.operation}),providerMetadata:{[X]:{itemId:K.id}}});break}}const ne={[X]:{responseId:U.id,...M.length>0?{logprobs:M}:{},...typeof U.service_tier=="string"?{serviceTier:U.service_tier}:{}}},we=U.usage;return{content:x,finishReason:{unified:Mp({finishReason:(j=U.incomplete_details)==null?void 0:j.reason,hasFunctionCall:W}),raw:(L=(N=U.incomplete_details)==null?void 0:N.reason)!=null?L:void 0},usage:S1(we),request:{body:z},response:{id:U.id,timestamp:new Date(U.created_at*1e3),modelId:U.model,headers:E,body:Z},providerMetadata:ne,warnings:H}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:a,isShellProviderExecuted:i}=await this.getArgs(e),{responseHeaders:l,value:c}=await nr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Hr,successfulResponseHandler:$l($P),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,f=E1(e.prompt),p=new Map;let h={unified:"other",raw:void 0},m;const _=[];let y=null;const w={},v=[];let g,S=!1;const b={};let k;const C=[];return{stream:c.pipeThrough(new TransformStream({start(R){R.enqueue({type:"stream-start",warnings:r})},transform(R,I){var j,N,L,z,H,ee,te,X,V,se,D,E,U,Z,x,M,W,oe,ne,we,K,A,F,G,Q,pe,Ie,Ge,dt,wt,st,it,zt,bt,Br,ar,et,$r;if(e.includeRawChunks&&I.enqueue({type:"raw",rawValue:R.rawValue}),!R.success){h={unified:"error",raw:void 0},I.enqueue({type:"error",error:R.error});return}const $=R.value;if($1($)){if($.item.type==="function_call")w[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name});else if($.item.type==="custom_tool_call"){const Y=o.toCustomToolName($.item.name);w[$.output_index]={toolName:Y,toolCallId:$.item.call_id},I.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:Y})}else if($.item.type==="web_search_call")w[$.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if($.item.type==="computer_call")w[$.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:$.item.id},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if($.item.type==="code_interpreter_call")w[$.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},I.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),I.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`});else if($.item.type==="file_search_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if($.item.type==="tool_search_call"){const Y=$.item.id,je=o.toCustomToolName("tool_search"),$e=$.item.execution==="server";w[$.output_index]={toolName:je,toolCallId:Y,toolSearchExecution:(j=$.item.execution)!=null?j:"server"},$e&&I.enqueue({type:"tool-input-start",id:Y,toolName:je,providerExecuted:!0})}else if($.item.type!=="tool_search_output"){if(!($.item.type==="mcp_call"||$.item.type==="mcp_list_tools"||$.item.type==="mcp_approval_request"))if($.item.type==="apply_patch_call"){const{call_id:Y,operation:je}=$.item;if(w[$.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:Y,applyPatch:{hasDiff:je.type==="delete_file",endEmitted:je.type==="delete_file"}},I.enqueue({type:"tool-input-start",id:Y,toolName:o.toCustomToolName("apply_patch")}),je.type==="delete_file"){const $e=JSON.stringify({callId:Y,operation:je});I.enqueue({type:"tool-input-delta",id:Y,delta:$e}),I.enqueue({type:"tool-input-end",id:Y})}else I.enqueue({type:"tool-input-delta",id:Y,delta:`{"callId":"${yo(Y)}","operation":{"type":"${yo(je.type)}","path":"${yo(je.path)}","diff":"`})}else $.item.type==="shell_call"?w[$.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:$.item.call_id}:$.item.type==="shell_call_output"||($.item.type==="message"?(v.splice(0,v.length),g=(N=$.item.phase)!=null?N:void 0,I.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[a]:{itemId:$.item.id,...$.item.phase!=null&&{phase:$.item.phase}}}})):$1($)&&$.item.type==="reasoning"&&(b[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},I.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[a]:{itemId:$.item.id,reasoningEncryptedContent:(L=$.item.encrypted_content)!=null?L:null}}})))}}else if(qP($)){if($.item.type==="message"){const Y=(z=$.item.phase)!=null?z:g;g=void 0,I.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[a]:{itemId:$.item.id,...Y!=null&&{phase:Y},...v.length>0&&{annotations:v}}}})}else if($.item.type==="function_call")w[$.output_index]=void 0,S=!0,I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="custom_tool_call"){w[$.output_index]=void 0,S=!0;const Y=o.toCustomToolName($.item.name);I.enqueue({type:"tool-input-end",id:$.item.call_id}),I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:Y,input:JSON.stringify($.item.input),providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="web_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),result:R1($.item.action)});else if($.item.type==="computer_call")w[$.output_index]=void 0,I.enqueue({type:"tool-input-end",id:$.item.id}),I.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:$.item.status||"completed"}});else if($.item.type==="file_search_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:$.item.queries,results:(ee=(H=$.item.results)==null?void 0:H.map(Y=>({attributes:Y.attributes,fileId:Y.file_id,filename:Y.filename,score:Y.score,text:Y.text})))!=null?ee:null}});else if($.item.type==="code_interpreter_call")w[$.output_index]=void 0,I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:$.item.outputs}});else if($.item.type==="image_generation_call")I.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:$.item.result}});else if($.item.type==="tool_search_call"){const Y=w[$.output_index],je=$.item.execution==="server";if(Y!=null){const $e=je?Y.toolCallId:(te=$.item.call_id)!=null?te:$.item.id;je?C.push($e):I.enqueue({type:"tool-input-start",id:$e,toolName:Y.toolName}),I.enqueue({type:"tool-input-end",id:$e}),I.enqueue({type:"tool-call",toolCallId:$e,toolName:Y.toolName,input:JSON.stringify({arguments:$.item.arguments,call_id:je?null:$e}),...je?{providerExecuted:!0}:{},providerMetadata:{[a]:{itemId:$.item.id}}})}w[$.output_index]=void 0}else if($.item.type==="tool_search_output"){const Y=(V=(X=$.item.call_id)!=null?X:C.shift())!=null?V:$.item.id;I.enqueue({type:"tool-result",toolCallId:Y,toolName:o.toCustomToolName("tool_search"),result:{tools:$.item.tools},providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="mcp_call"){w[$.output_index]=void 0;const Y=(se=$.item.approval_request_id)!=null?se:void 0,je=Y!=null&&(E=(D=p.get(Y))!=null?D:f[Y])!=null?E:$.item.id,$e=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:je,toolName:$e,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-result",toolCallId:je,toolName:$e,result:{type:"call",serverLabel:$.item.server_label,name:$.item.name,arguments:$.item.arguments,...$.item.output!=null?{output:$.item.output}:{},...$.item.error!=null?{error:$.item.error}:{}},providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="mcp_list_tools")w[$.output_index]=void 0;else if($.item.type==="apply_patch_call"){const Y=w[$.output_index];Y?.applyPatch&&!Y.applyPatch.endEmitted&&$.item.operation.type!=="delete_file"&&(Y.applyPatch.hasDiff||I.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:yo($.item.operation.diff)}),I.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:Y.toolCallId}),Y.applyPatch.endEmitted=!0),Y&&$.item.status==="completed"&&I.enqueue({type:"tool-call",toolCallId:Y.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:$.item.call_id,operation:$.item.operation}),providerMetadata:{[a]:{itemId:$.item.id}}}),w[$.output_index]=void 0}else if($.item.type==="mcp_approval_request"){w[$.output_index]=void 0;const Y=(x=(Z=(U=u.config).generateId)==null?void 0:Z.call(U))!=null?x:Wt(),je=(M=$.item.approval_request_id)!=null?M:$.item.id;p.set(je,Y);const $e=`mcp.${$.item.name}`;I.enqueue({type:"tool-call",toolCallId:Y,toolName:$e,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),I.enqueue({type:"tool-approval-request",approvalId:je,toolCallId:Y})}else if($.item.type==="local_shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="shell_call")w[$.output_index]=void 0,I.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:$.item.action.commands}}),...i&&{providerExecuted:!0},providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="shell_call_output")I.enqueue({type:"tool-result",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:$.item.output.map(Y=>({stdout:Y.stdout,stderr:Y.stderr,outcome:Y.outcome.type==="exit"?{type:"exit",exitCode:Y.outcome.exit_code}:{type:"timeout"}}))}});else if($.item.type==="reasoning"){const Y=b[$.item.id],je=Object.entries(Y.summaryParts).filter(([$e,lt])=>lt==="active"||lt==="can-conclude").map(([$e])=>$e);for(const $e of je)I.enqueue({type:"reasoning-end",id:`${$.item.id}:${$e}`,providerMetadata:{[a]:{itemId:$.item.id,reasoningEncryptedContent:(W=$.item.encrypted_content)!=null?W:null}}});delete b[$.item.id]}}else if(UP($)){const Y=w[$.output_index];Y!=null&&I.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:$.delta})}else if(zP($)){const Y=w[$.output_index];Y!=null&&I.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:$.delta})}else if(HP($)){const Y=w[$.output_index];Y?.applyPatch&&(I.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:yo($.delta)}),Y.applyPatch.hasDiff=!0)}else if(BP($)){const Y=w[$.output_index];Y?.applyPatch&&!Y.applyPatch.endEmitted&&(Y.applyPatch.hasDiff||(I.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:yo($.diff)}),Y.applyPatch.hasDiff=!0),I.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:'"}}'}),I.enqueue({type:"tool-input-end",id:Y.toolCallId}),Y.applyPatch.endEmitted=!0)}else if(ZP($))I.enqueue({type:"tool-result",toolCallId:$.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:$.partial_image_b64},preliminary:!0});else if(FP($)){const Y=w[$.output_index];Y!=null&&I.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:yo($.delta)})}else if(VP($)){const Y=w[$.output_index];Y!=null&&(I.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:'"}'}),I.enqueue({type:"tool-input-end",id:Y.toolCallId}),I.enqueue({type:"tool-call",toolCallId:Y.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:$.code,containerId:Y.codeInterpreter.containerId}),providerExecuted:!0}))}else if(DP($))y=$.response.id,I.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(AP($))I.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(ne=(oe=e.providerOptions)==null?void 0:oe[a])!=null&&ne.logprobs&&$.logprobs&&_.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const Y=b[$.item_id];Y.summaryParts[$.summary_index]="active";for(const je of Object.keys(Y.summaryParts))Y.summaryParts[je]==="can-conclude"&&(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${je}`,providerMetadata:{[a]:{itemId:$.item_id}}}),Y.summaryParts[je]="concluded");I.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[a]:{itemId:$.item_id,reasoningEncryptedContent:(K=(we=b[$.item_id])==null?void 0:we.encryptedContent)!=null?K:null}}})}}else if($.type==="response.reasoning_summary_text.delta")I.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[a]:{itemId:$.item_id}}});else if($.type==="response.reasoning_summary_part.done")s?(I.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[a]:{itemId:$.item_id}}}),b[$.item_id].summaryParts[$.summary_index]="concluded"):b[$.item_id].summaryParts[$.summary_index]="can-conclude";else if(LP($))h={unified:Mp({finishReason:(A=$.response.incomplete_details)==null?void 0:A.reason,hasFunctionCall:S}),raw:(G=(F=$.response.incomplete_details)==null?void 0:F.reason)!=null?G:void 0},m=$.response.usage,typeof $.response.service_tier=="string"&&(k=$.response.service_tier);else if(jP($)){const Y=(Q=$.response.incomplete_details)==null?void 0:Q.reason;h={unified:Y?Mp({finishReason:Y,hasFunctionCall:S}):"error",raw:Y??"error"},m=(pe=$.response.usage)!=null?pe:void 0}else WP($)?(v.push($.annotation),$.annotation.type==="url_citation"?I.enqueue({type:"source",sourceType:"url",id:(dt=(Ge=(Ie=u.config).generateId)==null?void 0:Ge.call(Ie))!=null?dt:Wt(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"?I.enqueue({type:"source",sourceType:"document",id:(it=(st=(wt=u.config).generateId)==null?void 0:st.call(wt))!=null?it:Wt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}}):$.annotation.type==="container_file_citation"?I.enqueue({type:"source",sourceType:"document",id:(Br=(bt=(zt=u.config).generateId)==null?void 0:bt.call(zt))!=null?Br:Wt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,containerId:$.annotation.container_id}}}):$.annotation.type==="file_path"&&I.enqueue({type:"source",sourceType:"document",id:($r=(et=(ar=u.config).generateId)==null?void 0:et.call(ar))!=null?$r:Wt(),mediaType:"application/octet-stream",title:$.annotation.file_id,filename:$.annotation.file_id,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}})):GP($)&&I.enqueue({type:"error",error:$})},flush(R){const I={[a]:{responseId:y,..._.length>0?{logprobs:_}:{},...k!==void 0?{serviceTier:k}:{}}};R.enqueue({type:"finish",finishReason:h,usage:S1(m),providerMetadata:I})}})),request:{body:t},response:{headers:l}}}};function AP(e){return e.type==="response.output_text.delta"}function qP(e){return e.type==="response.output_item.done"}function LP(e){return e.type==="response.completed"||e.type==="response.incomplete"}function jP(e){return e.type==="response.failed"}function DP(e){return e.type==="response.created"}function UP(e){return e.type==="response.function_call_arguments.delta"}function zP(e){return e.type==="response.custom_tool_call_input.delta"}function ZP(e){return e.type==="response.image_generation_call.partial_image"}function FP(e){return e.type==="response.code_interpreter_call_code.delta"}function VP(e){return e.type==="response.code_interpreter_call_code.done"}function HP(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function BP(e){return e.type==="response.apply_patch_call_operation_diff.done"}function $1(e){return e.type==="response.output_item.added"}function WP(e){return e.type==="response.output_text.annotation.added"}function GP(e){return e.type==="error"}function R1(e){var t;if(e==null)return{};switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function yo(e){return JSON.stringify(e).slice(1,-1)}var JP=Te(()=>be(T({instructions:d().nullish(),speed:O().min(.25).max(4).default(1).nullish()}))),KP=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:s,providerOptions:a}){const i=[],l=await gn({provider:"openai",providerOptions:a,schema:JP}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const f in u){const p=u[f];p!==void 0&&(c[f]=p)}}return s&&i.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(e){var t,r,n;const o=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:c}=await nr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),body:s,failedResponseHandler:Hr,successfulResponseHandler:Mx(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},YP=Te(()=>be(T({text:d(),language:d().nullish(),duration:O().nullish(),words:q(T({word:d(),start:O(),end:O()})).nullish(),segments:q(T({id:O(),seek:O(),start:O(),end:O(),text:d(),tokens:q(O()),temperature:O(),avg_logprob:O(),compression_ratio:O(),no_speech_prob:O()})).nullish()}))),QP=Te(()=>be(T({include:q(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:O().min(0).max(1).default(0).optional(),timestampGranularities:q(de(["word","segment"])).default(["segment"]).optional()}))),P1={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"},XP=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await gn({provider:"openai",providerOptions:r,schema:QP}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([Go(e)]);s.append("model",this.modelId);const i=A5(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${i}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const f of u)s.append(`${c}[]`,String(f));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,a,i,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:f}=await this.getArgs(e),{value:p,responseHeaders:h,rawValue:m}=await dy({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Dt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Hr,successfulResponseHandler:or(YP),abortSignal:e.abortSignal,fetch:this.config.fetch}),_=p.language!=null&&p.language in P1?P1[p.language]:void 0;return{text:p.text,segments:(i=(a=(o=p.segments)==null?void 0:o.map(y=>({text:y.text,startSecond:y.start,endSecond:y.end})))!=null?a:(s=p.words)==null?void 0:s.map(y=>({text:y.word,startSecond:y.start,endSecond:y.end})))!=null?i:[],language:_,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:f,response:{timestamp:c,modelId:this.modelId,headers:h,body:m}}}},eM="3.0.48";function M1(e={}){var t,r;const n=(t=hy(Yo({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>qn({Authorization:`Bearer ${O5({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${eM}`),a=_=>new xR(_,{provider:`${o}.chat`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),i=_=>new PR(_,{provider:`${o}.completion`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),l=_=>new OR(_,{provider:`${o}.embedding`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),c=_=>new jR(_,{provider:`${o}.image`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),u=_=>new XP(_,{provider:`${o}.transcription`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),f=_=>new KP(_,{provider:`${o}.speech`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch}),p=_=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return h(_)},h=_=>new OP(_,{provider:`${o}.responses`,url:({path:y})=>`${n}${y}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),m=function(_){return p(_)};return m.specificationVersion="v3",m.languageModel=p,m.chat=a,m.completion=i,m.responses=h,m.embedding=l,m.embeddingModel=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.transcription=u,m.transcriptionModel=u,m.speech=f,m.speechModel=f,m.tools=IP,m}M1();var N1="vercel.ai.error",tM=Symbol.for(N1),O1,rM=class Yw extends Error{constructor({name:t,message:r,cause:n}){super(r),this[O1]=!0,this.name=t,this.cause=n}static isInstance(t){return Yw.hasMarker(t,N1)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};O1=tM;var Rt=rM,A1="AI_APICallError",q1=`vercel.ai.error.${A1}`,nM=Symbol.for(q1),L1,_n=class extends Rt{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:s,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:A1,message:e,cause:a}),this[L1]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(e){return Rt.hasMarker(e,q1)}};L1=nM;var j1="AI_EmptyResponseBodyError",D1=`vercel.ai.error.${j1}`,oM=Symbol.for(D1),U1,sM=class extends Rt{constructor({message:e="Empty response body"}={}){super({name:j1,message:e}),this[U1]=!0}static isInstance(e){return Rt.hasMarker(e,D1)}};U1=oM;function z1(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var Z1="AI_InvalidArgumentError",F1=`vercel.ai.error.${Z1}`,aM=Symbol.for(F1),V1,H1=class extends Rt{constructor({message:e,cause:t,argument:r}){super({name:Z1,message:e,cause:t}),this[V1]=!0,this.argument=r}static isInstance(e){return Rt.hasMarker(e,F1)}};V1=aM;var B1="AI_InvalidResponseDataError",W1=`vercel.ai.error.${B1}`,iM=Symbol.for(W1),G1,J1=class extends Rt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:B1,message:t}),this[G1]=!0,this.data=e}static isInstance(e){return Rt.hasMarker(e,W1)}};G1=iM;var K1="AI_JSONParseError",Y1=`vercel.ai.error.${K1}`,lM=Symbol.for(Y1),Q1,Wl=class extends Rt{constructor({text:e,cause:t}){super({name:K1,message:`JSON parsing failed: Text: ${e}.
595
- Error message: ${z1(t)}`,cause:t}),this[Q1]=!0,this.text=e}static isInstance(e){return Rt.hasMarker(e,Y1)}};Q1=lM;var X1="AI_LoadAPIKeyError",ew=`vercel.ai.error.${X1}`,cM=Symbol.for(ew),tw,Gl=class extends Rt{constructor({message:e}){super({name:X1,message:e}),this[tw]=!0}static isInstance(e){return Rt.hasMarker(e,ew)}};tw=cM;var rw="AI_NoSuchModelError",nw=`vercel.ai.error.${rw}`,uM=Symbol.for(nw),ow,sw=class extends Rt{constructor({errorName:e=rw,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[ow]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return Rt.hasMarker(e,nw)}};ow=uM;var aw="AI_TypeValidationError",iw=`vercel.ai.error.${aw}`,dM=Symbol.for(iw),lw,pM=class rf extends Rt{constructor({value:t,cause:r}){super({name:aw,message:`Type validation failed: Value: ${JSON.stringify(t)}.
596
- Error message: ${z1(r)}`,cause:r}),this[lw]=!0,this.value=t}static isInstance(t){return Rt.hasMarker(t,iw)}static wrap({value:t,cause:r}){return rf.isInstance(r)&&r.value===t?r:new rf({value:t,cause:r})}};lw=dM;var Sa=pM,cw="AI_UnsupportedFunctionalityError",uw=`vercel.ai.error.${cw}`,fM=Symbol.for(uw),dw,pw=class extends Rt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:cw,message:t}),this[dw]=!0,this.functionality=e}static isInstance(e){return Rt.hasMarker(e,uw)}};dw=fM;function fw(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function Jl(e){return Object.fromEntries([...e.headers])}var hM=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new H1({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},Kl=hM();function Np(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var mM=["fetch failed","failed to fetch"];function gM({error:e,url:t,requestBodyValues:r}){if(Np(e))return e;if(e instanceof TypeError&&mM.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new _n({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function yM(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function vM(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function hw(e,...t){const r=new Headers(vM(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var _M="3.0.18";function wM({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Gl({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Gl({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new Gl({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Gl({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var bM=/"__proto__"\s*:/,TM=/"constructor"\s*:/;function mw(e){const t=JSON.parse(e);return t===null||typeof t!="object"||bM.test(e)===!1&&TM.test(e)===!1?t:kM(t)}function kM(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Op(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return mw(e)}try{return mw(e)}finally{Error.stackTraceLimit=t}}var Ap=Symbol.for("vercel.ai.validator");function SM(e){return{[Ap]:!0,validate:e}}function CM(e){return typeof e=="object"&&e!==null&&Ap in e&&e[Ap]===!0&&"validate"in e}function IM(e){return CM(e)?e:typeof e=="function"?e():xM(e)}function xM(e){return SM(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Sa({value:t,cause:r.issues})}})}async function EM({value:e,schema:t}){const r=await Ca({value:e,schema:t});if(!r.success)throw Sa.wrap({value:e,cause:r.error});return r.value}async function Ca({value:e,schema:t}){const r=IM(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:Sa.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:Sa.wrap({value:e,cause:n}),rawValue:e}}}async function $M({text:e,schema:t}){try{const r=Op(e);return t==null?r:EM({value:r,schema:t})}catch(r){throw Wl.isInstance(r)||Sa.isInstance(r)?r:new Wl({text:e,cause:r})}}async function gw({text:e,schema:t}){try{const r=Op(e);return t==null?{success:!0,value:r,rawValue:r}:await Ca({value:r,schema:t})}catch(r){return{success:!1,error:Wl.isInstance(r)?r:new Wl({text:e,cause:r}),rawValue:void 0}}}function yw(e){try{return Op(e),!0}catch{return!1}}function RM({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Fo).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await gw({text:r,schema:t}))}}))}async function vw({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Ca({value:t[e],schema:r});if(!n.success)throw new H1({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var PM=()=>globalThis.fetch,_w=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>MM({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),MM=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=PM()})=>{try{const i=await a(e,{method:"POST",headers:hw(t,`ai-sdk/provider-utils/${_M}`,yM()),body:r.content,signal:s}),l=Jl(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Np(u)||_n.isInstance(u)?u:new _n({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Np(c)||_n.isInstance(c))?c:new _n({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw gM({error:i,url:e,requestBodyValues:r.values})}},NM=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=Jl(n);if(a.trim()==="")return{responseHeaders:i,value:new _n({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await $M({text:a,schema:e});return{responseHeaders:i,value:new _n({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new _n({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},OM=e=>async({response:t})=>{const r=Jl(t);if(t.body==null)throw new sM({});return{responseHeaders:r,value:RM({stream:t.body,schema:e})}},AM=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await gw({text:o,schema:e}),a=Jl(t);if(!s.success)throw new _n({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:qM}=globalThis;function LM(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return qM(t)}function jM(e){return e instanceof Uint8Array?LM(e):e}function DM(e){return e?.replace(/\/$/,"")}function Ia(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function UM(e){const t=[];for(const{role:r,content:n,...o}of e){const s=Ia({...o});switch(r){case"system":{t.push({role:"system",content:n,...s});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...Ia(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=Ia(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,${jM(a.data)}`},...i}}else throw new pw({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=Ia(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of n){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const c=Ia(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...c})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return t}function ww({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function bw(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var qp=T({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),zM=T({error:T({message:d(),type:d().nullish(),param:Tt().nullish(),code:ae([d(),O()]).nullish()})}),ZM={errorSchema:zM,errorToMessage:e=>e.error.message};function FM({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new pw({functionality:`tool choice type: ${s}`})}}}var VM=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:ZM;this.chunkSchema=BM(o.errorSchema),this.failedResponseHandler=NM(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:f,tools:p}){var h,m,_,y;const w=[],v=Object.assign((h=await vw({provider:"openai-compatible",providerOptions:i,schema:qp}))!=null?h:{},(m=await vw({provider:this.providerOptionsName,providerOptions:i,schema:qp}))!=null?m:{});o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:g,toolChoice:S,toolWarnings:b}=FM({tools:p,toolChoice:f});return{args:{model:this.modelId,user:v.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(_=c.name)!=null?_:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((y=i?.[this.providerOptionsName])!=null?y:{}).filter(([k])=>!Object.keys(qp.shape).includes(k))),reasoning_effort:v.reasoningEffort,verbosity:v.textVerbosity,messages:UM(e),tools:g,tool_choice:S},warnings:[...w,...b]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,f,p,h,m,_,y,w;const{args:v,warnings:g}=await this.getArgs({...e}),S=JSON.stringify(v),{responseHeaders:b,value:k,rawValue:C}=await _w({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:fw(this.config.headers(),e.headers),body:v,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:AM(HM),abortSignal:e.abortSignal,fetch:this.config.fetch}),R=k.choices[0],I=[],j=R.message.content;j!=null&&j.length>0&&I.push({type:"text",text:j});const N=(t=R.message.reasoning_content)!=null?t:R.message.reasoning;if(N!=null&&N.length>0&&I.push({type:"reasoning",text:N}),R.message.tool_calls!=null)for(const H of R.message.tool_calls)I.push({type:"tool-call",toolCallId:(r=H.id)!=null?r:Kl(),toolName:H.function.name,input:H.function.arguments});const L={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:C}))},z=(s=k.usage)==null?void 0:s.completion_tokens_details;return z?.accepted_prediction_tokens!=null&&(L[this.providerOptionsName].acceptedPredictionTokens=z?.accepted_prediction_tokens),z?.rejected_prediction_tokens!=null&&(L[this.providerOptionsName].rejectedPredictionTokens=z?.rejected_prediction_tokens),{content:I,finishReason:bw(R.finish_reason),usage:{inputTokens:(i=(a=k.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=k.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(f=(u=k.usage)==null?void 0:u.total_tokens)!=null?f:void 0,reasoningTokens:(m=(h=(p=k.usage)==null?void 0:p.completion_tokens_details)==null?void 0:h.reasoning_tokens)!=null?m:void 0,cachedInputTokens:(w=(y=(_=k.usage)==null?void 0:_.prompt_tokens_details)==null?void 0:y.cached_tokens)!=null?w:void 0},providerMetadata:L,request:{body:S},response:{...ww(k),headers:b,body:C},warnings:g}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await _w({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:fw(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:OM(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let f=!0;const p=this.providerOptionsName;let h=!1,m=!1;return{stream:i.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:n})},transform(_,y){var w,v,g,S,b,k,C,R,I,j,N,L,z;if(e.includeRawChunks&&y.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){c="error",y.enqueue({type:"error",error:_.error});return}const H=_.value;if(s?.processChunk(_.rawValue),"error"in H){c="error",y.enqueue({type:"error",error:H.error.message});return}if(f&&(f=!1,y.enqueue({type:"response-metadata",...ww(H)})),H.usage!=null){const{prompt_tokens:V,completion_tokens:se,total_tokens:D,prompt_tokens_details:E,completion_tokens_details:U}=H.usage;u.promptTokens=V??void 0,u.completionTokens=se??void 0,u.totalTokens=D??void 0,U?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=U?.reasoning_tokens),U?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=U?.accepted_prediction_tokens),U?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=U?.rejected_prediction_tokens),E?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=E?.cached_tokens)}const ee=H.choices[0];if(ee?.finish_reason!=null&&(c=bw(ee.finish_reason)),ee?.delta==null)return;const te=ee.delta,X=(w=te.reasoning_content)!=null?w:te.reasoning;if(X&&(h||(y.enqueue({type:"reasoning-start",id:"reasoning-0"}),h=!0),y.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:X})),te.content&&(m||(y.enqueue({type:"text-start",id:"txt-0"}),m=!0),y.enqueue({type:"text-delta",id:"txt-0",delta:te.content})),te.tool_calls!=null)for(const V of te.tool_calls){const se=V.index;if(l[se]==null){if(V.id==null)throw new J1({data:V,message:"Expected 'id' to be a string."});if(((v=V.function)==null?void 0:v.name)==null)throw new J1({data:V,message:"Expected 'function.name' to be a string."});y.enqueue({type:"tool-input-start",id:V.id,toolName:V.function.name}),l[se]={id:V.id,type:"function",function:{name:V.function.name,arguments:(g=V.function.arguments)!=null?g:""},hasFinished:!1};const E=l[se];((S=E.function)==null?void 0:S.name)!=null&&((b=E.function)==null?void 0:b.arguments)!=null&&(E.function.arguments.length>0&&y.enqueue({type:"tool-input-delta",id:E.id,delta:E.function.arguments}),yw(E.function.arguments)&&(y.enqueue({type:"tool-input-end",id:E.id}),y.enqueue({type:"tool-call",toolCallId:(k=E.id)!=null?k:Kl(),toolName:E.function.name,input:E.function.arguments}),E.hasFinished=!0));continue}const D=l[se];D.hasFinished||(((C=V.function)==null?void 0:C.arguments)!=null&&(D.function.arguments+=(I=(R=V.function)==null?void 0:R.arguments)!=null?I:""),y.enqueue({type:"tool-input-delta",id:D.id,delta:(j=V.function.arguments)!=null?j:""}),((N=D.function)==null?void 0:N.name)!=null&&((L=D.function)==null?void 0:L.arguments)!=null&&yw(D.function.arguments)&&(y.enqueue({type:"tool-input-end",id:D.id}),y.enqueue({type:"tool-call",toolCallId:(z=D.id)!=null?z:Kl(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0))}},flush(_){var y,w,v,g,S,b;h&&_.enqueue({type:"reasoning-end",id:"reasoning-0"}),m&&_.enqueue({type:"text-end",id:"txt-0"});for(const C of l.filter(R=>!R.hasFinished))_.enqueue({type:"tool-input-end",id:C.id}),_.enqueue({type:"tool-call",toolCallId:(y=C.id)!=null?y:Kl(),toolName:C.function.name,input:C.function.arguments});const k={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(k[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(k[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),_.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(v=u.completionTokens)!=null?v:void 0,totalTokens:(g=u.totalTokens)!=null?g:void 0,reasoningTokens:(S=u.completionTokensDetails.reasoningTokens)!=null?S:void 0,cachedInputTokens:(b=u.promptTokensDetails.cachedTokens)!=null?b:void 0},providerMetadata:k})}})),request:{body:o},response:{headers:a}}}},Tw=T({prompt_tokens:O().nullish(),completion_tokens:O().nullish(),total_tokens:O().nullish(),prompt_tokens_details:T({cached_tokens:O().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:O().nullish(),accepted_prediction_tokens:O().nullish(),rejected_prediction_tokens:O().nullish()}).nullish()}).nullish(),HM=T({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(T({message:T({role:P("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({id:d().nullish(),function:T({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:Tw}),BM=e=>ae([T({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(T({delta:T({role:de(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:q(T({index:O(),id:d().nullish(),function:T({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:Tw}),e]);T({echo:ve().optional(),logitBias:_e(d(),O()).optional(),suffix:d().optional(),user:d().optional()});var WM=T({prompt_tokens:O(),completion_tokens:O(),total_tokens:O()});T({id:d().nullish(),created:O().nullish(),model:d().nullish(),choices:q(T({text:d(),finish_reason:d()})),usage:WM.nullish()}),T({dimensions:O().optional(),user:d().optional()}),T({data:q(T({embedding:q(O())})),usage:T({prompt_tokens:O()}).nullish(),providerMetadata:_e(d(),_e(d(),Tt())).optional()}),T({data:q(T({b64_json:d()}))});var kw=e=>{var t,r;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(r=e.prompt_cache_miss_tokens)!=null?r:NaN}}},GM={extractMetadata:async({parsedBody:e})=>{const t=await Ca({value:e,schema:JM});return!t.success||t.value.usage==null?void 0:kw(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await Ca({value:t,schema:KM});o.success&&((n=(r=o.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>kw(e)}}},Sw=T({prompt_cache_hit_tokens:O().nullish(),prompt_cache_miss_tokens:O().nullish()}),JM=T({usage:Sw.nullish()}),KM=T({choices:q(T({finish_reason:d().nullish()})).nullish(),usage:Sw.nullish()}),YM="1.0.30";function Cw(e={}){var t;const r=DM((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>hw({Authorization:`Bearer ${wM({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${YM}`);class o extends VM{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const p=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:p}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=i=>new o(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:GM}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new sw({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new sw({modelId:i,modelType:"imageModel"})},a}Cw();const Iw=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:s}of r.tools){const a=async(i,l)=>e.callTool({name:n,arguments:i},{signal:l?.abortSignal});t[n]=fy({description:o,inputSchema:Qo({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}};function QM(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
594
+ ${t}:`]}}function h1({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function m1(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var D7=$e(()=>xe(k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:j(k({text:d(),finish_reason:d(),logprobs:k({tokens:j(d()),token_logprobs:j(N()),top_logprobs:j(Se(d(),N())).nullish()}).nullish()})),usage:k({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()}).nullish()}))),U7=$e(()=>xe(le([k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:j(k({text:d(),finish_reason:d().nullish(),index:N(),logprobs:k({tokens:j(d()),token_logprobs:j(N()),top_logprobs:j(Se(d(),N())).nullish()}).nullish()})),usage:k({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()}).nullish()}),Mp]))),g1=$e(()=>xe(k({echo:Te().optional(),logitBias:Se(d(),N()).optional(),suffix:d().optional(),user:d().optional(),logprobs:le([Te(),N()]).optional()}))),z7=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:f,providerOptions:p}){const h=[],m={...await _n({provider:"openai",providerOptions:p,schema:g1}),...await _n({provider:this.providerOptionsName,providerOptions:p,schema:g1})};o!=null&&h.push({type:"unsupported",feature:"topK"}),c?.length&&h.push({type:"unsupported",feature:"tools"}),u!=null&&h.push({type:"unsupported",feature:"toolChoice"}),l!=null&&l.type!=="text"&&h.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:_,stopSequences:g}=L7({prompt:e}),w=[...g??[],...i??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,seed:f,prompt:_,stop:w.length>0?w:void 0},warnings:h}}async doGenerate(e){var t;const{args:r,warnings:n}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:a}=await ar({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Vt(this.config.headers(),e.headers),body:r,failedResponseHandler:Hr,successfulResponseHandler:ir(D7),abortSignal:e.abortSignal,fetch:this.config.fetch}),i=s.choices[0],l={openai:{}};return i.logprobs!=null&&(l.openai.logprobs=i.logprobs),{content:[{type:"text",text:i.text}],usage:f1(s.usage),finishReason:{unified:m1(i.finish_reason),raw:(t=i.finish_reason)!=null?t:void 0},request:{body:r},response:{...h1(s),headers:o,body:a},providerMetadata:l,warnings:n}}async doStream(e){const{args:t,warnings:r}=await this.getArgs(e),n={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await ar({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Vt(this.config.headers(),e.headers),body:n,failedResponseHandler:Hr,successfulResponseHandler:Nl(U7),abortSignal:e.abortSignal,fetch:this.config.fetch});let a={unified:"other",raw:void 0};const i={openai:{}};let l,c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,f){if(e.includeRawChunks&&f.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:u.error});return}const p=u.value;if("error"in p){a={unified:"error",raw:void 0},f.enqueue({type:"error",error:p.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...h1(p)}),f.enqueue({type:"text-start",id:"0"})),p.usage!=null&&(l=p.usage);const h=p.choices[0];h?.finish_reason!=null&&(a={unified:m1(h.finish_reason),raw:h.finish_reason}),h?.logprobs!=null&&(i.openai.logprobs=h.logprobs),h?.text!=null&&h.text.length>0&&f.enqueue({type:"text-delta",id:"0",delta:h.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:a,providerMetadata:i,usage:f1(l)})}})),request:{body:n},response:{headers:o}}}},Z7=$e(()=>xe(k({dimensions:N().optional(),user:d().optional()}))),F7=$e(()=>xe(k({data:j(k({embedding:j(N())})),usage:k({prompt_tokens:N()}).nullish()}))),V7=class{constructor(e,t){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:r,providerOptions:n}){var o;if(e.length>this.maxEmbeddingsPerCall)throw new $6({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});const s=(o=await _n({provider:"openai",providerOptions:n,schema:Z7}))!=null?o:{},{responseHeaders:a,value:i,rawValue:l}=await ar({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Vt(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Hr,successfulResponseHandler:ir(F7),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:a,body:l}}}},y1=$e(()=>xe(k({created:N().nullish(),data:j(k({b64_json:d(),revised_prompt:d().nullish()})),background:d().nullish(),output_format:d().nullish(),size:d().nullish(),quality:d().nullish(),usage:k({input_tokens:N().nullish(),output_tokens:N().nullish(),total_tokens:N().nullish(),input_tokens_details:k({image_tokens:N().nullish(),text_tokens:N().nullish()}).nullish()}).nullish()}))),H7={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},B7=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function J7(e){return B7.some(t=>e.startsWith(t))}var W7=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get maxImagesPerCall(){var e;return(e=H7[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:e,files:t,mask:r,n,size:o,aspectRatio:s,seed:a,providerOptions:i,headers:l,abortSignal:c}){var u,f,p,h,m,_,g,w,v,y,S;const b=[];s!=null&&b.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),a!=null&&b.push({type:"unsupported",feature:"seed"});const T=(p=(f=(u=this.config._internal)==null?void 0:u.currentDate)==null?void 0:f.call(u))!=null?p:new Date;if(t!=null){const{value:C,responseHeaders:L}=await hy({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:Vt(this.config.headers(),l),formData:A6({model:this.modelId,prompt:e,image:await Promise.all(t.map(O=>O.type==="file"?new Blob([O.data instanceof Uint8Array?new Blob([O.data],{type:O.mediaType}):new Blob([rs(O.data)],{type:O.mediaType})],{type:O.mediaType}):ey(O.url))),mask:r!=null?await G7(r):void 0,n,size:o,...(h=i.openai)!=null?h:{}}),failedResponseHandler:Hr,successfulResponseHandler:ir(y1),abortSignal:c,fetch:this.config.fetch});return{images:C.data.map(O=>O.b64_json),warnings:b,usage:C.usage!=null?{inputTokens:(m=C.usage.input_tokens)!=null?m:void 0,outputTokens:(_=C.usage.output_tokens)!=null?_:void 0,totalTokens:(g=C.usage.total_tokens)!=null?g:void 0}:void 0,response:{timestamp:T,modelId:this.modelId,headers:L},providerMetadata:{openai:{images:C.data.map((O,q)=>{var z,H,ee,re,X,V;return{...O.revised_prompt?{revisedPrompt:O.revised_prompt}:{},created:(z=C.created)!=null?z:void 0,size:(H=C.size)!=null?H:void 0,quality:(ee=C.quality)!=null?ee:void 0,background:(re=C.background)!=null?re:void 0,outputFormat:(X=C.output_format)!=null?X:void 0,...v1((V=C.usage)==null?void 0:V.input_tokens_details,q,C.data.length)}})}}}}const{value:x,responseHeaders:R}=await ar({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Vt(this.config.headers(),l),body:{model:this.modelId,prompt:e,n,size:o,...(w=i.openai)!=null?w:{},...J7(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Hr,successfulResponseHandler:ir(y1),abortSignal:c,fetch:this.config.fetch});return{images:x.data.map(C=>C.b64_json),warnings:b,usage:x.usage!=null?{inputTokens:(v=x.usage.input_tokens)!=null?v:void 0,outputTokens:(y=x.usage.output_tokens)!=null?y:void 0,totalTokens:(S=x.usage.total_tokens)!=null?S:void 0}:void 0,response:{timestamp:T,modelId:this.modelId,headers:R},providerMetadata:{openai:{images:x.data.map((C,L)=>{var O,q,z,H,ee,re;return{...C.revised_prompt?{revisedPrompt:C.revised_prompt}:{},created:(O=x.created)!=null?O:void 0,size:(q=x.size)!=null?q:void 0,quality:(z=x.quality)!=null?z:void 0,background:(H=x.background)!=null?H:void 0,outputFormat:(ee=x.output_format)!=null?ee:void 0,...v1((re=x.usage)==null?void 0:re.input_tokens_details,L,x.data.length)}})}}}}};function v1(e,t,r){if(e==null)return{};const n={};if(e.image_tokens!=null){const o=Math.floor(e.image_tokens/r),s=e.image_tokens-o*(r-1);n.imageTokens=t===r-1?s:o}if(e.text_tokens!=null){const o=Math.floor(e.text_tokens/r),s=e.text_tokens-o*(r-1);n.textTokens=t===r-1?s:o}return n}async function G7(e){if(!e)return;if(e.type==="url")return ey(e.url);const t=e.data instanceof Uint8Array?e.data:rs(e.data);return new Blob([t],{type:e.mediaType})}var _1=$e(()=>xe(k({callId:d(),operation:Qe("type",[k({type:P("create_file"),path:d(),diff:d()}),k({type:P("delete_file"),path:d()}),k({type:P("update_file"),path:d(),diff:d()})])}))),w1=$e(()=>xe(k({status:ge(["completed","failed"]),output:d().optional()}))),K7=$r({id:"openai.apply_patch",inputSchema:_1,outputSchema:w1}),Y7=K7,Q7=$e(()=>xe(k({code:d().nullish(),containerId:d()}))),X7=$e(()=>xe(k({outputs:j(Qe("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullish()}))),eP=$e(()=>xe(k({container:le([d(),k({fileIds:j(d()).optional()})]).optional()}))),tP=$r({id:"openai.code_interpreter",inputSchema:Q7,outputSchema:X7}),rP=(e={})=>tP(e),nP=$e(()=>xe(k({name:d(),description:d().optional(),format:le([k({type:P("grammar"),syntax:ge(["regex","lark"]),definition:d()}),k({type:P("text")})]).optional()}))),oP=$e(()=>xe(d())),sP=z5({id:"openai.custom",inputSchema:oP}),aP=e=>sP(e),b1=k({key:d(),type:ge(["eq","ne","gt","gte","lt","lte","in","nin"]),value:le([d(),N(),Te(),j(d())])}),k1=k({type:ge(["and","or"]),filters:j(le([b1,Xi(()=>k1)]))}),iP=$e(()=>xe(k({vectorStoreIds:j(d()),maxNumResults:N().optional(),ranking:k({ranker:d().optional(),scoreThreshold:N().optional()}).optional(),filters:le([b1,k1]).optional()}))),lP=$e(()=>xe(k({queries:j(d()),results:j(k({attributes:Se(d(),Ne()),fileId:d(),filename:d(),score:N(),text:d()})).nullable()}))),cP=$r({id:"openai.file_search",inputSchema:k({}),outputSchema:lP}),uP=$e(()=>xe(k({background:ge(["auto","opaque","transparent"]).optional(),inputFidelity:ge(["low","high"]).optional(),inputImageMask:k({fileId:d().optional(),imageUrl:d().optional()}).optional(),model:d().optional(),moderation:ge(["auto"]).optional(),outputCompression:N().int().min(0).max(100).optional(),outputFormat:ge(["png","jpeg","webp"]).optional(),partialImages:N().int().min(0).max(3).optional(),quality:ge(["auto","low","medium","high"]).optional(),size:ge(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),dP=$e(()=>xe(k({}))),pP=$e(()=>xe(k({result:d()}))),fP=$r({id:"openai.image_generation",inputSchema:dP,outputSchema:pP}),hP=(e={})=>fP(e),T1=$e(()=>xe(k({action:k({type:P("exec"),command:j(d()),timeoutMs:N().optional(),user:d().optional(),workingDirectory:d().optional(),env:Se(d(),d()).optional()})}))),S1=$e(()=>xe(k({output:d()}))),mP=$r({id:"openai.local_shell",inputSchema:T1,outputSchema:S1}),C1=$e(()=>xe(k({action:k({commands:j(d()),timeoutMs:N().optional(),maxOutputLength:N().optional()})}))),Np=$e(()=>xe(k({output:j(k({stdout:d(),stderr:d(),outcome:Qe("type",[k({type:P("timeout")}),k({type:P("exit"),exitCode:N()})])}))}))),gP=j(Qe("type",[k({type:P("skillReference"),skillId:d(),version:d().optional()}),k({type:P("inline"),name:d(),description:d(),source:k({type:P("base64"),mediaType:P("application/zip"),data:d()})})])).optional(),yP=$e(()=>xe(k({environment:le([k({type:P("containerAuto"),fileIds:j(d()).optional(),memoryLimit:ge(["1g","4g","16g","64g"]).optional(),networkPolicy:Qe("type",[k({type:P("disabled")}),k({type:P("allowlist"),allowedDomains:j(d()),domainSecrets:j(k({domain:d(),name:d(),value:d()})).optional()})]).optional(),skills:gP}),k({type:P("containerReference"),containerId:d()}),k({type:P("local").optional(),skills:j(k({name:d(),description:d(),path:d()})).optional()})]).optional()}))),vP=$r({id:"openai.shell",inputSchema:C1,outputSchema:Np}),_P=$e(()=>xe(k({execution:ge(["server","client"]).optional(),description:d().optional(),parameters:Se(d(),Ne()).optional()}))),Ap=$e(()=>xe(k({arguments:Ne().optional(),call_id:d().nullish()}))),qp=$e(()=>xe(k({tools:j(Se(d(),Ne()))}))),wP=$r({id:"openai.tool_search",inputSchema:Ap,outputSchema:qp}),bP=(e={})=>wP(e),kP=$e(()=>xe(k({externalWebAccess:Te().optional(),filters:k({allowedDomains:j(d()).optional()}).optional(),searchContextSize:ge(["low","medium","high"]).optional(),userLocation:k({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),TP=$e(()=>xe(k({}))),SP=$e(()=>xe(k({action:Qe("type",[k({type:P("search"),query:d().optional()}),k({type:P("openPage"),url:d().nullish()}),k({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional(),sources:j(Qe("type",[k({type:P("url"),url:d()}),k({type:P("api"),name:d()})])).optional()}))),CP=$r({id:"openai.web_search",inputSchema:TP,outputSchema:SP}),xP=(e={})=>CP(e),IP=$e(()=>xe(k({searchContextSize:ge(["low","medium","high"]).optional(),userLocation:k({type:P("approximate"),country:d().optional(),city:d().optional(),region:d().optional(),timezone:d().optional()}).optional()}))),$P=$e(()=>xe(k({}))),EP=$e(()=>xe(k({action:Qe("type",[k({type:P("search"),query:d().optional()}),k({type:P("openPage"),url:d().nullish()}),k({type:P("findInPage"),url:d().nullish(),pattern:d().nullish()})]).optional()}))),RP=$r({id:"openai.web_search_preview",inputSchema:$P,outputSchema:EP}),jp=Xi(()=>le([d(),N(),Te(),Zs(),j(jp),Se(d(),jp)])),PP=$e(()=>xe(k({serverLabel:d(),allowedTools:le([j(d()),k({readOnly:Te().optional(),toolNames:j(d()).optional()})]).optional(),authorization:d().optional(),connectorId:d().optional(),headers:Se(d(),d()).optional(),requireApproval:le([ge(["always","never"]),k({never:k({toolNames:j(d()).optional()}).optional()})]).optional(),serverDescription:d().optional(),serverUrl:d().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,"One of serverUrl or connectorId must be provided."))),MP=$e(()=>xe(k({}))),OP=$e(()=>xe(k({type:P("call"),serverLabel:d(),name:d(),arguments:d(),output:d().nullish(),error:le([d(),jp]).optional()}))),NP=$r({id:"openai.mcp",inputSchema:MP,outputSchema:OP}),AP=e=>NP(e),qP={applyPatch:Y7,customTool:aP,codeInterpreter:rP,fileSearch:cP,imageGeneration:hP,localShell:mP,shell:vP,webSearchPreview:RP,webSearch:xP,mcp:AP,toolSearch:bP};function x1(e){var t,r,n,o;if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const s=e.input_tokens,a=e.output_tokens,i=(r=(t=e.input_tokens_details)==null?void 0:t.cached_tokens)!=null?r:0,l=(o=(n=e.output_tokens_details)==null?void 0:n.reasoning_tokens)!=null?o:0;return{inputTokens:{total:s,noCache:s-i,cacheRead:i,cacheWrite:void 0},outputTokens:{total:a,text:a-l,reasoning:l},raw:e}}function I1(e,t){return t?t.some(r=>e.startsWith(r)):!1}async function jP({prompt:e,toolNameMapping:t,systemMessageMode:r,providerOptionsName:n,fileIdPrefixes:o,store:s,hasConversation:a=!1,hasLocalShellTool:i=!1,hasShellTool:l=!1,hasApplyPatchTool:c=!1,customProviderToolNames:u}){var f,p,h,m,_,g,w,v,y,S,b,T,x,R,C,L,O;let q=[];const z=[],H=new Set;for(const{role:ee,content:re}of e)switch(ee){case"system":{switch(r){case"system":{q.push({role:"system",content:re});break}case"developer":{q.push({role:"developer",content:re});break}case"remove":{z.push({type:"other",message:"system messages are removed for this model"});break}default:{const X=r;throw new Error(`Unsupported system message mode: ${X}`)}}break}case"user":{q.push({role:"user",content:re.map((X,V)=>{var ie,D,E;switch(X.type){case"text":return{type:"input_text",text:X.text};case"file":if(X.mediaType.startsWith("image/")){const U=X.mediaType==="image/*"?"image/jpeg":X.mediaType;return{type:"input_image",...X.data instanceof URL?{image_url:X.data.toString()}:typeof X.data=="string"&&I1(X.data,o)?{file_id:X.data}:{image_url:`data:${U};base64,${os(X.data)}`},detail:(D=(ie=X.providerOptions)==null?void 0:ie[n])==null?void 0:D.imageDetail}}else{if(X.mediaType==="application/pdf")return X.data instanceof URL?{type:"input_file",file_url:X.data.toString()}:{type:"input_file",...typeof X.data=="string"&&I1(X.data,o)?{file_id:X.data}:{filename:(E=X.filename)!=null?E:`part-${V}.pdf`,file_data:`data:application/pdf;base64,${os(X.data)}`}};throw new Qr({functionality:`file part media type ${X.mediaType}`})}}})});break}case"assistant":{const X={};for(const V of re)switch(V.type){case"text":{const ie=(f=V.providerOptions)==null?void 0:f[n],D=ie?.itemId,E=ie?.phase;if(a&&D!=null)break;if(s&&D!=null){q.push({type:"item_reference",id:D});break}q.push({role:"assistant",content:[{type:"output_text",text:V.text}],id:D,...E!=null&&{phase:E}});break}case"tool-call":{const ie=(g=(h=(p=V.providerOptions)==null?void 0:p[n])==null?void 0:h.itemId)!=null?g:(_=(m=V.providerMetadata)==null?void 0:m[n])==null?void 0:_.itemId;if(a&&ie!=null)break;const D=t.toProviderToolName(V.toolName);if(D==="tool_search"){if(s&&ie!=null){q.push({type:"item_reference",id:ie});break}const E=typeof V.input=="string"?await dy({text:V.input,schema:Ap}):await Ct({value:V.input,schema:Ap}),U=E.call_id!=null?"client":"server";q.push({type:"tool_search_call",id:ie??V.toolCallId,execution:U,call_id:(w=E.call_id)!=null?w:null,status:"completed",arguments:E.arguments});break}if(V.providerExecuted){s&&ie!=null&&q.push({type:"item_reference",id:ie});break}if(s&&ie!=null){q.push({type:"item_reference",id:ie});break}if(i&&D==="local_shell"){const E=await Ct({value:V.input,schema:T1});q.push({type:"local_shell_call",call_id:V.toolCallId,id:ie,action:{type:"exec",command:E.action.command,timeout_ms:E.action.timeoutMs,user:E.action.user,working_directory:E.action.workingDirectory,env:E.action.env}});break}if(l&&D==="shell"){const E=await Ct({value:V.input,schema:C1});q.push({type:"shell_call",call_id:V.toolCallId,id:ie,status:"completed",action:{commands:E.action.commands,timeout_ms:E.action.timeoutMs,max_output_length:E.action.maxOutputLength}});break}if(c&&D==="apply_patch"){const E=await Ct({value:V.input,schema:_1});q.push({type:"apply_patch_call",call_id:E.callId,id:ie,status:"completed",operation:E.operation});break}if(u?.has(D)){q.push({type:"custom_tool_call",call_id:V.toolCallId,name:D,input:typeof V.input=="string"?V.input:JSON.stringify(V.input),id:ie});break}q.push({type:"function_call",call_id:V.toolCallId,name:D,arguments:JSON.stringify(V.input),id:ie});break}case"tool-result":{if(V.output.type==="execution-denied"||V.output.type==="json"&&typeof V.output.value=="object"&&V.output.value!=null&&"type"in V.output.value&&V.output.value.type==="execution-denied"||a)break;const ie=t.toProviderToolName(V.toolName);if(ie==="tool_search"){const D=(S=(y=(v=V.providerOptions)==null?void 0:v[n])==null?void 0:y.itemId)!=null?S:V.toolCallId;if(s)q.push({type:"item_reference",id:D});else if(V.output.type==="json"){const E=await Ct({value:V.output.value,schema:qp});q.push({type:"tool_search_output",id:D,execution:"server",call_id:null,status:"completed",tools:E.tools})}break}if(l&&ie==="shell"){if(V.output.type==="json"){const D=await Ct({value:V.output.value,schema:Np});q.push({type:"shell_call_output",call_id:V.toolCallId,output:D.output.map(E=>({stdout:E.stdout,stderr:E.stderr,outcome:E.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:E.outcome.exitCode}}))})}break}if(s){const D=(x=(T=(b=V.providerOptions)==null?void 0:b[n])==null?void 0:T.itemId)!=null?x:V.toolCallId;q.push({type:"item_reference",id:D})}else z.push({type:"other",message:`Results for OpenAI tool ${V.toolName} are not sent to the API when store is false`});break}case"reasoning":{const ie=await _n({provider:n,providerOptions:V.providerOptions,schema:LP}),D=ie?.itemId;if(a&&D!=null)break;if(D!=null){const E=X[D];if(s)E===void 0&&(q.push({type:"item_reference",id:D}),X[D]={type:"reasoning",id:D,summary:[]});else{const U=[];V.text.length>0?U.push({type:"summary_text",text:V.text}):E!==void 0&&z.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(V)}.`}),E===void 0?(X[D]={type:"reasoning",id:D,encrypted_content:ie?.reasoningEncryptedContent,summary:U},q.push(X[D])):(E.summary.push(...U),ie?.reasoningEncryptedContent!=null&&(E.encrypted_content=ie.reasoningEncryptedContent))}}else{const E=ie?.reasoningEncryptedContent;if(E!=null){const U=[];V.text.length>0&&U.push({type:"summary_text",text:V.text}),q.push({type:"reasoning",encrypted_content:E,summary:U})}else z.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(V)}.`})}break}}break}case"tool":{for(const X of re){if(X.type==="tool-approval-response"){const E=X;if(H.has(E.approvalId))continue;H.add(E.approvalId),s&&q.push({type:"item_reference",id:E.approvalId}),q.push({type:"mcp_approval_response",approval_request_id:E.approvalId,approve:E.approved});continue}const V=X.output;if(V.type==="execution-denied"&&((C=(R=V.providerOptions)==null?void 0:R.openai)==null?void 0:C.approvalId))continue;const ie=t.toProviderToolName(X.toolName);if(ie==="tool_search"&&V.type==="json"){const E=await Ct({value:V.value,schema:qp});q.push({type:"tool_search_output",execution:"client",call_id:X.toolCallId,status:"completed",tools:E.tools});continue}if(i&&ie==="local_shell"&&V.type==="json"){const E=await Ct({value:V.value,schema:S1});q.push({type:"local_shell_call_output",call_id:X.toolCallId,output:E.output});continue}if(l&&ie==="shell"&&V.type==="json"){const E=await Ct({value:V.value,schema:Np});q.push({type:"shell_call_output",call_id:X.toolCallId,output:E.output.map(U=>({stdout:U.stdout,stderr:U.stderr,outcome:U.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:U.outcome.exitCode}}))});continue}if(c&&X.toolName==="apply_patch"&&V.type==="json"){const E=await Ct({value:V.value,schema:w1});q.push({type:"apply_patch_call_output",call_id:X.toolCallId,status:E.status,output:E.output});continue}if(u?.has(ie)){let E;switch(V.type){case"text":case"error-text":E=V.value;break;case"execution-denied":E=(L=V.reason)!=null?L:"Tool execution denied.";break;case"json":case"error-json":E=JSON.stringify(V.value);break;case"content":E=V.value.map(U=>{var Z;switch(U.type){case"text":return{type:"input_text",text:U.text};case"image-data":return{type:"input_image",image_url:`data:${U.mediaType};base64,${U.data}`};case"image-url":return{type:"input_image",image_url:U.url};case"file-data":return{type:"input_file",filename:(Z=U.filename)!=null?Z:"data",file_data:`data:${U.mediaType};base64,${U.data}`};case"file-url":return{type:"input_file",file_url:U.url};default:z.push({type:"other",message:`unsupported custom tool content part type: ${U.type}`});return}}).filter(ny);break;default:E=""}q.push({type:"custom_tool_call_output",call_id:X.toolCallId,output:E});continue}let D;switch(V.type){case"text":case"error-text":D=V.value;break;case"execution-denied":D=(O=V.reason)!=null?O:"Tool execution denied.";break;case"json":case"error-json":D=JSON.stringify(V.value);break;case"content":D=V.value.map(E=>{var U;switch(E.type){case"text":return{type:"input_text",text:E.text};case"image-data":return{type:"input_image",image_url:`data:${E.mediaType};base64,${E.data}`};case"image-url":return{type:"input_image",image_url:E.url};case"file-data":return{type:"input_file",filename:(U=E.filename)!=null?U:"data",file_data:`data:${E.mediaType};base64,${E.data}`};case"file-url":return{type:"input_file",file_url:E.url};default:{z.push({type:"other",message:`unsupported tool content part type: ${E.type}`});return}}}).filter(ny);break}q.push({type:"function_call_output",call_id:X.toolCallId,output:D})}break}default:{const X=ee;throw new Error(`Unsupported role: ${X}`)}}return!s&&q.some(ee=>"type"in ee&&ee.type==="reasoning"&&ee.encrypted_content==null)&&(z.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),q=q.filter(ee=>!("type"in ee)||ee.type!=="reasoning"||ee.encrypted_content!=null)),{input:q,warnings:z}}var LP=k({itemId:d().nullish(),reasoningEncryptedContent:d().nullish()});function Lp({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return t?"tool-calls":"other"}}var $a=Xi(()=>le([d(),N(),Te(),Zs(),j($a),Se(d(),$a.optional())])),DP=$e(()=>xe(le([k({type:P("response.output_text.delta"),item_id:d(),delta:d(),logprobs:j(k({token:d(),logprob:N(),top_logprobs:j(k({token:d(),logprob:N()}))})).nullish()}),k({type:ge(["response.completed","response.incomplete"]),response:k({incomplete_details:k({reason:d()}).nullish(),usage:k({input_tokens:N(),input_tokens_details:k({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:k({reasoning_tokens:N().nullish()}).nullish()}),service_tier:d().nullish()})}),k({type:P("response.failed"),response:k({error:k({code:d().nullish(),message:d()}).nullish(),incomplete_details:k({reason:d()}).nullish(),usage:k({input_tokens:N(),input_tokens_details:k({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:k({reasoning_tokens:N().nullish()}).nullish()}).nullish(),service_tier:d().nullish()})}),k({type:P("response.created"),response:k({id:d(),created_at:N(),model:d(),service_tier:d().nullish()})}),k({type:P("response.output_item.added"),output_index:N(),item:Qe("type",[k({type:P("message"),id:d(),phase:ge(["commentary","final_answer"]).nullish()}),k({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),k({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d()}),k({type:P("web_search_call"),id:d(),status:d()}),k({type:P("computer_call"),id:d(),status:d()}),k({type:P("file_search_call"),id:d()}),k({type:P("image_generation_call"),id:d()}),k({type:P("code_interpreter_call"),id:d(),container_id:d(),code:d().nullable(),outputs:j(Qe("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullable(),status:d()}),k({type:P("mcp_call"),id:d(),status:d(),approval_request_id:d().nullish()}),k({type:P("mcp_list_tools"),id:d()}),k({type:P("mcp_approval_request"),id:d()}),k({type:P("apply_patch_call"),id:d(),call_id:d(),status:ge(["in_progress","completed"]),operation:Qe("type",[k({type:P("create_file"),path:d(),diff:d()}),k({type:P("delete_file"),path:d()}),k({type:P("update_file"),path:d(),diff:d()})])}),k({type:P("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d()}),k({type:P("shell_call"),id:d(),call_id:d(),status:ge(["in_progress","completed","incomplete"]),action:k({commands:j(d())})}),k({type:P("shell_call_output"),id:d(),call_id:d(),status:ge(["in_progress","completed","incomplete"]),output:j(k({stdout:d(),stderr:d(),outcome:Qe("type",[k({type:P("timeout")}),k({type:P("exit"),exit_code:N()})])}))}),k({type:P("tool_search_call"),id:d(),execution:ge(["server","client"]),call_id:d().nullable(),status:ge(["in_progress","completed","incomplete"]),arguments:Ne()}),k({type:P("tool_search_output"),id:d(),execution:ge(["server","client"]),call_id:d().nullable(),status:ge(["in_progress","completed","incomplete"]),tools:j(Se(d(),$a.optional()))})])}),k({type:P("response.output_item.done"),output_index:N(),item:Qe("type",[k({type:P("message"),id:d(),phase:ge(["commentary","final_answer"]).nullish()}),k({type:P("reasoning"),id:d(),encrypted_content:d().nullish()}),k({type:P("function_call"),id:d(),call_id:d(),name:d(),arguments:d(),status:P("completed")}),k({type:P("custom_tool_call"),id:d(),call_id:d(),name:d(),input:d(),status:P("completed")}),k({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:j(Qe("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullable()}),k({type:P("image_generation_call"),id:d(),result:d()}),k({type:P("web_search_call"),id:d(),status:d(),action:Qe("type",[k({type:P("search"),query:d().nullish(),sources:j(Qe("type",[k({type:P("url"),url:d()}),k({type:P("api"),name:d()})])).nullish()}),k({type:P("open_page"),url:d().nullish()}),k({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),k({type:P("file_search_call"),id:d(),queries:j(d()),results:j(k({attributes:Se(d(),le([d(),N(),Te()])),file_id:d(),filename:d(),score:N(),text:d()})).nullish()}),k({type:P("local_shell_call"),id:d(),call_id:d(),action:k({type:P("exec"),command:j(d()),timeout_ms:N().optional(),user:d().optional(),working_directory:d().optional(),env:Se(d(),d()).optional()})}),k({type:P("computer_call"),id:d(),status:P("completed")}),k({type:P("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:le([d(),k({type:d().optional(),code:le([N(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),k({type:P("mcp_list_tools"),id:d(),server_label:d(),tools:j(k({name:d(),description:d().optional(),input_schema:xt(),annotations:Se(d(),Ne()).optional()})),error:le([d(),k({type:d().optional(),code:le([N(),d()]).optional(),message:d().optional()}).loose()]).optional()}),k({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),k({type:P("apply_patch_call"),id:d(),call_id:d(),status:ge(["in_progress","completed"]),operation:Qe("type",[k({type:P("create_file"),path:d(),diff:d()}),k({type:P("delete_file"),path:d()}),k({type:P("update_file"),path:d(),diff:d()})])}),k({type:P("shell_call"),id:d(),call_id:d(),status:ge(["in_progress","completed","incomplete"]),action:k({commands:j(d())})}),k({type:P("shell_call_output"),id:d(),call_id:d(),status:ge(["in_progress","completed","incomplete"]),output:j(k({stdout:d(),stderr:d(),outcome:Qe("type",[k({type:P("timeout")}),k({type:P("exit"),exit_code:N()})])}))}),k({type:P("tool_search_call"),id:d(),execution:ge(["server","client"]),call_id:d().nullable(),status:ge(["in_progress","completed","incomplete"]),arguments:Ne()}),k({type:P("tool_search_output"),id:d(),execution:ge(["server","client"]),call_id:d().nullable(),status:ge(["in_progress","completed","incomplete"]),tools:j(Se(d(),$a.optional()))})])}),k({type:P("response.function_call_arguments.delta"),item_id:d(),output_index:N(),delta:d()}),k({type:P("response.custom_tool_call_input.delta"),item_id:d(),output_index:N(),delta:d()}),k({type:P("response.image_generation_call.partial_image"),item_id:d(),output_index:N(),partial_image_b64:d()}),k({type:P("response.code_interpreter_call_code.delta"),item_id:d(),output_index:N(),delta:d()}),k({type:P("response.code_interpreter_call_code.done"),item_id:d(),output_index:N(),code:d()}),k({type:P("response.output_text.annotation.added"),annotation:Qe("type",[k({type:P("url_citation"),start_index:N(),end_index:N(),url:d(),title:d()}),k({type:P("file_citation"),file_id:d(),filename:d(),index:N()}),k({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:N(),end_index:N()}),k({type:P("file_path"),file_id:d(),index:N()})])}),k({type:P("response.reasoning_summary_part.added"),item_id:d(),summary_index:N()}),k({type:P("response.reasoning_summary_text.delta"),item_id:d(),summary_index:N(),delta:d()}),k({type:P("response.reasoning_summary_part.done"),item_id:d(),summary_index:N()}),k({type:P("response.apply_patch_call_operation_diff.delta"),item_id:d(),output_index:N(),delta:d(),obfuscation:d().nullish()}),k({type:P("response.apply_patch_call_operation_diff.done"),item_id:d(),output_index:N(),diff:d()}),k({type:P("error"),sequence_number:N(),error:k({type:d(),code:d(),message:d(),param:d().nullish()})}),k({type:d()}).loose().transform(e=>({type:"unknown_chunk",message:e.type}))]))),UP=$e(()=>xe(k({id:d().optional(),created_at:N().optional(),error:k({message:d(),type:d(),param:d().nullish(),code:d()}).nullish(),model:d().optional(),output:j(Qe("type",[k({type:P("message"),role:P("assistant"),id:d(),phase:ge(["commentary","final_answer"]).nullish(),content:j(k({type:P("output_text"),text:d(),logprobs:j(k({token:d(),logprob:N(),top_logprobs:j(k({token:d(),logprob:N()}))})).nullish(),annotations:j(Qe("type",[k({type:P("url_citation"),start_index:N(),end_index:N(),url:d(),title:d()}),k({type:P("file_citation"),file_id:d(),filename:d(),index:N()}),k({type:P("container_file_citation"),container_id:d(),file_id:d(),filename:d(),start_index:N(),end_index:N()}),k({type:P("file_path"),file_id:d(),index:N()})]))}))}),k({type:P("web_search_call"),id:d(),status:d(),action:Qe("type",[k({type:P("search"),query:d().nullish(),sources:j(Qe("type",[k({type:P("url"),url:d()}),k({type:P("api"),name:d()})])).nullish()}),k({type:P("open_page"),url:d().nullish()}),k({type:P("find_in_page"),url:d().nullish(),pattern:d().nullish()})]).nullish()}),k({type:P("file_search_call"),id:d(),queries:j(d()),results:j(k({attributes:Se(d(),le([d(),N(),Te()])),file_id:d(),filename:d(),score:N(),text:d()})).nullish()}),k({type:P("code_interpreter_call"),id:d(),code:d().nullable(),container_id:d(),outputs:j(Qe("type",[k({type:P("logs"),logs:d()}),k({type:P("image"),url:d()})])).nullable()}),k({type:P("image_generation_call"),id:d(),result:d()}),k({type:P("local_shell_call"),id:d(),call_id:d(),action:k({type:P("exec"),command:j(d()),timeout_ms:N().optional(),user:d().optional(),working_directory:d().optional(),env:Se(d(),d()).optional()})}),k({type:P("function_call"),call_id:d(),name:d(),arguments:d(),id:d()}),k({type:P("custom_tool_call"),call_id:d(),name:d(),input:d(),id:d()}),k({type:P("computer_call"),id:d(),status:d().optional()}),k({type:P("reasoning"),id:d(),encrypted_content:d().nullish(),summary:j(k({type:P("summary_text"),text:d()}))}),k({type:P("mcp_call"),id:d(),status:d(),arguments:d(),name:d(),server_label:d(),output:d().nullish(),error:le([d(),k({type:d().optional(),code:le([N(),d()]).optional(),message:d().optional()}).loose()]).nullish(),approval_request_id:d().nullish()}),k({type:P("mcp_list_tools"),id:d(),server_label:d(),tools:j(k({name:d(),description:d().optional(),input_schema:xt(),annotations:Se(d(),Ne()).optional()})),error:le([d(),k({type:d().optional(),code:le([N(),d()]).optional(),message:d().optional()}).loose()]).optional()}),k({type:P("mcp_approval_request"),id:d(),server_label:d(),name:d(),arguments:d(),approval_request_id:d().optional()}),k({type:P("apply_patch_call"),id:d(),call_id:d(),status:ge(["in_progress","completed"]),operation:Qe("type",[k({type:P("create_file"),path:d(),diff:d()}),k({type:P("delete_file"),path:d()}),k({type:P("update_file"),path:d(),diff:d()})])}),k({type:P("shell_call"),id:d(),call_id:d(),status:ge(["in_progress","completed","incomplete"]),action:k({commands:j(d())})}),k({type:P("shell_call_output"),id:d(),call_id:d(),status:ge(["in_progress","completed","incomplete"]),output:j(k({stdout:d(),stderr:d(),outcome:Qe("type",[k({type:P("timeout")}),k({type:P("exit"),exit_code:N()})])}))}),k({type:P("tool_search_call"),id:d(),execution:ge(["server","client"]),call_id:d().nullable(),status:ge(["in_progress","completed","incomplete"]),arguments:Ne()}),k({type:P("tool_search_output"),id:d(),execution:ge(["server","client"]),call_id:d().nullable(),status:ge(["in_progress","completed","incomplete"]),tools:j(Se(d(),$a.optional()))})])).optional(),service_tier:d().nullish(),incomplete_details:k({reason:d()}).nullish(),usage:k({input_tokens:N(),input_tokens_details:k({cached_tokens:N().nullish()}).nullish(),output_tokens:N(),output_tokens_details:k({reasoning_tokens:N().nullish()}).nullish()}).optional()}))),$1=20,E1=$e(()=>xe(k({conversation:d().nullish(),include:j(ge(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:d().nullish(),logprobs:le([Te(),N().min(1).max($1)]).optional(),maxToolCalls:N().nullish(),metadata:xt().nullish(),parallelToolCalls:Te().nullish(),previousResponseId:d().nullish(),promptCacheKey:d().nullish(),promptCacheRetention:ge(["in_memory","24h"]).nullish(),reasoningEffort:d().nullish(),reasoningSummary:d().nullish(),safetyIdentifier:d().nullish(),serviceTier:ge(["auto","flex","priority","default"]).nullish(),store:Te().nullish(),strictJsonSchema:Te().nullish(),textVerbosity:ge(["low","medium","high"]).nullish(),truncation:ge(["auto","disabled"]).nullish(),user:d().nullish(),systemMessageMode:ge(["system","developer","remove"]).optional(),forceReasoning:Te().optional()})));async function zP({tools:e,toolChoice:t,toolNameMapping:r,customProviderToolNames:n}){var o,s;e=e?.length?e:void 0;const a=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};const i=[],l=n??new Set;for(const u of e)switch(u.type){case"function":{const f=(o=u.providerOptions)==null?void 0:o.openai,p=f?.deferLoading;i.push({type:"function",name:u.name,description:u.description,parameters:u.inputSchema,...u.strict!=null?{strict:u.strict}:{},...p!=null?{defer_loading:p}:{}});break}case"provider":{switch(u.id){case"openai.file_search":{const f=await Ct({value:u.args,schema:iP});i.push({type:"file_search",vector_store_ids:f.vectorStoreIds,max_num_results:f.maxNumResults,ranking_options:f.ranking?{ranker:f.ranking.ranker,score_threshold:f.ranking.scoreThreshold}:void 0,filters:f.filters});break}case"openai.local_shell":{i.push({type:"local_shell"});break}case"openai.shell":{const f=await Ct({value:u.args,schema:yP});i.push({type:"shell",...f.environment&&{environment:ZP(f.environment)}});break}case"openai.apply_patch":{i.push({type:"apply_patch"});break}case"openai.web_search_preview":{const f=await Ct({value:u.args,schema:IP});i.push({type:"web_search_preview",search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.web_search":{const f=await Ct({value:u.args,schema:kP});i.push({type:"web_search",filters:f.filters!=null?{allowed_domains:f.filters.allowedDomains}:void 0,external_web_access:f.externalWebAccess,search_context_size:f.searchContextSize,user_location:f.userLocation});break}case"openai.code_interpreter":{const f=await Ct({value:u.args,schema:eP});i.push({type:"code_interpreter",container:f.container==null?{type:"auto",file_ids:void 0}:typeof f.container=="string"?f.container:{type:"auto",file_ids:f.container.fileIds}});break}case"openai.image_generation":{const f=await Ct({value:u.args,schema:uP});i.push({type:"image_generation",background:f.background,input_fidelity:f.inputFidelity,input_image_mask:f.inputImageMask?{file_id:f.inputImageMask.fileId,image_url:f.inputImageMask.imageUrl}:void 0,model:f.model,moderation:f.moderation,partial_images:f.partialImages,quality:f.quality,output_compression:f.outputCompression,output_format:f.outputFormat,size:f.size});break}case"openai.mcp":{const f=await Ct({value:u.args,schema:PP}),p=_=>({tool_names:_.toolNames}),h=f.requireApproval,m=h==null?void 0:typeof h=="string"?h:h.never!=null?{never:p(h.never)}:void 0;i.push({type:"mcp",server_label:f.serverLabel,allowed_tools:Array.isArray(f.allowedTools)?f.allowedTools:f.allowedTools?{read_only:f.allowedTools.readOnly,tool_names:f.allowedTools.toolNames}:void 0,authorization:f.authorization,connector_id:f.connectorId,headers:f.headers,require_approval:m??"never",server_description:f.serverDescription,server_url:f.serverUrl});break}case"openai.custom":{const f=await Ct({value:u.args,schema:nP});i.push({type:"custom",name:f.name,description:f.description,format:f.format}),l.add(f.name);break}case"openai.tool_search":{const f=await Ct({value:u.args,schema:_P});i.push({type:"tool_search",...f.execution!=null?{execution:f.execution}:{},...f.description!=null?{description:f.description}:{},...f.parameters!=null?{parameters:f.parameters}:{}});break}}break}default:a.push({type:"unsupported",feature:`function tool ${u}`});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:a};const c=t.type;switch(c){case"auto":case"none":case"required":return{tools:i,toolChoice:c,toolWarnings:a};case"tool":{const u=(s=r?.toProviderToolName(t.toolName))!=null?s:t.toolName;return{tools:i,toolChoice:u==="code_interpreter"||u==="file_search"||u==="image_generation"||u==="web_search_preview"||u==="web_search"||u==="mcp"||u==="apply_patch"?{type:u}:l.has(u)?{type:"custom",name:u}:{type:"function",name:u},toolWarnings:a}}default:{const u=c;throw new Qr({functionality:`tool choice type: ${u}`})}}}function ZP(e){if(e.type==="containerReference")return{type:"container_reference",container_id:e.containerId};if(e.type==="containerAuto"){const r=e;return{type:"container_auto",file_ids:r.fileIds,memory_limit:r.memoryLimit,network_policy:r.networkPolicy==null?void 0:r.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:r.networkPolicy.allowedDomains,domain_secrets:r.networkPolicy.domainSecrets},skills:FP(r.skills)}}return{type:"local",skills:e.skills}}function FP(e){return e?.map(t=>t.type==="skillReference"?{type:"skill_reference",skill_id:t.skillId,version:t.version}:{type:"inline",name:t.name,description:t.description,source:{type:"base64",media_type:t.source.mediaType,data:t.source.data}})}function R1(e){var t,r;const n={};for(const o of e)if(o.role==="assistant")for(const s of o.content){if(s.type!=="tool-call")continue;const a=(r=(t=s.providerOptions)==null?void 0:t.openai)==null?void 0:r.approvalRequestId;a!=null&&(n[a]=s.toolCallId)}return n}var VP=class{constructor(e,t){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:r,topP:n,topK:o,presencePenalty:s,frequencyPenalty:a,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:f,responseFormat:p}){var h,m,_,g,w,v,y,S,b;const T=[],x=u1(this.modelId);o!=null&&T.push({type:"unsupported",feature:"topK"}),i!=null&&T.push({type:"unsupported",feature:"seed"}),s!=null&&T.push({type:"unsupported",feature:"presencePenalty"}),a!=null&&T.push({type:"unsupported",feature:"frequencyPenalty"}),r!=null&&T.push({type:"unsupported",feature:"stopSequences"});const R=this.config.provider.includes("azure")?"azure":"openai";let C=await _n({provider:R,providerOptions:c,schema:E1});C==null&&R!=="openai"&&(C=await _n({provider:"openai",providerOptions:c,schema:E1}));const L=(h=C?.forceReasoning)!=null?h:x.isReasoningModel;C?.conversation&&C?.previousResponseId&&T.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const O=P6({tools:u,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search"},resolveProviderToolName:ne=>ne.id==="openai.custom"?ne.args.name:void 0}),q=new Set,{tools:z,toolChoice:H,toolWarnings:ee}=await zP({tools:u,toolChoice:f,toolNameMapping:O,customProviderToolNames:q}),{input:re,warnings:X}=await jP({prompt:l,toolNameMapping:O,systemMessageMode:(m=C?.systemMessageMode)!=null?m:L?"developer":x.systemMessageMode,providerOptionsName:R,fileIdPrefixes:this.config.fileIdPrefixes,store:(_=C?.store)!=null?_:!0,hasConversation:C?.conversation!=null,hasLocalShellTool:E("openai.local_shell"),hasShellTool:E("openai.shell"),hasApplyPatchTool:E("openai.apply_patch"),customProviderToolNames:q.size>0?q:void 0});T.push(...X);const V=(g=C?.strictJsonSchema)!=null?g:!0;let ie=C?.include;function D(ne){ie==null?ie=[ne]:ie.includes(ne)||(ie=[...ie,ne])}function E(ne){return u?.find(be=>be.type==="provider"&&be.id===ne)!=null}const U=typeof C?.logprobs=="number"?C?.logprobs:C?.logprobs===!0?$1:void 0;U&&D("message.output_text.logprobs");const Z=(w=u?.find(ne=>ne.type==="provider"&&(ne.id==="openai.web_search"||ne.id==="openai.web_search_preview")))==null?void 0:w.name;Z&&D("web_search_call.action.sources"),E("openai.code_interpreter")&&D("code_interpreter_call.outputs");const I=C?.store;I===!1&&L&&D("reasoning.encrypted_content");const M={model:this.modelId,input:re,temperature:t,top_p:n,max_output_tokens:e,...(p?.type==="json"||C?.textVerbosity)&&{text:{...p?.type==="json"&&{format:p.schema!=null?{type:"json_schema",strict:V,name:(v=p.name)!=null?v:"response",description:p.description,schema:p.schema}:{type:"json_object"}},...C?.textVerbosity&&{verbosity:C.textVerbosity}}},conversation:C?.conversation,max_tool_calls:C?.maxToolCalls,metadata:C?.metadata,parallel_tool_calls:C?.parallelToolCalls,previous_response_id:C?.previousResponseId,store:I,user:C?.user,instructions:C?.instructions,service_tier:C?.serviceTier,include:ie,prompt_cache_key:C?.promptCacheKey,prompt_cache_retention:C?.promptCacheRetention,safety_identifier:C?.safetyIdentifier,top_logprobs:U,truncation:C?.truncation,...L&&(C?.reasoningEffort!=null||C?.reasoningSummary!=null)&&{reasoning:{...C?.reasoningEffort!=null&&{effort:C.reasoningEffort},...C?.reasoningSummary!=null&&{summary:C.reasoningSummary}}}};L?C?.reasoningEffort==="none"&&x.supportsNonReasoningParameters||(M.temperature!=null&&(M.temperature=void 0,T.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,T.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(C?.reasoningEffort!=null&&T.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),C?.reasoningSummary!=null&&T.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),C?.serviceTier==="flex"&&!x.supportsFlexProcessing&&(T.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete M.service_tier),C?.serviceTier==="priority"&&!x.supportsPriorityProcessing&&(T.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete M.service_tier);const B=(b=(S=(y=u?.find(ne=>ne.type==="provider"&&ne.id==="openai.shell"))==null?void 0:y.args)==null?void 0:S.environment)==null?void 0:b.type,oe=B==="containerAuto"||B==="containerReference";return{webSearchToolName:Z,args:{...M,tools:z,tool_choice:H},warnings:[...T,...ee],store:I,toolNameMapping:O,providerOptionsName:R,isShellProviderExecuted:oe}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,f,p,h,m,_,g,w,v,y,S,b,T,x,R,C,L,O,q;const{args:z,warnings:H,webSearchToolName:ee,toolNameMapping:re,providerOptionsName:X,isShellProviderExecuted:V}=await this.getArgs(e),ie=this.config.url({path:"/responses",modelId:this.modelId}),D=R1(e.prompt),{responseHeaders:E,value:U,rawValue:Z}=await ar({url:ie,headers:Vt(this.config.headers(),e.headers),body:z,failedResponseHandler:Hr,successfulResponseHandler:ir(UP),abortSignal:e.abortSignal,fetch:this.config.fetch});if(U.error)throw new _t({message:U.error.message,url:ie,requestBodyValues:z,statusCode:400,responseHeaders:E,responseBody:Z,isRetryable:!1});const I=[],M=[];let B=!1;const oe=[];for(const W of U.output)switch(W.type){case"reasoning":{W.summary.length===0&&W.summary.push({type:"summary_text",text:""});for(const A of W.summary)I.push({type:"reasoning",text:A.text,providerMetadata:{[X]:{itemId:W.id,reasoningEncryptedContent:(t=W.encrypted_content)!=null?t:null}}});break}case"image_generation_call":{I.push({type:"tool-call",toolCallId:W.id,toolName:re.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:W.id,toolName:re.toCustomToolName("image_generation"),result:{result:W.result}});break}case"tool_search_call":{const A=(r=W.call_id)!=null?r:W.id,F=W.execution==="server";F&&oe.push(A),I.push({type:"tool-call",toolCallId:A,toolName:re.toCustomToolName("tool_search"),input:JSON.stringify({arguments:W.arguments,call_id:W.call_id}),...F?{providerExecuted:!0}:{},providerMetadata:{[X]:{itemId:W.id}}});break}case"tool_search_output":{const A=(o=(n=W.call_id)!=null?n:oe.shift())!=null?o:W.id;I.push({type:"tool-result",toolCallId:A,toolName:re.toCustomToolName("tool_search"),result:{tools:W.tools},providerMetadata:{[X]:{itemId:W.id}}});break}case"local_shell_call":{I.push({type:"tool-call",toolCallId:W.call_id,toolName:re.toCustomToolName("local_shell"),input:JSON.stringify({action:W.action}),providerMetadata:{[X]:{itemId:W.id}}});break}case"shell_call":{I.push({type:"tool-call",toolCallId:W.call_id,toolName:re.toCustomToolName("shell"),input:JSON.stringify({action:{commands:W.action.commands}}),...V&&{providerExecuted:!0},providerMetadata:{[X]:{itemId:W.id}}});break}case"shell_call_output":{I.push({type:"tool-result",toolCallId:W.call_id,toolName:re.toCustomToolName("shell"),result:{output:W.output.map(A=>({stdout:A.stdout,stderr:A.stderr,outcome:A.outcome.type==="exit"?{type:"exit",exitCode:A.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const A of W.content){(a=(s=e.providerOptions)==null?void 0:s[X])!=null&&a.logprobs&&A.logprobs&&M.push(A.logprobs);const F={itemId:W.id,...W.phase!=null&&{phase:W.phase},...A.annotations.length>0&&{annotations:A.annotations}};I.push({type:"text",text:A.text,providerMetadata:{[X]:F}});for(const J of A.annotations)J.type==="url_citation"?I.push({type:"source",sourceType:"url",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:Yt(),url:J.url,title:J.title}):J.type==="file_citation"?I.push({type:"source",sourceType:"document",id:(p=(f=(u=this.config).generateId)==null?void 0:f.call(u))!=null?p:Yt(),mediaType:"text/plain",title:J.filename,filename:J.filename,providerMetadata:{[X]:{type:J.type,fileId:J.file_id,index:J.index}}}):J.type==="container_file_citation"?I.push({type:"source",sourceType:"document",id:(_=(m=(h=this.config).generateId)==null?void 0:m.call(h))!=null?_:Yt(),mediaType:"text/plain",title:J.filename,filename:J.filename,providerMetadata:{[X]:{type:J.type,fileId:J.file_id,containerId:J.container_id}}}):J.type==="file_path"&&I.push({type:"source",sourceType:"document",id:(v=(w=(g=this.config).generateId)==null?void 0:w.call(g))!=null?v:Yt(),mediaType:"application/octet-stream",title:J.file_id,filename:J.file_id,providerMetadata:{[X]:{type:J.type,fileId:J.file_id,index:J.index}}})}break}case"function_call":{B=!0,I.push({type:"tool-call",toolCallId:W.call_id,toolName:W.name,input:W.arguments,providerMetadata:{[X]:{itemId:W.id}}});break}case"custom_tool_call":{B=!0;const A=re.toCustomToolName(W.name);I.push({type:"tool-call",toolCallId:W.call_id,toolName:A,input:JSON.stringify(W.input),providerMetadata:{[X]:{itemId:W.id}}});break}case"web_search_call":{I.push({type:"tool-call",toolCallId:W.id,toolName:re.toCustomToolName(ee??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),I.push({type:"tool-result",toolCallId:W.id,toolName:re.toCustomToolName(ee??"web_search"),result:M1(W.action)});break}case"mcp_call":{const A=W.approval_request_id!=null&&(y=D[W.approval_request_id])!=null?y:W.id,F=`mcp.${W.name}`;I.push({type:"tool-call",toolCallId:A,toolName:F,input:W.arguments,providerExecuted:!0,dynamic:!0}),I.push({type:"tool-result",toolCallId:A,toolName:F,result:{type:"call",serverLabel:W.server_label,name:W.name,arguments:W.arguments,...W.output!=null?{output:W.output}:{},...W.error!=null?{error:W.error}:{}},providerMetadata:{[X]:{itemId:W.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const A=(S=W.approval_request_id)!=null?S:W.id,F=(x=(T=(b=this.config).generateId)==null?void 0:T.call(b))!=null?x:Yt(),J=`mcp.${W.name}`;I.push({type:"tool-call",toolCallId:F,toolName:J,input:W.arguments,providerExecuted:!0,dynamic:!0}),I.push({type:"tool-approval-request",approvalId:A,toolCallId:F});break}case"computer_call":{I.push({type:"tool-call",toolCallId:W.id,toolName:re.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:W.id,toolName:re.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:W.status||"completed"}});break}case"file_search_call":{I.push({type:"tool-call",toolCallId:W.id,toolName:re.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),I.push({type:"tool-result",toolCallId:W.id,toolName:re.toCustomToolName("file_search"),result:{queries:W.queries,results:(C=(R=W.results)==null?void 0:R.map(A=>({attributes:A.attributes,fileId:A.file_id,filename:A.filename,score:A.score,text:A.text})))!=null?C:null}});break}case"code_interpreter_call":{I.push({type:"tool-call",toolCallId:W.id,toolName:re.toCustomToolName("code_interpreter"),input:JSON.stringify({code:W.code,containerId:W.container_id}),providerExecuted:!0}),I.push({type:"tool-result",toolCallId:W.id,toolName:re.toCustomToolName("code_interpreter"),result:{outputs:W.outputs}});break}case"apply_patch_call":{I.push({type:"tool-call",toolCallId:W.call_id,toolName:re.toCustomToolName("apply_patch"),input:JSON.stringify({callId:W.call_id,operation:W.operation}),providerMetadata:{[X]:{itemId:W.id}}});break}}const ne={[X]:{responseId:U.id,...M.length>0?{logprobs:M}:{},...typeof U.service_tier=="string"?{serviceTier:U.service_tier}:{}}},be=U.usage;return{content:I,finishReason:{unified:Lp({finishReason:(L=U.incomplete_details)==null?void 0:L.reason,hasFunctionCall:B}),raw:(q=(O=U.incomplete_details)==null?void 0:O.reason)!=null?q:void 0},usage:x1(be),request:{body:z},response:{id:U.id,timestamp:new Date(U.created_at*1e3),modelId:U.model,headers:E,body:Z},providerMetadata:ne,warnings:H}}async doStream(e){const{args:t,warnings:r,webSearchToolName:n,toolNameMapping:o,store:s,providerOptionsName:a,isShellProviderExecuted:i}=await this.getArgs(e),{responseHeaders:l,value:c}=await ar({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Vt(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:Hr,successfulResponseHandler:Nl(DP),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,f=R1(e.prompt),p=new Map;let h={unified:"other",raw:void 0},m;const _=[];let g=null;const w={},v=[];let y,S=!1;const b={};let T;const x=[];return{stream:c.pipeThrough(new TransformStream({start(R){R.enqueue({type:"stream-start",warnings:r})},transform(R,C){var L,O,q,z,H,ee,re,X,V,ie,D,E,U,Z,I,M,B,oe,ne,be,W,A,F,J,Q,he,Pe,Ke,it,gt,ae,rt,_e,ue,Ie,ce,te,Ce;if(e.includeRawChunks&&C.enqueue({type:"raw",rawValue:R.rawValue}),!R.success){h={unified:"error",raw:void 0},C.enqueue({type:"error",error:R.error});return}const $=R.value;if(P1($)){if($.item.type==="function_call")w[$.output_index]={toolName:$.item.name,toolCallId:$.item.call_id},C.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:$.item.name});else if($.item.type==="custom_tool_call"){const Y=o.toCustomToolName($.item.name);w[$.output_index]={toolName:Y,toolCallId:$.item.call_id},C.enqueue({type:"tool-input-start",id:$.item.call_id,toolName:Y})}else if($.item.type==="web_search_call")w[$.output_index]={toolName:o.toCustomToolName(n??"web_search"),toolCallId:$.item.id},C.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName(n??"web_search"),providerExecuted:!0}),C.enqueue({type:"tool-input-end",id:$.item.id}),C.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if($.item.type==="computer_call")w[$.output_index]={toolName:o.toCustomToolName("computer_use"),toolCallId:$.item.id},C.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("computer_use"),providerExecuted:!0});else if($.item.type==="code_interpreter_call")w[$.output_index]={toolName:o.toCustomToolName("code_interpreter"),toolCallId:$.item.id,codeInterpreter:{containerId:$.item.container_id}},C.enqueue({type:"tool-input-start",id:$.item.id,toolName:o.toCustomToolName("code_interpreter"),providerExecuted:!0}),C.enqueue({type:"tool-input-delta",id:$.item.id,delta:`{"containerId":"${$.item.container_id}","code":"`});else if($.item.type==="file_search_call")C.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if($.item.type==="image_generation_call")C.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if($.item.type==="tool_search_call"){const Y=$.item.id,Fe=o.toCustomToolName("tool_search"),Ae=$.item.execution==="server";w[$.output_index]={toolName:Fe,toolCallId:Y,toolSearchExecution:(L=$.item.execution)!=null?L:"server"},Ae&&C.enqueue({type:"tool-input-start",id:Y,toolName:Fe,providerExecuted:!0})}else if($.item.type!=="tool_search_output"){if(!($.item.type==="mcp_call"||$.item.type==="mcp_list_tools"||$.item.type==="mcp_approval_request"))if($.item.type==="apply_patch_call"){const{call_id:Y,operation:Fe}=$.item;if(w[$.output_index]={toolName:o.toCustomToolName("apply_patch"),toolCallId:Y,applyPatch:{hasDiff:Fe.type==="delete_file",endEmitted:Fe.type==="delete_file"}},C.enqueue({type:"tool-input-start",id:Y,toolName:o.toCustomToolName("apply_patch")}),Fe.type==="delete_file"){const Ae=JSON.stringify({callId:Y,operation:Fe});C.enqueue({type:"tool-input-delta",id:Y,delta:Ae}),C.enqueue({type:"tool-input-end",id:Y})}else C.enqueue({type:"tool-input-delta",id:Y,delta:`{"callId":"${ko(Y)}","operation":{"type":"${ko(Fe.type)}","path":"${ko(Fe.path)}","diff":"`})}else $.item.type==="shell_call"?w[$.output_index]={toolName:o.toCustomToolName("shell"),toolCallId:$.item.call_id}:$.item.type==="shell_call_output"||($.item.type==="message"?(v.splice(0,v.length),y=(O=$.item.phase)!=null?O:void 0,C.enqueue({type:"text-start",id:$.item.id,providerMetadata:{[a]:{itemId:$.item.id,...$.item.phase!=null&&{phase:$.item.phase}}}})):P1($)&&$.item.type==="reasoning"&&(b[$.item.id]={encryptedContent:$.item.encrypted_content,summaryParts:{0:"active"}},C.enqueue({type:"reasoning-start",id:`${$.item.id}:0`,providerMetadata:{[a]:{itemId:$.item.id,reasoningEncryptedContent:(q=$.item.encrypted_content)!=null?q:null}}})))}}else if(BP($)){if($.item.type==="message"){const Y=(z=$.item.phase)!=null?z:y;y=void 0,C.enqueue({type:"text-end",id:$.item.id,providerMetadata:{[a]:{itemId:$.item.id,...Y!=null&&{phase:Y},...v.length>0&&{annotations:v}}}})}else if($.item.type==="function_call")w[$.output_index]=void 0,S=!0,C.enqueue({type:"tool-input-end",id:$.item.call_id}),C.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:$.item.name,input:$.item.arguments,providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="custom_tool_call"){w[$.output_index]=void 0,S=!0;const Y=o.toCustomToolName($.item.name);C.enqueue({type:"tool-input-end",id:$.item.call_id}),C.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:Y,input:JSON.stringify($.item.input),providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="web_search_call")w[$.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName(n??"web_search"),result:M1($.item.action)});else if($.item.type==="computer_call")w[$.output_index]=void 0,C.enqueue({type:"tool-input-end",id:$.item.id}),C.enqueue({type:"tool-call",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),C.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:$.item.status||"completed"}});else if($.item.type==="file_search_call")w[$.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("file_search"),result:{queries:$.item.queries,results:(ee=(H=$.item.results)==null?void 0:H.map(Y=>({attributes:Y.attributes,fileId:Y.file_id,filename:Y.filename,score:Y.score,text:Y.text})))!=null?ee:null}});else if($.item.type==="code_interpreter_call")w[$.output_index]=void 0,C.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:$.item.outputs}});else if($.item.type==="image_generation_call")C.enqueue({type:"tool-result",toolCallId:$.item.id,toolName:o.toCustomToolName("image_generation"),result:{result:$.item.result}});else if($.item.type==="tool_search_call"){const Y=w[$.output_index],Fe=$.item.execution==="server";if(Y!=null){const Ae=Fe?Y.toolCallId:(re=$.item.call_id)!=null?re:$.item.id;Fe?x.push(Ae):C.enqueue({type:"tool-input-start",id:Ae,toolName:Y.toolName}),C.enqueue({type:"tool-input-end",id:Ae}),C.enqueue({type:"tool-call",toolCallId:Ae,toolName:Y.toolName,input:JSON.stringify({arguments:$.item.arguments,call_id:Fe?null:Ae}),...Fe?{providerExecuted:!0}:{},providerMetadata:{[a]:{itemId:$.item.id}}})}w[$.output_index]=void 0}else if($.item.type==="tool_search_output"){const Y=(V=(X=$.item.call_id)!=null?X:x.shift())!=null?V:$.item.id;C.enqueue({type:"tool-result",toolCallId:Y,toolName:o.toCustomToolName("tool_search"),result:{tools:$.item.tools},providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="mcp_call"){w[$.output_index]=void 0;const Y=(ie=$.item.approval_request_id)!=null?ie:void 0,Fe=Y!=null&&(E=(D=p.get(Y))!=null?D:f[Y])!=null?E:$.item.id,Ae=`mcp.${$.item.name}`;C.enqueue({type:"tool-call",toolCallId:Fe,toolName:Ae,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),C.enqueue({type:"tool-result",toolCallId:Fe,toolName:Ae,result:{type:"call",serverLabel:$.item.server_label,name:$.item.name,arguments:$.item.arguments,...$.item.output!=null?{output:$.item.output}:{},...$.item.error!=null?{error:$.item.error}:{}},providerMetadata:{[a]:{itemId:$.item.id}}})}else if($.item.type==="mcp_list_tools")w[$.output_index]=void 0;else if($.item.type==="apply_patch_call"){const Y=w[$.output_index];Y?.applyPatch&&!Y.applyPatch.endEmitted&&$.item.operation.type!=="delete_file"&&(Y.applyPatch.hasDiff||C.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:ko($.item.operation.diff)}),C.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:'"}}'}),C.enqueue({type:"tool-input-end",id:Y.toolCallId}),Y.applyPatch.endEmitted=!0),Y&&$.item.status==="completed"&&C.enqueue({type:"tool-call",toolCallId:Y.toolCallId,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:$.item.call_id,operation:$.item.operation}),providerMetadata:{[a]:{itemId:$.item.id}}}),w[$.output_index]=void 0}else if($.item.type==="mcp_approval_request"){w[$.output_index]=void 0;const Y=(I=(Z=(U=u.config).generateId)==null?void 0:Z.call(U))!=null?I:Yt(),Fe=(M=$.item.approval_request_id)!=null?M:$.item.id;p.set(Fe,Y);const Ae=`mcp.${$.item.name}`;C.enqueue({type:"tool-call",toolCallId:Y,toolName:Ae,input:$.item.arguments,providerExecuted:!0,dynamic:!0}),C.enqueue({type:"tool-approval-request",approvalId:Fe,toolCallId:Y})}else if($.item.type==="local_shell_call")w[$.output_index]=void 0,C.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:$.item.action.command,timeoutMs:$.item.action.timeout_ms,user:$.item.action.user,workingDirectory:$.item.action.working_directory,env:$.item.action.env}}),providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="shell_call")w[$.output_index]=void 0,C.enqueue({type:"tool-call",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:$.item.action.commands}}),...i&&{providerExecuted:!0},providerMetadata:{[a]:{itemId:$.item.id}}});else if($.item.type==="shell_call_output")C.enqueue({type:"tool-result",toolCallId:$.item.call_id,toolName:o.toCustomToolName("shell"),result:{output:$.item.output.map(Y=>({stdout:Y.stdout,stderr:Y.stderr,outcome:Y.outcome.type==="exit"?{type:"exit",exitCode:Y.outcome.exit_code}:{type:"timeout"}}))}});else if($.item.type==="reasoning"){const Y=b[$.item.id],Fe=Object.entries(Y.summaryParts).filter(([Ae,ft])=>ft==="active"||ft==="can-conclude").map(([Ae])=>Ae);for(const Ae of Fe)C.enqueue({type:"reasoning-end",id:`${$.item.id}:${Ae}`,providerMetadata:{[a]:{itemId:$.item.id,reasoningEncryptedContent:(B=$.item.encrypted_content)!=null?B:null}}});delete b[$.item.id]}}else if(KP($)){const Y=w[$.output_index];Y!=null&&C.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:$.delta})}else if(YP($)){const Y=w[$.output_index];Y!=null&&C.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:$.delta})}else if(tM($)){const Y=w[$.output_index];Y?.applyPatch&&(C.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:ko($.delta)}),Y.applyPatch.hasDiff=!0)}else if(rM($)){const Y=w[$.output_index];Y?.applyPatch&&!Y.applyPatch.endEmitted&&(Y.applyPatch.hasDiff||(C.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:ko($.diff)}),Y.applyPatch.hasDiff=!0),C.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:'"}}'}),C.enqueue({type:"tool-input-end",id:Y.toolCallId}),Y.applyPatch.endEmitted=!0)}else if(QP($))C.enqueue({type:"tool-result",toolCallId:$.item_id,toolName:o.toCustomToolName("image_generation"),result:{result:$.partial_image_b64},preliminary:!0});else if(XP($)){const Y=w[$.output_index];Y!=null&&C.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:ko($.delta)})}else if(eM($)){const Y=w[$.output_index];Y!=null&&(C.enqueue({type:"tool-input-delta",id:Y.toolCallId,delta:'"}'}),C.enqueue({type:"tool-input-end",id:Y.toolCallId}),C.enqueue({type:"tool-call",toolCallId:Y.toolCallId,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:$.code,containerId:Y.codeInterpreter.containerId}),providerExecuted:!0}))}else if(GP($))g=$.response.id,C.enqueue({type:"response-metadata",id:$.response.id,timestamp:new Date($.response.created_at*1e3),modelId:$.response.model});else if(HP($))C.enqueue({type:"text-delta",id:$.item_id,delta:$.delta}),(ne=(oe=e.providerOptions)==null?void 0:oe[a])!=null&&ne.logprobs&&$.logprobs&&_.push($.logprobs);else if($.type==="response.reasoning_summary_part.added"){if($.summary_index>0){const Y=b[$.item_id];Y.summaryParts[$.summary_index]="active";for(const Fe of Object.keys(Y.summaryParts))Y.summaryParts[Fe]==="can-conclude"&&(C.enqueue({type:"reasoning-end",id:`${$.item_id}:${Fe}`,providerMetadata:{[a]:{itemId:$.item_id}}}),Y.summaryParts[Fe]="concluded");C.enqueue({type:"reasoning-start",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[a]:{itemId:$.item_id,reasoningEncryptedContent:(W=(be=b[$.item_id])==null?void 0:be.encryptedContent)!=null?W:null}}})}}else if($.type==="response.reasoning_summary_text.delta")C.enqueue({type:"reasoning-delta",id:`${$.item_id}:${$.summary_index}`,delta:$.delta,providerMetadata:{[a]:{itemId:$.item_id}}});else if($.type==="response.reasoning_summary_part.done")s?(C.enqueue({type:"reasoning-end",id:`${$.item_id}:${$.summary_index}`,providerMetadata:{[a]:{itemId:$.item_id}}}),b[$.item_id].summaryParts[$.summary_index]="concluded"):b[$.item_id].summaryParts[$.summary_index]="can-conclude";else if(JP($))h={unified:Lp({finishReason:(A=$.response.incomplete_details)==null?void 0:A.reason,hasFunctionCall:S}),raw:(J=(F=$.response.incomplete_details)==null?void 0:F.reason)!=null?J:void 0},m=$.response.usage,typeof $.response.service_tier=="string"&&(T=$.response.service_tier);else if(WP($)){const Y=(Q=$.response.incomplete_details)==null?void 0:Q.reason;h={unified:Y?Lp({finishReason:Y,hasFunctionCall:S}):"error",raw:Y??"error"},m=(he=$.response.usage)!=null?he:void 0}else nM($)?(v.push($.annotation),$.annotation.type==="url_citation"?C.enqueue({type:"source",sourceType:"url",id:(it=(Ke=(Pe=u.config).generateId)==null?void 0:Ke.call(Pe))!=null?it:Yt(),url:$.annotation.url,title:$.annotation.title}):$.annotation.type==="file_citation"?C.enqueue({type:"source",sourceType:"document",id:(rt=(ae=(gt=u.config).generateId)==null?void 0:ae.call(gt))!=null?rt:Yt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}}):$.annotation.type==="container_file_citation"?C.enqueue({type:"source",sourceType:"document",id:(Ie=(ue=(_e=u.config).generateId)==null?void 0:ue.call(_e))!=null?Ie:Yt(),mediaType:"text/plain",title:$.annotation.filename,filename:$.annotation.filename,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,containerId:$.annotation.container_id}}}):$.annotation.type==="file_path"&&C.enqueue({type:"source",sourceType:"document",id:(Ce=(te=(ce=u.config).generateId)==null?void 0:te.call(ce))!=null?Ce:Yt(),mediaType:"application/octet-stream",title:$.annotation.file_id,filename:$.annotation.file_id,providerMetadata:{[a]:{type:$.annotation.type,fileId:$.annotation.file_id,index:$.annotation.index}}})):oM($)&&C.enqueue({type:"error",error:$})},flush(R){const C={[a]:{responseId:g,..._.length>0?{logprobs:_}:{},...T!==void 0?{serviceTier:T}:{}}};R.enqueue({type:"finish",finishReason:h,usage:x1(m),providerMetadata:C})}})),request:{body:t},response:{headers:l}}}};function HP(e){return e.type==="response.output_text.delta"}function BP(e){return e.type==="response.output_item.done"}function JP(e){return e.type==="response.completed"||e.type==="response.incomplete"}function WP(e){return e.type==="response.failed"}function GP(e){return e.type==="response.created"}function KP(e){return e.type==="response.function_call_arguments.delta"}function YP(e){return e.type==="response.custom_tool_call_input.delta"}function QP(e){return e.type==="response.image_generation_call.partial_image"}function XP(e){return e.type==="response.code_interpreter_call_code.delta"}function eM(e){return e.type==="response.code_interpreter_call_code.done"}function tM(e){return e.type==="response.apply_patch_call_operation_diff.delta"}function rM(e){return e.type==="response.apply_patch_call_operation_diff.done"}function P1(e){return e.type==="response.output_item.added"}function nM(e){return e.type==="response.output_text.annotation.added"}function oM(e){return e.type==="error"}function M1(e){var t;if(e==null)return{};switch(e.type){case"search":return{action:{type:"search",query:(t=e.query)!=null?t:void 0},...e.sources!=null&&{sources:e.sources}};case"open_page":return{action:{type:"openPage",url:e.url}};case"find_in_page":return{action:{type:"findInPage",url:e.url,pattern:e.pattern}}}}function ko(e){return JSON.stringify(e).slice(1,-1)}var sM=$e(()=>xe(k({instructions:d().nullish(),speed:N().min(.25).max(4).default(1).nullish()}))),aM=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:e,voice:t="alloy",outputFormat:r="mp3",speed:n,instructions:o,language:s,providerOptions:a}){const i=[],l=await _n({provider:"openai",providerOptions:a,schema:sM}),c={model:this.modelId,input:e,voice:t,response_format:"mp3",speed:n,instructions:o};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const f in u){const p=u[f];p!==void 0&&(c[f]=p)}}return s&&i.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(e){var t,r,n;const o=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{requestBody:s,warnings:a}=await this.getArgs(e),{value:i,responseHeaders:l,rawValue:c}=await ar({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Vt(this.config.headers(),e.headers),body:s,failedResponseHandler:Hr,successfulResponseHandler:Z5(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:a,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:c}}}},iM=$e(()=>xe(k({text:d(),language:d().nullish(),duration:N().nullish(),words:j(k({word:d(),start:N(),end:N()})).nullish(),segments:j(k({id:N(),seek:N(),start:N(),end:N(),text:d(),tokens:j(N()),temperature:N(),avg_logprob:N(),compression_ratio:N(),no_speech_prob:N()})).nullish()}))),lM=$e(()=>xe(k({include:j(d()).optional(),language:d().optional(),prompt:d().optional(),temperature:N().min(0).max(1).default(0).optional(),timestampGranularities:j(ge(["word","segment"])).default(["segment"]).optional()}))),O1={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"},cM=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:r}){const n=[],o=await _n({provider:"openai",providerOptions:r,schema:lM}),s=new FormData,a=e instanceof Uint8Array?new Blob([e]):new Blob([rs(e)]);s.append("model",this.modelId);const i=H6(t);if(s.append("file",new File([a],"audio",{type:t}),`audio.${i}`),o){const l={include:o.include,language:o.language,prompt:o.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:o.temperature,timestamp_granularities:o.timestampGranularities};for(const[c,u]of Object.entries(l))if(u!=null)if(Array.isArray(u))for(const f of u)s.append(`${c}[]`,String(f));else s.append(c,String(u))}return{formData:s,warnings:n}}async doGenerate(e){var t,r,n,o,s,a,i,l;const c=(n=(r=(t=this.config._internal)==null?void 0:t.currentDate)==null?void 0:r.call(t))!=null?n:new Date,{formData:u,warnings:f}=await this.getArgs(e),{value:p,responseHeaders:h,rawValue:m}=await hy({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Vt(this.config.headers(),e.headers),formData:u,failedResponseHandler:Hr,successfulResponseHandler:ir(iM),abortSignal:e.abortSignal,fetch:this.config.fetch}),_=p.language!=null&&p.language in O1?O1[p.language]:void 0;return{text:p.text,segments:(i=(a=(o=p.segments)==null?void 0:o.map(g=>({text:g.text,startSecond:g.start,endSecond:g.end})))!=null?a:(s=p.words)==null?void 0:s.map(g=>({text:g.word,startSecond:g.start,endSecond:g.end})))!=null?i:[],language:_,durationInSeconds:(l=p.duration)!=null?l:void 0,warnings:f,response:{timestamp:c,modelId:this.modelId,headers:h,body:m}}}},uM="3.0.50";function N1(e={}){var t,r;const n=(t=gy(ss({settingValue:e.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?t:"https://api.openai.com/v1",o=(r=e.name)!=null?r:"openai",s=()=>Dn({Authorization:`Bearer ${V6({apiKey:e.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${uM}`),a=_=>new j7(_,{provider:`${o}.chat`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),i=_=>new z7(_,{provider:`${o}.completion`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),l=_=>new V7(_,{provider:`${o}.embedding`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),c=_=>new W7(_,{provider:`${o}.image`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),u=_=>new cM(_,{provider:`${o}.transcription`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),f=_=>new aM(_,{provider:`${o}.speech`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch}),p=_=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return h(_)},h=_=>new VP(_,{provider:`${o}.responses`,url:({path:g})=>`${n}${g}`,headers:s,fetch:e.fetch,fileIdPrefixes:["file-"]}),m=function(_){return p(_)};return m.specificationVersion="v3",m.languageModel=p,m.chat=a,m.completion=i,m.responses=h,m.embedding=l,m.embeddingModel=l,m.textEmbedding=l,m.textEmbeddingModel=l,m.image=c,m.imageModel=c,m.transcription=u,m.transcriptionModel=u,m.speech=f,m.speechModel=f,m.tools=qP,m}N1();var A1="vercel.ai.error",dM=Symbol.for(A1),q1,pM=class ab extends Error{constructor({name:t,message:r,cause:n}){super(r),this[q1]=!0,this.name=t,this.cause=n}static isInstance(t){return ab.hasMarker(t,A1)}static hasMarker(t,r){const n=Symbol.for(r);return t!=null&&typeof t=="object"&&n in t&&typeof t[n]=="boolean"&&t[n]===!0}};q1=dM;var Nt=pM,j1="AI_APICallError",L1=`vercel.ai.error.${j1}`,fM=Symbol.for(L1),D1,kn=class extends Nt{constructor({message:e,url:t,requestBodyValues:r,statusCode:n,responseHeaders:o,responseBody:s,cause:a,isRetryable:i=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:j1,message:e,cause:a}),this[D1]=!0,this.url=t,this.requestBodyValues=r,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(e){return Nt.hasMarker(e,L1)}};D1=fM;var U1="AI_EmptyResponseBodyError",z1=`vercel.ai.error.${U1}`,hM=Symbol.for(z1),Z1,mM=class extends Nt{constructor({message:e="Empty response body"}={}){super({name:U1,message:e}),this[Z1]=!0}static isInstance(e){return Nt.hasMarker(e,z1)}};Z1=hM;function F1(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var V1="AI_InvalidArgumentError",H1=`vercel.ai.error.${V1}`,gM=Symbol.for(H1),B1,J1=class extends Nt{constructor({message:e,cause:t,argument:r}){super({name:V1,message:e,cause:t}),this[B1]=!0,this.argument=r}static isInstance(e){return Nt.hasMarker(e,H1)}};B1=gM;var W1="AI_InvalidResponseDataError",G1=`vercel.ai.error.${W1}`,yM=Symbol.for(G1),K1,Y1=class extends Nt{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:W1,message:t}),this[K1]=!0,this.data=e}static isInstance(e){return Nt.hasMarker(e,G1)}};K1=yM;var Q1="AI_JSONParseError",X1=`vercel.ai.error.${Q1}`,vM=Symbol.for(X1),ew,Ql=class extends Nt{constructor({text:e,cause:t}){super({name:Q1,message:`JSON parsing failed: Text: ${e}.
595
+ Error message: ${F1(t)}`,cause:t}),this[ew]=!0,this.text=e}static isInstance(e){return Nt.hasMarker(e,X1)}};ew=vM;var tw="AI_LoadAPIKeyError",rw=`vercel.ai.error.${tw}`,_M=Symbol.for(rw),nw,Xl=class extends Nt{constructor({message:e}){super({name:tw,message:e}),this[nw]=!0}static isInstance(e){return Nt.hasMarker(e,rw)}};nw=_M;var ow="AI_NoSuchModelError",sw=`vercel.ai.error.${ow}`,wM=Symbol.for(sw),aw,iw=class extends Nt{constructor({errorName:e=ow,modelId:t,modelType:r,message:n=`No such ${r}: ${t}`}){super({name:e,message:n}),this[aw]=!0,this.modelId=t,this.modelType=r}static isInstance(e){return Nt.hasMarker(e,sw)}};aw=wM;var lw="AI_TypeValidationError",cw=`vercel.ai.error.${lw}`,bM=Symbol.for(cw),uw,kM=class sf extends Nt{constructor({value:t,cause:r}){super({name:lw,message:`Type validation failed: Value: ${JSON.stringify(t)}.
596
+ Error message: ${F1(r)}`,cause:r}),this[uw]=!0,this.value=t}static isInstance(t){return Nt.hasMarker(t,cw)}static wrap({value:t,cause:r}){return sf.isInstance(r)&&r.value===t?r:new sf({value:t,cause:r})}};uw=bM;var Ea=kM,dw="AI_UnsupportedFunctionalityError",pw=`vercel.ai.error.${dw}`,TM=Symbol.for(pw),fw,hw=class extends Nt{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:dw,message:t}),this[fw]=!0,this.functionality=e}static isInstance(e){return Nt.hasMarker(e,pw)}};fw=TM;function mw(...e){return e.reduce((t,r)=>({...t,...r??{}}),{})}function ec(e){return Object.fromEntries([...e.headers])}var SM=({prefix:e,size:t=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{const o=()=>{const s=r.length,a=new Array(t);for(let i=0;i<t;i++)a[i]=r[Math.random()*s|0];return a.join("")};if(e==null)return o;if(r.includes(n))throw new J1({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${r}".`});return()=>`${e}${n}${o()}`},tc=SM();function Dp(e){return(e instanceof Error||e instanceof DOMException)&&(e.name==="AbortError"||e.name==="ResponseAborted"||e.name==="TimeoutError")}var CM=["fetch failed","failed to fetch"];function xM({error:e,url:t,requestBodyValues:r}){if(Dp(e))return e;if(e instanceof TypeError&&CM.includes(e.message.toLowerCase())){const n=e.cause;if(n!=null)return new kn({message:`Cannot connect to API: ${n.message}`,cause:n,url:t,requestBodyValues:r,isRetryable:!0})}return e}function IM(e=globalThis){var t,r,n;return e.window?"runtime/browser":(t=e.navigator)!=null&&t.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:(n=(r=e.process)==null?void 0:r.versions)!=null&&n.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function $M(e){if(e==null)return{};const t={};if(e instanceof Headers)e.forEach((r,n)=>{t[n.toLowerCase()]=r});else{Array.isArray(e)||(e=Object.entries(e));for(const[r,n]of e)n!=null&&(t[r.toLowerCase()]=n)}return t}function gw(e,...t){const r=new Headers($M(e)),n=r.get("user-agent")||"";return r.set("user-agent",[n,...t].filter(Boolean).join(" ")),Object.fromEntries(r.entries())}var EM="3.0.18";function RM({apiKey:e,environmentVariableName:t,apiKeyParameterName:r="apiKey",description:n}){if(typeof e=="string")return e;if(e!=null)throw new Xl({message:`${n} API key must be a string.`});if(typeof process>"u")throw new Xl({message:`${n} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new Xl({message:`${n} API key is missing. Pass it using the '${r}' parameter or the ${t} environment variable.`});if(typeof e!="string")throw new Xl({message:`${n} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}var PM=/"__proto__"\s*:/,MM=/"constructor"\s*:/;function yw(e){const t=JSON.parse(e);return t===null||typeof t!="object"||PM.test(e)===!1&&MM.test(e)===!1?t:OM(t)}function OM(e){let t=[e];for(;t.length;){const r=t;t=[];for(const n of r){if(Object.prototype.hasOwnProperty.call(n,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(n,"constructor")&&Object.prototype.hasOwnProperty.call(n.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const o in n){const s=n[o];s&&typeof s=="object"&&t.push(s)}}}return e}function Up(e){const{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return yw(e)}try{return yw(e)}finally{Error.stackTraceLimit=t}}var zp=Symbol.for("vercel.ai.validator");function NM(e){return{[zp]:!0,validate:e}}function AM(e){return typeof e=="object"&&e!==null&&zp in e&&e[zp]===!0&&"validate"in e}function qM(e){return AM(e)?e:typeof e=="function"?e():jM(e)}function jM(e){return NM(async t=>{const r=await e["~standard"].validate(t);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Ea({value:t,cause:r.issues})}})}async function LM({value:e,schema:t}){const r=await Ra({value:e,schema:t});if(!r.success)throw Ea.wrap({value:e,cause:r.error});return r.value}async function Ra({value:e,schema:t}){const r=qM(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};const n=await r.validate(e);return n.success?{success:!0,value:n.value,rawValue:e}:{success:!1,error:Ea.wrap({value:e,cause:n.error}),rawValue:e}}catch(n){return{success:!1,error:Ea.wrap({value:e,cause:n}),rawValue:e}}}async function DM({text:e,schema:t}){try{const r=Up(e);return t==null?r:LM({value:r,schema:t})}catch(r){throw Ql.isInstance(r)||Ea.isInstance(r)?r:new Ql({text:e,cause:r})}}async function vw({text:e,schema:t}){try{const r=Up(e);return t==null?{success:!0,value:r,rawValue:r}:await Ra({value:r,schema:t})}catch(r){return{success:!1,error:Ql.isInstance(r)?r:new Ql({text:e,cause:r}),rawValue:void 0}}}function _w(e){try{return Up(e),!0}catch{return!1}}function UM({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Yo).pipeThrough(new TransformStream({async transform({data:r},n){r!=="[DONE]"&&n.enqueue(await vw({text:r,schema:t}))}}))}async function ww({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;const n=await Ra({value:t[e],schema:r});if(!n.success)throw new J1({argument:"providerOptions",message:`invalid ${e} provider options`,cause:n.error});return n.value}var zM=()=>globalThis.fetch,bw=async({url:e,headers:t,body:r,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a})=>ZM({url:e,headers:{"Content-Type":"application/json",...t},body:{content:JSON.stringify(r),values:r},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:a}),ZM=async({url:e,headers:t={},body:r,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:a=zM()})=>{try{const i=await a(e,{method:"POST",headers:gw(t,`ai-sdk/provider-utils/${EM}`,IM()),body:r.content,signal:s}),l=ec(i);if(!i.ok){let c;try{c=await o({response:i,url:e,requestBodyValues:r.values})}catch(u){throw Dp(u)||kn.isInstance(u)?u:new kn({message:"Failed to process error response",cause:u,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await n({response:i,url:e,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Dp(c)||kn.isInstance(c))?c:new kn({message:"Failed to process successful response",cause:c,statusCode:i.status,url:e,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw xM({error:i,url:e,requestBodyValues:r.values})}},FM=({errorSchema:e,errorToMessage:t,isRetryable:r})=>async({response:n,url:o,requestBodyValues:s})=>{const a=await n.text(),i=ec(n);if(a.trim()==="")return{responseHeaders:i,value:new kn({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})};try{const l=await DM({text:a,schema:e});return{responseHeaders:i,value:new kn({message:t(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,data:l,isRetryable:r?.(n,l)})}}catch{return{responseHeaders:i,value:new kn({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:i,responseBody:a,isRetryable:r?.(n)})}}},VM=e=>async({response:t})=>{const r=ec(t);if(t.body==null)throw new mM({});return{responseHeaders:r,value:UM({stream:t.body,schema:e})}},HM=e=>async({response:t,url:r,requestBodyValues:n})=>{const o=await t.text(),s=await vw({text:o,schema:e}),a=ec(t);if(!s.success)throw new kn({message:"Invalid JSON response",cause:s.error,statusCode:t.status,responseHeaders:a,responseBody:o,url:r,requestBodyValues:n});return{responseHeaders:a,value:s.value,rawValue:s.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:BM}=globalThis;function JM(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCodePoint(e[r]);return BM(t)}function WM(e){return e instanceof Uint8Array?JM(e):e}function GM(e){return e?.replace(/\/$/,"")}function Pa(e){var t,r;return(r=(t=e?.providerOptions)==null?void 0:t.openaiCompatible)!=null?r:{}}function KM(e){const t=[];for(const{role:r,content:n,...o}of e){const s=Pa({...o});switch(r){case"system":{t.push({role:"system",content:n,...s});break}case"user":{if(n.length===1&&n[0].type==="text"){t.push({role:"user",content:n[0].text,...Pa(n[0])});break}t.push({role:"user",content:n.map(a=>{const i=Pa(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,${WM(a.data)}`},...i}}else throw new hw({functionality:`file part media type ${a.mediaType}`})}}),...s});break}case"assistant":{let a="";const i=[];for(const l of n){const c=Pa(l);switch(l.type){case"text":{a+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}t.push({role:"assistant",content:a,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const a of n){const i=a.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}const c=Pa(a);t.push({role:"tool",tool_call_id:a.toolCallId,content:l,...c})}break}default:{const a=r;throw new Error(`Unsupported role: ${a}`)}}}return t}function kw({id:e,model:t,created:r}){return{id:e??void 0,modelId:t??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function Tw(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var Zp=k({user:d().optional(),reasoningEffort:d().optional(),textVerbosity:d().optional()}),YM=k({error:k({message:d(),type:d().nullish(),param:xt().nullish(),code:le([d(),N()]).nullish()})}),QM={errorSchema:YM,errorToMessage:e=>e.error.message};function XM({tools:e,toolChoice:t}){e=e?.length?e:void 0;const r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const n=[];for(const s of e)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):n.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(t==null)return{tools:n,toolChoice:void 0,toolWarnings:r};const o=t.type;switch(o){case"auto":case"none":case"required":return{tools:n,toolChoice:o,toolWarnings:r};case"tool":return{tools:n,toolChoice:{type:"function",function:{name:t.toolName}},toolWarnings:r};default:{const s=o;throw new hw({functionality:`tool choice type: ${s}`})}}}var eO=class{constructor(e,t){this.specificationVersion="v2";var r,n;this.modelId=e,this.config=t;const o=(r=t.errorStructure)!=null?r:QM;this.chunkSchema=rO(o.errorSchema),this.failedResponseHandler=FM(o),this.supportsStructuredOutputs=(n=t.supportsStructuredOutputs)!=null?n:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var e,t,r;return(r=(t=(e=this.config).supportedUrls)==null?void 0:t.call(e))!=null?r:{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:r,topP:n,topK:o,frequencyPenalty:s,presencePenalty:a,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:f,tools:p}){var h,m,_,g;const w=[],v=Object.assign((h=await ww({provider:"openai-compatible",providerOptions:i,schema:Zp}))!=null?h:{},(m=await ww({provider:this.providerOptionsName,providerOptions:i,schema:Zp}))!=null?m:{});o!=null&&w.push({type:"unsupported-setting",setting:"topK"}),c?.type==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&w.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:y,toolChoice:S,toolWarnings:b}=XM({tools:p,toolChoice:f});return{args:{model:this.modelId,user:v.user,max_tokens:t,temperature:r,top_p:n,frequency_penalty:s,presence_penalty:a,response_format:c?.type==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(_=c.name)!=null?_:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((g=i?.[this.providerOptionsName])!=null?g:{}).filter(([T])=>!Object.keys(Zp.shape).includes(T))),reasoning_effort:v.reasoningEffort,verbosity:v.textVerbosity,messages:KM(e),tools:y,tool_choice:S},warnings:[...w,...b]}}async doGenerate(e){var t,r,n,o,s,a,i,l,c,u,f,p,h,m,_,g,w;const{args:v,warnings:y}=await this.getArgs({...e}),S=JSON.stringify(v),{responseHeaders:b,value:T,rawValue:x}=await bw({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mw(this.config.headers(),e.headers),body:v,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:HM(tO),abortSignal:e.abortSignal,fetch:this.config.fetch}),R=T.choices[0],C=[],L=R.message.content;L!=null&&L.length>0&&C.push({type:"text",text:L});const O=(t=R.message.reasoning_content)!=null?t:R.message.reasoning;if(O!=null&&O.length>0&&C.push({type:"reasoning",text:O}),R.message.tool_calls!=null)for(const H of R.message.tool_calls)C.push({type:"tool-call",toolCallId:(r=H.id)!=null?r:tc(),toolName:H.function.name,input:H.function.arguments});const q={[this.providerOptionsName]:{},...await((o=(n=this.config.metadataExtractor)==null?void 0:n.extractMetadata)==null?void 0:o.call(n,{parsedBody:x}))},z=(s=T.usage)==null?void 0:s.completion_tokens_details;return z?.accepted_prediction_tokens!=null&&(q[this.providerOptionsName].acceptedPredictionTokens=z?.accepted_prediction_tokens),z?.rejected_prediction_tokens!=null&&(q[this.providerOptionsName].rejectedPredictionTokens=z?.rejected_prediction_tokens),{content:C,finishReason:Tw(R.finish_reason),usage:{inputTokens:(i=(a=T.usage)==null?void 0:a.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=T.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(f=(u=T.usage)==null?void 0:u.total_tokens)!=null?f:void 0,reasoningTokens:(m=(h=(p=T.usage)==null?void 0:p.completion_tokens_details)==null?void 0:h.reasoning_tokens)!=null?m:void 0,cachedInputTokens:(w=(g=(_=T.usage)==null?void 0:_.prompt_tokens_details)==null?void 0:g.cached_tokens)!=null?w:void 0},providerMetadata:q,request:{body:S},response:{...kw(T),headers:b,body:x},warnings:y}}async doStream(e){var t;const{args:r,warnings:n}=await this.getArgs({...e}),o={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(t=this.config.metadataExtractor)==null?void 0:t.createStreamExtractor(),{responseHeaders:a,value:i}=await bw({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mw(this.config.headers(),e.headers),body:o,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:VM(this.chunkSchema),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let f=!0;const p=this.providerOptionsName;let h=!1,m=!1;return{stream:i.pipeThrough(new TransformStream({start(_){_.enqueue({type:"stream-start",warnings:n})},transform(_,g){var w,v,y,S,b,T,x,R,C,L,O,q,z;if(e.includeRawChunks&&g.enqueue({type:"raw",rawValue:_.rawValue}),!_.success){c="error",g.enqueue({type:"error",error:_.error});return}const H=_.value;if(s?.processChunk(_.rawValue),"error"in H){c="error",g.enqueue({type:"error",error:H.error.message});return}if(f&&(f=!1,g.enqueue({type:"response-metadata",...kw(H)})),H.usage!=null){const{prompt_tokens:V,completion_tokens:ie,total_tokens:D,prompt_tokens_details:E,completion_tokens_details:U}=H.usage;u.promptTokens=V??void 0,u.completionTokens=ie??void 0,u.totalTokens=D??void 0,U?.reasoning_tokens!=null&&(u.completionTokensDetails.reasoningTokens=U?.reasoning_tokens),U?.accepted_prediction_tokens!=null&&(u.completionTokensDetails.acceptedPredictionTokens=U?.accepted_prediction_tokens),U?.rejected_prediction_tokens!=null&&(u.completionTokensDetails.rejectedPredictionTokens=U?.rejected_prediction_tokens),E?.cached_tokens!=null&&(u.promptTokensDetails.cachedTokens=E?.cached_tokens)}const ee=H.choices[0];if(ee?.finish_reason!=null&&(c=Tw(ee.finish_reason)),ee?.delta==null)return;const re=ee.delta,X=(w=re.reasoning_content)!=null?w:re.reasoning;if(X&&(h||(g.enqueue({type:"reasoning-start",id:"reasoning-0"}),h=!0),g.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:X})),re.content&&(m||(g.enqueue({type:"text-start",id:"txt-0"}),m=!0),g.enqueue({type:"text-delta",id:"txt-0",delta:re.content})),re.tool_calls!=null)for(const V of re.tool_calls){const ie=V.index;if(l[ie]==null){if(V.id==null)throw new Y1({data:V,message:"Expected 'id' to be a string."});if(((v=V.function)==null?void 0:v.name)==null)throw new Y1({data:V,message:"Expected 'function.name' to be a string."});g.enqueue({type:"tool-input-start",id:V.id,toolName:V.function.name}),l[ie]={id:V.id,type:"function",function:{name:V.function.name,arguments:(y=V.function.arguments)!=null?y:""},hasFinished:!1};const E=l[ie];((S=E.function)==null?void 0:S.name)!=null&&((b=E.function)==null?void 0:b.arguments)!=null&&(E.function.arguments.length>0&&g.enqueue({type:"tool-input-delta",id:E.id,delta:E.function.arguments}),_w(E.function.arguments)&&(g.enqueue({type:"tool-input-end",id:E.id}),g.enqueue({type:"tool-call",toolCallId:(T=E.id)!=null?T:tc(),toolName:E.function.name,input:E.function.arguments}),E.hasFinished=!0));continue}const D=l[ie];D.hasFinished||(((x=V.function)==null?void 0:x.arguments)!=null&&(D.function.arguments+=(C=(R=V.function)==null?void 0:R.arguments)!=null?C:""),g.enqueue({type:"tool-input-delta",id:D.id,delta:(L=V.function.arguments)!=null?L:""}),((O=D.function)==null?void 0:O.name)!=null&&((q=D.function)==null?void 0:q.arguments)!=null&&_w(D.function.arguments)&&(g.enqueue({type:"tool-input-end",id:D.id}),g.enqueue({type:"tool-call",toolCallId:(z=D.id)!=null?z:tc(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0))}},flush(_){var g,w,v,y,S,b;h&&_.enqueue({type:"reasoning-end",id:"reasoning-0"}),m&&_.enqueue({type:"text-end",id:"txt-0"});for(const x of l.filter(R=>!R.hasFinished))_.enqueue({type:"tool-input-end",id:x.id}),_.enqueue({type:"tool-call",toolCallId:(g=x.id)!=null?g:tc(),toolName:x.function.name,input:x.function.arguments});const T={[p]:{},...s?.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(T[p].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(T[p].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),_.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(w=u.promptTokens)!=null?w:void 0,outputTokens:(v=u.completionTokens)!=null?v:void 0,totalTokens:(y=u.totalTokens)!=null?y:void 0,reasoningTokens:(S=u.completionTokensDetails.reasoningTokens)!=null?S:void 0,cachedInputTokens:(b=u.promptTokensDetails.cachedTokens)!=null?b:void 0},providerMetadata:T})}})),request:{body:o},response:{headers:a}}}},Sw=k({prompt_tokens:N().nullish(),completion_tokens:N().nullish(),total_tokens:N().nullish(),prompt_tokens_details:k({cached_tokens:N().nullish()}).nullish(),completion_tokens_details:k({reasoning_tokens:N().nullish(),accepted_prediction_tokens:N().nullish(),rejected_prediction_tokens:N().nullish()}).nullish()}).nullish(),tO=k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:j(k({message:k({role:P("assistant").nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:j(k({id:d().nullish(),function:k({name:d(),arguments:d()})})).nullish()}),finish_reason:d().nullish()})),usage:Sw}),rO=e=>le([k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:j(k({delta:k({role:ge(["assistant"]).nullish(),content:d().nullish(),reasoning_content:d().nullish(),reasoning:d().nullish(),tool_calls:j(k({index:N(),id:d().nullish(),function:k({name:d().nullish(),arguments:d().nullish()})})).nullish()}).nullish(),finish_reason:d().nullish()})),usage:Sw}),e]);k({echo:Te().optional(),logitBias:Se(d(),N()).optional(),suffix:d().optional(),user:d().optional()});var nO=k({prompt_tokens:N(),completion_tokens:N(),total_tokens:N()});k({id:d().nullish(),created:N().nullish(),model:d().nullish(),choices:j(k({text:d(),finish_reason:d()})),usage:nO.nullish()}),k({dimensions:N().optional(),user:d().optional()}),k({data:j(k({embedding:j(N())})),usage:k({prompt_tokens:N()}).nullish(),providerMetadata:Se(d(),Se(d(),xt())).optional()}),k({data:j(k({b64_json:d()}))});var Cw=e=>{var t,r;return e==null?void 0:{deepseek:{promptCacheHitTokens:(t=e.prompt_cache_hit_tokens)!=null?t:NaN,promptCacheMissTokens:(r=e.prompt_cache_miss_tokens)!=null?r:NaN}}},oO={extractMetadata:async({parsedBody:e})=>{const t=await Ra({value:e,schema:sO});return!t.success||t.value.usage==null?void 0:Cw(t.value.usage)},createStreamExtractor:()=>{let e;return{processChunk:async t=>{var r,n;const o=await Ra({value:t,schema:aO});o.success&&((n=(r=o.value.choices)==null?void 0:r[0])==null?void 0:n.finish_reason)==="stop"&&o.value.usage&&(e=o.value.usage)},buildMetadata:()=>Cw(e)}}},xw=k({prompt_cache_hit_tokens:N().nullish(),prompt_cache_miss_tokens:N().nullish()}),sO=k({usage:xw.nullish()}),aO=k({choices:j(k({finish_reason:d().nullish()})).nullish(),usage:xw.nullish()}),iO="1.0.30";function Iw(e={}){var t;const r=GM((t=e.baseURL)!=null?t:"https://api.deepseek.com/v1"),n=()=>gw({Authorization:`Bearer ${RM({apiKey:e.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...e.headers},`ai-sdk/deepseek/${iO}`);class o extends eO{addJsonInstruction(l){var c;if(((c=l.responseFormat)==null?void 0:c.type)!=="json")return l;const p=[...Array.isArray(l.prompt)?l.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...l,prompt:p}}async doGenerate(l){return super.doGenerate(this.addJsonInstruction(l))}async doStream(l){return super.doStream(this.addJsonInstruction(l))}}const s=i=>new o(i,{provider:"deepseek.chat",url:({path:l})=>`${r}${l}`,headers:n,fetch:e.fetch,metadataExtractor:oO}),a=i=>s(i);return a.languageModel=s,a.chat=s,a.textEmbeddingModel=i=>{throw new iw({modelId:i,modelType:"textEmbeddingModel"})},a.imageModel=i=>{throw new iw({modelId:i,modelType:"imageModel"})},a}Iw();const $w=async e=>{const t={};try{const r=await e.listTools();for(const{name:n,description:o,inputSchema:s}of r.tools){const a=async(i,l)=>e.callTool({name:n,arguments:i},{signal:l?.abortSignal});t[n]=Qd({description:o,inputSchema:go({...s,properties:s.properties??{},additionalProperties:!1}),execute:a})}return t}catch(r){throw r}},lO=async e=>{const t={};if(!e)return t;const r=e,n=r.listTools??r.getTools;if(!n)return t;const o=await n.call(r),s=Array.isArray(o)?o:[];for(const a of s){const{name:i,description:l}=a,c=a.inputSchema;let u={};if(typeof c=="string")try{u=JSON.parse(c)}catch(p){console.error("Failed to parse inputSchema in getBuiltinMcpTools:",p)}else typeof c=="object"&&c!==null&&(u=c);const f={type:"object",properties:u.properties??{},...u.required?{required:u.required}:{},additionalProperties:!1,...u};t[i]=Qd({description:l??"",inputSchema:go(f),async execute(p){if(!r.executeTool)throw new Error("navigator.modelContextTesting.executeTool is not available");return r.executeTool(i,JSON.stringify(p??{}))}})}return t};function cO(e){const t=Object.entries(e);if(t.length===0)return"";let r=`
597
597
  # 工具调用
598
598
 
599
599
  你可以根据需要调用以下工具:
@@ -629,14 +629,14 @@ Thought: 用户想要获取今天的日期,我需要调用日期相关的工
629
629
  - 必须严格按照 XML 格式调用工具
630
630
  - arguments 必须是有效的 JSON 格式
631
631
  - 如果不需要调用工具,直接给出最终答案即可
632
- `,r}function xw(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),s=o.name||o.action||o.tool,a=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:a}}catch{}return null}const XM={openai:M1,deepseek:Cw};class eN{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=XM[n]:o=n,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=t.useReActMode??!1}async _createOneClient(t){try{let r;if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Xs(new URL(o.url),{requestInit:s})}else if("type"in t&&t.type==="sse"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Zo(new URL(o.url),{requestInit:s})}else"type"in t&&t.type==="extension"?r=new h2(t.sessionId):"transport"in t?r=t.transport:r=t;if(t.useAISdkClient??!1){const o=await wR({transport:r});return o.__transport__=r,o}else{const o=new d2({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof oa||r&&r instanceof ea)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const s=await this._createOneClient(o);return{serverName:n,client:s}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await Iw(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const s=await this._getClientTools(o,n);return{serverName:n,tools:s}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[n]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async refreshTools(){await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(s=>s!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={},r=!0){const n=Object.values(this.mcpTools).reduce((o,s)=>({...o,...s}),{});return Object.assign(n,t),r&&this.ignoreToolnames.forEach(o=>{delete n[o]}),n}_getActiveToolNames(t){return Object.keys(t).filter(r=>!this.ignoreToolnames.includes(r))}_generateReActSystemPrompt(t,r,n){const o=QM(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
633
- ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,a=s.execute||s.call;return typeof a!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let i=[];o.message&&!o.messages?i.push({role:"user",content:o.message}):o.messages?i=[...o.messages]:i=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},f=i[0]?.role==="system"?i:[u,...i];return t===bp?this._chatReActStream(f,s,l,n,o):this._chatReActNonStream(f,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const a=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(s<n)a.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&a.unshift(u)}else a.unshift(l)}return o.push(...a),o}async _chatReActNonStream(t,r,n,o,s){let a=[...t];const i=t[0]?.role==="system"?t[0]:null,l=i?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(i,l,u),{tools:h,...m}=s,y=(await P_({model:this.llm(n),messages:p,...m})).text,w={role:"assistant",content:y};l.push(w),a.push(w);const v=xw(y,r);if(!v)return this.responseMessages=a,{text:y,response:{messages:a}};const g=await this._executeReActToolCall(v.toolName,v.arguments,r),k={role:"user",content:`<tool_response>
634
- ${g.success?JSON.stringify(g.result):`工具执行失败 - ${g.error}`}
635
- </tool_response>`};l.push(k),a.push(k)}return this.responseMessages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(t,r,n,o,s){const a=this,i=this.llm(n);let l,c;const u=new Promise((p,h)=>{l=p,c=h});return{fullStream:new ReadableStream({async start(p){let h=[...t];const m=t[0]?.role==="system"?t[0]:null,_=m?t.slice(1):[...t];let y=0,w="";const v=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;y<o;){y++;const g=a._buildMessagesForModel(m,_,v),{tools:S,...b}=s;delete b.system,delete b.onFinish;const k=await bp({...b,model:i,messages:g});let C="";for await(const te of k.fullStream)te.type==="text-delta"?(C+=te.text||"",p.enqueue({type:"text-delta",text:te.text})):te.type==="text-start"?p.enqueue({type:"text-start"}):te.type==="text-end"||te.type==="finish-step"||te.type==="finish"||te.type==="start"||te.type==="start-step"||p.enqueue(te);w+=C;const R={role:"assistant",content:w};_.push(R),h.push(R);const I=xw(w,r);if(!I){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h});return}if(I.toolName==="computer"&&I.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h});return}const j=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:j,toolName:I.toolName});const N=JSON.stringify(I.arguments,null,2);p.enqueue({type:"tool-input-delta",id:j,delta:N}),p.enqueue({type:"tool-input-end",id:j}),p.enqueue({type:"tool-call",toolCallId:j,toolName:I.toolName,input:I.arguments});const L=await a._executeReActToolCall(I.toolName,I.arguments,r);let z,H=L.result;if(L.success&&L.result&&typeof L.result=="object"&&L.result.screenshot){z=L.result.screenshot;const{screenshot:te,...X}=L.result;H=X}let ee="";if(L.success){H&&Array.isArray(H.content)&&H.content.length>0&&H.content[0].text?ee=H.content[0].text:ee=JSON.stringify(H);let te=`<tool_response>
632
+ `,r}function Ew(e,t){if(!e||typeof e!="string")return null;const r=e.match(/<tool_call>([\s\S]*?)<\/tool_call>/i);if(r)try{const n=r[1].trim(),o=JSON.parse(n),s=o.name||o.action||o.tool,a=o.arguments||o.args||o.input||{};if(s&&t[s])return{toolName:s,arguments:a}}catch{}return null}const uO={openai:N1,deepseek:Iw};class dO{constructor({llmConfig:t,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.responseMessages=[],this.useReActMode=!1,!t)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},t.llm)this.llm=t.llm;else if(t.providerType){const n=t.providerType;let o;typeof n=="string"?o=uO[n]:o=n,this.llm=o({apiKey:t.apiKey,baseURL:t.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided");this.useReActMode=t.useReActMode??!1}async _createOneClient(t){try{let r;if("type"in t&&t.type==="builtin"){const o=t.client;return{tools:()=>lO(o),close:async()=>{}}}if("type"in t&&t.type.toLocaleLowerCase()==="streamablehttp"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new oa(new URL(o.url),{requestInit:s})}else if("type"in t&&t.type==="sse"){const o=t,s=o.headers?{headers:o.headers}:void 0;r=new Ko(new URL(o.url),{requestInit:s})}else"type"in t&&t.type==="extension"?r=new y2(t.sessionId):"transport"in t?r=t.transport:r=t;if(t.useAISdkClient??!1){const o=await R7({transport:r});return o.__transport__=r,o}else{const o=new h2({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await o.connect(r),o.__transport__=r,o}}catch(r){return this.onError&&this.onError(r?.message||"Failed to create MCP client",r),console.error("Failed to create MCP client",t,r),null}}async _closeOneClient(t){try{const r=t.__transport__;if(r&&r instanceof ca||r&&r instanceof sa)return;await r?.terminateSession?.(),await r?.close?.(),await t?.close?.()}catch{}}async _createMpcClients(){const t=Object.entries(this.mcpServers),r=await Promise.all(t.map(async([n,o])=>{const s=await this._createOneClient(o);return{serverName:n,client:s}}));this.mcpClients={},r.forEach(({serverName:n,client:o})=>{this.mcpClients[n]=o})}async _getClientTools(t,r){if(!t)return null;try{return typeof t.tools=="function"?await t.tools():await $w(t)}catch(n){return this.onError&&this.onError(n?.message||`Failed to query tools for ${r}`,n),console.error(`Failed to query tools for ${r}`,n),null}}async _createMpcTools(){const t=Object.entries(this.mcpClients),r=await Promise.all(t.map(async([n,o])=>{const s=await this._getClientTools(o,n);return{serverName:n,tools:s}}));this.mcpTools={},r.forEach(({serverName:n,tools:o})=>{const s=o&&typeof o=="object"?o:{};this.mcpTools[n]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async t=>{try{await this._closeOneClient(t)}catch(r){this.onError&&this.onError(r?.message||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){await this._createMpcClients(),await this._createMpcTools(),this.onUpdatedTools?.()}async refreshTools(){await this._createMpcTools(),this.onUpdatedTools?.()}async updateMcpServers(t){await this.closeAll(),this.mcpServers=t||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(t,r){if(this.mcpServers[t])return!1;const n=await this._createOneClient(r);if(!n)return this.onError?.(`Failed to create MCP client: ${t}`),null;this.mcpClients[t]=n;const o=await this._getClientTools(n,t);return this.mcpTools[t]=o&&typeof o=="object"?o:{},this.mcpServers[t]=r,this.onUpdatedTools?.(),n}async removeMcpServer(t){if(!this.mcpServers[t])return;delete this.mcpServers[t];const r=this.mcpClients[t];delete this.mcpClients[t];try{await this._closeOneClient(r)}catch{}const n=this.mcpTools[t];delete this.mcpTools[t],n&&Object.keys(n).forEach(o=>{this.ignoreToolnames=this.ignoreToolnames.filter(s=>s!==o)}),this.onUpdatedTools?.()}_tempMergeTools(t={},r=!0){const n=Object.values(this.mcpTools).reduce((o,s)=>({...o,...s}),{});return Object.assign(n,t),r&&this.ignoreToolnames.forEach(o=>{delete n[o]}),n}_getActiveToolNames(t){return Object.keys(t).filter(r=>!this.ignoreToolnames.includes(r))}_generateReActSystemPrompt(t,r,n){const o=cO(t);return n?`${n}${o}`:`你是一个智能助手,可以通过调用工具来完成任务。
633
+ ${o}`}async _executeReActToolCall(t,r,n){const o=n[t];if(!o)return{success:!1,error:`工具 ${t} 不存在`};try{const s=o,a=s.execute||s.call;return typeof a!="function"?{success:!1,error:`工具 ${t} 没有可执行的函数`}:{success:!0,result:await a(r,{})}}catch(s){return{success:!1,error:s?.message||String(s)||"工具执行失败"}}}async _chatReAct(t,{model:r,maxSteps:n=5,...o}){if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=this._tempMergeTools(o.tools);if(Object.keys(s).length===0)return this._chat(t,{model:r,maxSteps:n,...o});let i=[];o.message&&!o.messages?i.push({role:"user",content:o.message}):o.messages?i=[...o.messages]:i=[...this.responseMessages];const l=typeof r=="string"?r:r?.modelId||"default-model",u={role:"system",content:this._generateReActSystemPrompt(s,l,o.system)},f=i[0]?.role==="system"?i:[u,...i];return t===xp?this._chatReActStream(f,s,l,n,o):this._chatReActNonStream(f,s,l,n,o)}_messageHasImage(t){return t&&Array.isArray(t)?t.some(r=>r&&r.type==="image"):!1}_removeImageFromMessage(t){if(!t||!t.content)return null;if(!Array.isArray(t.content))return t;const r=t.content.filter(n=>n&&n.type!=="image");return r.length===0?null:{...t,content:r}}_buildMessagesForModel(t,r,n=3){const o=[];t&&o.push(t);let s=0;const a=[];for(let i=r.length-1;i>=0;i--){const l=r[i];if(this._messageHasImage(l.content))if(s<n)a.unshift(l),s++;else{const u=this._removeImageFromMessage(l);u&&a.unshift(u)}else a.unshift(l)}return o.push(...a),o}async _chatReActNonStream(t,r,n,o,s){let a=[...t];const i=t[0]?.role==="system"?t[0]:null,l=i?t.slice(1):t;let c=0;const u=s.maxImages??3;for(;c<o;){c++;const p=this._buildMessagesForModel(i,l,u),{tools:h,...m}=s,g=(await O_({model:this.llm(n),messages:p,...m})).text,w={role:"assistant",content:g};l.push(w),a.push(w);const v=Ew(g,r);if(!v)return this.responseMessages=a,{text:g,response:{messages:a}};const y=await this._executeReActToolCall(v.toolName,v.arguments,r),T={role:"user",content:`<tool_response>
634
+ ${y.success?JSON.stringify(y.result):`工具执行失败 - ${y.error}`}
635
+ </tool_response>`};l.push(T),a.push(T)}return this.responseMessages=a,{text:a[a.length-2]?.content||"",response:{messages:a}}}_chatReActStream(t,r,n,o,s){const a=this,i=this.llm(n);let l,c;const u=new Promise((p,h)=>{l=p,c=h});return{fullStream:new ReadableStream({async start(p){let h=[...t];const m=t[0]?.role==="system"?t[0]:null,_=m?t.slice(1):[...t];let g=0,w="";const v=s.maxImages??3;p.enqueue({type:"start"}),p.enqueue({type:"start-step"});try{for(;g<o;){g++;const y=a._buildMessagesForModel(m,_,v),{tools:S,...b}=s;delete b.system,delete b.onFinish;const T=await xp({...b,model:i,messages:y});let x="";for await(const re of T.fullStream)re.type==="text-delta"?(x+=re.text||"",p.enqueue({type:"text-delta",text:re.text})):re.type==="text-start"?p.enqueue({type:"text-start"}):re.type==="text-end"||re.type==="finish-step"||re.type==="finish"||re.type==="start"||re.type==="start-step"||p.enqueue(re);w+=x;const R={role:"assistant",content:w};_.push(R),h.push(R);const C=Ew(w,r);if(!C){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h});return}if(C.toolName==="computer"&&C.arguments?.action==="terminate"){p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h});return}const L=`react-${Date.now()}`;p.enqueue({type:"tool-input-start",id:L,toolName:C.toolName});const O=JSON.stringify(C.arguments,null,2);p.enqueue({type:"tool-input-delta",id:L,delta:O}),p.enqueue({type:"tool-input-end",id:L}),p.enqueue({type:"tool-call",toolCallId:L,toolName:C.toolName,input:C.arguments});const q=await a._executeReActToolCall(C.toolName,C.arguments,r);let z,H=q.result;if(q.success&&q.result&&typeof q.result=="object"&&q.result.screenshot){z=q.result.screenshot;const{screenshot:re,...X}=q.result;H=X}let ee="";if(q.success){H&&Array.isArray(H.content)&&H.content.length>0&&H.content[0].text?ee=H.content[0].text:ee=JSON.stringify(H);let re=`<tool_response>
636
636
  ${ee}
637
- </tool_response>`;z&&(te+=`
638
- 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:j,result:te});const X=z?{role:"user",content:[{type:"text",text:te},{type:"image",image:z}]}:{role:"user",content:te};_.push(X),h.push(X),w=""}else ee=`工具执行失败 - ${L.error}`,p.enqueue({type:"tool-error",toolCallId:j,input:I.arguments,error:{message:ee}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h})}catch(g){p.error(g),c(g)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=o.tools||{},a=this._tempMergeTools(s,!1),i=()=>{const h=this._tempMergeTools(s,!1);Object.entries(h).forEach(([m,_])=>{a[m]=_}),Object.keys(a).forEach(m=>{m in h||delete a[m]})},l=o.prepareStep,c=async h=>{i();const m=this._getActiveToolNames(a),_=typeof l=="function"?await l(h):void 0,y=_&&typeof _=="object"?_:{};return{...y,activeTools:Array.isArray(y.activeTools)?y.activeTools.filter(w=>m.includes(w)):m}},u={model:this.llm(r),stopWhen:vp(n),...o,tools:a,prepareStep:c,activeTools:this._getActiveToolNames(a)};let f=null;if(o.message&&!o.messages)f={role:"user",content:o.message},this.responseMessages.push(f),u.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const h=o.messages[o.messages.length-1];h.role==="user"&&(f=h)}const p=t(u);return p?.response?.then(h=>{const m=h.messages?.[0];f&&m?.role!=="user"&&this.responseMessages.push(f),this.responseMessages.push(...h.messages)}),p}async chat(t){return this._chat(P_,t)}async chatStream(t){return this._chat(bp,t)}}let wn=null,Yl=null,Ew=null,Ql=0;const tN="next-sdk-tool-body-glow";function xa(){return typeof window<"u"&&typeof document<"u"}function rN(){if(!xa()||Ew)return;const e=document.createElement("style");e.textContent=`
639
- .${tN} {
637
+ </tool_response>`;z&&(re+=`
638
+ 请检查截图以确认操作是否成功。如果成功,请继续下一步;如果失败,请重试。`),p.enqueue({type:"tool-result",toolCallId:L,result:re});const X=z?{role:"user",content:[{type:"text",text:re},{type:"image",image:z}]}:{role:"user",content:re};_.push(X),h.push(X),w=""}else ee=`工具执行失败 - ${q.error}`,p.enqueue({type:"tool-error",toolCallId:L,input:C.arguments,error:{message:ee}})}p.enqueue({type:"text-end"}),p.enqueue({type:"finish-step"}),p.enqueue({type:"finish"}),p.close(),a.responseMessages=h,l({messages:h})}catch(y){p.error(y),c(y)}}}),response:u}}async _chat(t,{model:r,maxSteps:n=5,...o}){if(this.useReActMode)return this._chatReAct(t,{model:r,maxSteps:n,...o});if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s=o.tools||{},a=this._tempMergeTools(s,!1),i=()=>{const h=this._tempMergeTools(s,!1);Object.entries(h).forEach(([m,_])=>{a[m]=_}),Object.keys(a).forEach(m=>{m in h||delete a[m]})},l=o.prepareStep,c=async h=>{i();const m=this._getActiveToolNames(a),_=typeof l=="function"?await l(h):void 0,g=_&&typeof _=="object"?_:{};return{...g,activeTools:Array.isArray(g.activeTools)?g.activeTools.filter(w=>m.includes(w)):m}},u={model:this.llm(r),stopWhen:Tp(n),...o,tools:a,prepareStep:c,activeTools:this._getActiveToolNames(a)};let f=null;if(o.message&&!o.messages)f={role:"user",content:o.message},this.responseMessages.push(f),u.messages=[...this.responseMessages];else if(o.messages&&o.messages.length>0){const h=o.messages[o.messages.length-1];h.role==="user"&&(f=h)}const p=t(u);return p?.response?.then(h=>{const m=h.messages?.[0];f&&m?.role!=="user"&&this.responseMessages.push(f),this.responseMessages.push(...h.messages)}),p}async chat(t){return this._chat(O_,t)}async chatStream(t){return this._chat(xp,t)}}const zn=()=>typeof window<"u"&&typeof navigator<"u",pO=()=>zn()&&typeof document<"u";let Tn=null,rc=null,Rw=null,nc=0;const fO="next-sdk-tool-body-glow";function Ma(){return pO()}function hO(){if(!Ma()||Rw)return;const e=document.createElement("style");e.textContent=`
639
+ .${fO} {
640
640
  position: relative;
641
641
  }
642
642
 
@@ -803,9 +803,12 @@ ${ee}
803
803
  transform: scale(1) translateY(0);
804
804
  }
805
805
  }
806
- `,document.head.appendChild(e),Ew=e}function nN(){if(!xa()||wn)return;rN();const e=document.createElement("div");e.className="next-sdk-tool-overlay";const t=document.createElement("div");t.className="next-sdk-tool-overlay__glow-ring";const r=document.createElement("div");r.className="next-sdk-tool-overlay__panel";const n=document.createElement("div");n.className="next-sdk-tool-overlay__indicator";const o=document.createElement("div");o.className="next-sdk-tool-overlay__indicator-orbit";const s=document.createElement("div");s.className="next-sdk-tool-overlay__indicator-core";const a=document.createElement("div");a.className="next-sdk-tool-overlay__content";const i=document.createElement("div");i.className="next-sdk-tool-overlay__title",i.textContent="AI 正在调用页面工具";const l=document.createElement("span");l.className="next-sdk-tool-overlay__title-dot";const c=document.createElement("div");c.className="next-sdk-tool-overlay__label",i.prepend(l),a.appendChild(i),a.appendChild(c),n.appendChild(o),n.appendChild(s),r.appendChild(n),r.appendChild(a),e.appendChild(t),e.appendChild(r),document.body.appendChild(e),wn=e,Yl=c}function oN(e){xa()&&(nN(),!(!wn||!Yl)&&(wn.classList.remove("next-sdk-tool-overlay--exit"),Yl.textContent=e.label))}function sN(){if(!wn)return;wn.classList.add("next-sdk-tool-overlay--exit");const e=wn;let t=!1,r;const n=()=>{t||(t=!0,r!==void 0&&(clearTimeout(r),r=void 0),e.parentNode&&e.parentNode.removeChild(e),wn===e&&(wn=null,Yl=null),e.removeEventListener("animationend",n))};e.addEventListener("animationend",n),r=setTimeout(n,500)}function aN(e){xa()&&(Ql+=1,oN(e))}function iN(){!xa()||Ql<=0||(Ql-=1,Ql===0&&sN())}function lN(e,t,r){if(!r)return;const n=t||e;return typeof r=="boolean"?r?{label:n}:void 0:{label:r.label||n}}const $w="next-sdk:tool-call",Lp="next-sdk:tool-response",jp="next-sdk:page-ready",Rw="next-sdk:page-leave",Pw="next-sdk:remoter-ready",cN="next-sdk:route-state-initial",Dp="next-sdk:tool-catalog-changed",Ea=new Map,Kt=e=>e.replace(/\/+$/,"")||"/",Xl=new Set;function uN(){typeof window<"u"&&Xl.add({win:window,origin:window.location.origin||"*"})}uN();function Mw(e,t,r={}){const n={type:e,route:t,...r};Xl.forEach(({win:o,origin:s})=>{try{o.postMessage(n,s)}catch{}})}function dN(){typeof window>"u"||window.addEventListener("message",e=>{if(e.data?.type!==Pw||!e.source||e.origin!==window.location.origin)return;const t=e.source;Xl.add({win:t,origin:e.origin||"*"})})}dN();const $a=new Map;function Up(){if(typeof window>"u")return;const e={type:Dp};Xl.forEach(({win:t,origin:r})=>{try{t.postMessage(e,r)}catch{}})}function zp(e){const t=e;try{t.sendToolListChanged?.()}catch{}}function pN(){return new Map}function fN(){return new Set(Ea.keys())}function hN(){const e=new Map;return Ea.forEach((t,r)=>{e.set(r,Array.from(t))}),e}function Nw(e,t){const r=Ea.get(e);return!!r&&r.has(t)}const rs=new Set,ec=new Map,tc=new Map,Zp=new Map,Ow=Symbol("builtin-remove-patched");function Fp(e,t){const r=t;if(r[Ow]||typeof r.remove!="function")return t;const n=r.remove.bind(r);return r.remove=()=>{try{n()}finally{oc(e)}},r[Ow]=!0,r}function rc(){if(typeof navigator>"u")return null;const e=navigator;return e.modelContext?.registerTool?e.modelContext:null}function Vp(){return typeof navigator>"u"?null:navigator.modelContextTesting??null}function Aw(){if(typeof window>"u")return!1;if(window.__NEXT_SDK_WEBMCP_DEBUG__===!0)return!0;try{return window.localStorage?.getItem("next-sdk:webmcp-debug")==="1"}catch{return!1}}function Xe(e,t={}){if(Aw())try{console.info("[next-sdk/webmcp]",e,t)}catch{}}async function ns(e){if(!Aw())return;const t=Vp();if(!t){Xe(`${e}:snapshot`,{available:!1});return}try{const r=t.listTools??t.getTools;if(!r){Xe(`${e}:snapshot`,{available:!1,reason:"no-list-method"});return}const n=await r(),s=(Array.isArray(n)?n:[]).map(a=>!a||typeof a!="object"?"":String(a.name??"")).filter(Boolean);Xe(`${e}:snapshot`,{count:s.length,names:s})}catch(r){Xe(`${e}:snapshot-error`,{error:r instanceof Error?r.message:String(r)})}}function mN(e){const t=rc();if(!t?.unregisterTool){Xe("direct-unregister-skip",{name:e,reason:"missing-unregister"});return}Xe("direct-unregister-start",{name:e});try{const r=t.unregisterTool.call(t,e);if(r&&typeof r=="object"&&"then"in r){r.then(()=>{Xe("direct-unregister-done",{name:e,async:!0}),ns(`direct-unregister-done:${e}`)}).catch(n=>{Xe("direct-unregister-error",{name:e,async:!0,error:n instanceof Error?n.message:String(n)})});return}Xe("direct-unregister-done",{name:e,async:!1}),ns(`direct-unregister-done:${e}`)}catch{Xe("direct-unregister-error",{name:e,async:!1})}}function gN(e){if(typeof e=="function")return e;if(!e||typeof e!="object")return null;const t=e;return typeof t.unregister=="function"?t.unregister.bind(t):typeof t.remove=="function"?t.remove.bind(t):typeof t.dispose=="function"?t.dispose.bind(t):typeof t.close=="function"?t.close.bind(t):null}function yN(){return!!rc()}function qw(e){return e._def?.typeName}function vN(e){return e.description}function mr(e,t){const r=vN(e);return r?{...t,description:r}:t}function Lw(e){const t=qw(e);if(t===B.ZodOptional||t===B.ZodDefault)return!0;if(t===B.ZodEffects){const r=e._def.schema;return Lw(r)}return!1}function _N(e){if(typeof e=="string")return"string";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean";if(e===null)return"null"}function os(e){switch(qw(e)){case B.ZodString:return mr(e,{type:"string"});case B.ZodNumber:return mr(e,{type:"number"});case B.ZodBoolean:return mr(e,{type:"boolean"});case B.ZodArray:{const r=e._def.type;return mr(e,{type:"array",items:os(r)})}case B.ZodEnum:{const r=e.options??[];return mr(e,{type:"string",enum:r})}case B.ZodNativeEnum:{const n=Object.values(e._def.values).filter(o=>typeof o=="string"||typeof o=="number");return mr(e,{enum:n})}case B.ZodLiteral:{const r=e._def.value,n=_N(r);return mr(e,{...n?{type:n}:{},const:r??null})}case B.ZodUnion:{const r=e._def.options??[];return mr(e,{anyOf:r.map(n=>os(n))})}case B.ZodNullable:{const r=e._def.innerType;return mr(e,{anyOf:[os(r),{type:"null"}]})}case B.ZodObject:{const r=e,n=r.shape??(typeof r._def?.shape=="function"?r._def.shape():r._def?.shape)??{};return mr(e,jw(n))}case B.ZodEffects:{const r=e._def.schema;return mr(e,os(r))}case B.ZodOptional:case B.ZodDefault:{const r=e._def.innerType;return mr(e,os(r))}default:return mr(e,{})}}function jw(e={}){const t={},r=[];return Object.entries(e).forEach(([n,o])=>{t[n]=os(o),Lw(o)||r.push(n)}),{type:"object",properties:t,...r.length?{required:r}:{},additionalProperties:!1}}async function nc(e){const t=rc();if(!t)return Xe("register-builtin-skip",{name:e.name,reason:"unsupported"}),!1;if(rs.has(e.name))return Xe("register-builtin-skip",{name:e.name,reason:"already-registered"}),!0;const r=()=>{ec.delete(e.name),tc.delete(e.name),rs.delete(e.name)};Xe("register-builtin-start",{name:e.name});const n=(async()=>{const o={name:e.name,description:e.description,inputSchema:jw(e.inputSchema??{}),execute:e.execute},s=await t.registerTool(o),a=gN(s);a&&ec.set(e.name,a),tc.set(e.name,o),rs.add(e.name),Xe("register-builtin-success",{name:e.name,hasDisposer:!!a}),ns(`register-success:${e.name}`)})();Zp.set(e.name,n);try{return await n,!0}catch(o){return r(),Xe("register-builtin-error",{name:e.name,error:o instanceof Error?o.message:String(o)}),!1}finally{Zp.delete(e.name)}}async function oc(e){Xe("unregister-builtin-start",{name:e});const t=()=>{ec.delete(e),tc.delete(e),rs.delete(e)},r=Zp.get(e);if(r)try{await r}catch{}const n=ec.get(e);if(n)try{return await n(),t(),Xe("unregister-builtin-success",{name:e,method:"disposer"}),ns(`unregister-success:${e}`),!0}catch(i){Xe("unregister-builtin-disposer-error",{name:e,error:i instanceof Error?i.message:String(i)})}const o=rc();if(!o)return t(),Xe("unregister-builtin-skip",{name:e,reason:"unsupported"}),!1;if(!o.unregisterTool)return t(),Xe("unregister-builtin-skip",{name:e,reason:"missing-unregister"}),!1;const s=tc.get(e),a=[e,{name:e},{toolName:e},{tool:{name:e}},s].filter(Boolean);for(const i of a)try{if(Xe("unregister-builtin-try",{name:e,candidate:i}),await o.unregisterTool.call(o,i)===!1)continue;return t(),Xe("unregister-builtin-success",{name:e,method:"unregisterTool",candidate:i}),ns(`unregister-success:${e}`),!0}catch(l){Xe("unregister-builtin-try-error",{name:e,candidate:i,error:l instanceof Error?l.message:String(l)})}return t(),Xe("unregister-builtin-failed",{name:e}),ns(`unregister-failed:${e}`),!1}function wN(e){return rs.has(e)}async function bN(){const e=Array.from(rs);for(const t of e)try{await oc(t)}catch{}}async function TN(){const e=Vp();if(!e?.listTools)return[];try{const t=await e.listTools();return Array.isArray(t)?t:[]}catch{return[]}}async function kN(e,t){const r=Vp();if(!r?.executeTool)throw new Error("当前浏览器不支持 navigator.modelContextTesting.executeTool。");return await r.executeTool(e,JSON.stringify(t??{}))}let Ra=null;function SN(e){Ra=e}function Dw(e){if(typeof window>"u")return!1;const t=Kt(e),r=Kt(window.location.pathname);return r===t||r.endsWith(t)&&(r.length===t.length||r[r.lastIndexOf(t)-1]==="/")}function CN(e,t=1500){if(typeof window>"u")return Promise.resolve();const r=Kt(e);return new Promise(n=>{let o=!1;const s=()=>{o||(o=!0,window.removeEventListener("message",a),n())},a=i=>{if(i.source===window){if(i.data?.type===jp){Kt(String(i.data.route??""))===r&&s();return}i.data?.type===Dp&&Dw(r)&&s()}};window.addEventListener("message",a),setTimeout(s,t)})}function IN(e){return e}function xN(e,t){return t.map(r=>e.registerTool(r.name,r.config,{route:r.route,timeout:r.timeout,invokeEffect:r.invokeEffect}))}function EN(e){return Hp(e)}function $N(e,t){const r=t.tools??[];if(!r.length)throw new Error("registerRuntimePageTools: tools 不能为空。");const n=t.route?Kt(t.route):null,o=new Set(r.map(l=>Kt(l.route)));if(!n&&o.size>1)throw new Error("registerRuntimePageTools: tools 包含多个 route,请显式传入 route。");const s=n??Array.from(o)[0],a=r.filter(l=>Kt(l.route)===s);if(!a.length)throw new Error(`registerRuntimePageTools: route "${s}" 下未找到工具定义。`);a.forEach(l=>{const c=Kt(l.route),u=$a.get(l.name);if(u){if(u.route!==c)throw new Error(`registerRuntimePageTools: 工具 "${l.name}" 已绑定路由 "${u.route}",不能重复绑定到 "${c}"。`);u.refCount+=1;return}const f=e.registerTool(l.name,l.config,{route:c,timeout:l.timeout,invokeEffect:l.invokeEffect});$a.set(l.name,{tool:f,route:c,refCount:1})});const i=Hp({route:s,tools:a,context:t.context});return()=>{i(),t.removeOnUnmount!==!1&&a.forEach(l=>{const c=$a.get(l.name);c&&(c.refCount-=1,!(c.refCount>0)&&($a.delete(l.name),e.unregisterTool(l.name)))})}}function RN(e,t){const r=t?.name??"navigate_to_page",n=t?.title??"页面跳转",o=t?.description??'当需要的工具在当前页面不可用时,使用此工具跳转到特定页面。例如:要查询订单时跳转到 "/orders",要创建价保时跳转到 "/price-protection"。',s=t?.timeoutMs??1500,a={path:Fe().describe('目标页面的路由地址,例如 "/orders"、"/inventory"、"/price-protection" 等。')},i=async({path:u})=>{if(typeof window>"u")return{content:[{type:"text",text:"当前环境不支持页面跳转(window 不存在)。"}]};if(!Ra)return{content:[{type:"text",text:"页面跳转失败:尚未在应用入口调用 setNavigator 注册导航函数,无法执行路由跳转。"}]};try{if(Dw(u))return{content:[{type:"text",text:`当前已在页面:${u}。请继续你的下一步操作。`}]};const f=CN(u,s);return await Ra(u),await f,{content:[{type:"text",text:`已成功跳转至页面:${u}。请继续你的下一步操作。`}]}}catch(f){return{content:[{type:"text",text:`页面跳转失败:${f instanceof Error?f.message:String(f)}。`}]}}},l=e.registerTool(r,{title:n,description:o,inputSchema:a},i);return typeof e.unregisterTool=="function"?l:(nc({name:r,description:o,inputSchema:a,execute:async u=>await i(u)}),Fp(r,l))}function PN(e,t,r=3e4,n){return o=>{const s=fd();return new Promise((a,i)=>{let l,c;const u=()=>{clearTimeout(l),window.removeEventListener("message",f),c&&window.removeEventListener("message",c),n&&iN()};l=setTimeout(()=>{u(),i(new Error(`工具 [${e}] 调用超时 (${r}ms),请检查目标页面是否正确调用了 registerPageTool`))},r);const f=y=>{y.source===window&&y.data?.type===Lp&&y.data.callId===s&&(u(),y.data.error?i(new Error(y.data.error)):a(y.data.result))};window.addEventListener("message",f);const p=()=>{window.postMessage({type:$w,callId:s,toolName:e,route:t,input:o},window.location.origin||"*")};let h=!1;const m=()=>{h||(h=!0,p())};(async()=>{try{if(n&&aN(n),Nw(t,e)){m();return}c=y=>{if(y.source!==window||y.data?.type!==jp||Kt(String(y.data.route??""))!==t)return;const v=Array.isArray(y.data.toolNames)?new Set(y.data.toolNames.map(g=>String(g))):null;v&&!v.has(e)||(window.removeEventListener("message",c),m())},window.addEventListener("message",c),Ra&&await Ra(t),Nw(t,e)&&(window.removeEventListener("message",c),m())}catch(y){u(),i(y instanceof Error?y:new Error(String(y)))}})()})}}function MN(e,t){const n=(t?.nativeWebMcp?.mode??"auto")!=="disabled",o=new Map,s=(a,i,l=!1)=>{const c=o.get(i),u=!!c;if(Xe("proxy-unregister-start",{name:i,hasExisting:!!c,silent:l}),mN(i),o.delete(i),$a.delete(i),c)try{c.remove()}catch{}return oc(i),!l&&u&&(zp(a),Up()),Xe("proxy-unregister-done",{name:i,removed:!!c,silent:l}),!!c};return new Proxy(e,{get(a,i,l){return i==="unregisterTool"?c=>s(a,c,!1):i==="registerTool"?(c,u,f)=>{Xe("proxy-register-start",{name:c,mode:typeof f=="function"?"callback":"route",shouldRegisterBuiltin:n}),s(a,c,!0);const p=a.registerTool.bind(a);if(typeof f=="function"){const b=p(c,u,f),k=n?Fp(c,b):b;return o.set(c,k),zp(a),Up(),n&&nc({name:c,description:u?.description,inputSchema:u?.inputSchema,execute:async C=>await f(C)}),Xe("proxy-register-done",{name:c,mode:"callback"}),k}const{route:h,timeout:m,invokeEffect:_}=f,y=Kt(h),w=lN(c,u?.title,_),v=PN(c,y,m,w),g=p(c,u,v),S=n?Fp(c,g):g;return o.set(c,S),zp(a),Up(),n&&nc({name:c,description:u?.description,inputSchema:u?.inputSchema,execute:async b=>await v(b)}),Xe("proxy-register-done",{name:c,mode:"route"}),S}:Reflect.get(a,i,l)}})}function NN(e){if("handlers"in e)return{route:Kt(e.route??window.location.pathname),handlers:e.handlers};const t=e.tools??[];if(!t.length)throw new Error("registerPageTool: tools 不能为空。");const r=e.route?Kt(e.route):null,n=new Set(t.map(a=>Kt(a.route)));if(!r&&n.size>1)throw new Error("registerPageTool: tools 包含多个 route,请显式传入 route 参数。");const o=r??Array.from(n)[0],s={};if(t.filter(a=>Kt(a.route)===o).forEach(a=>{if(s[a.name])throw new Error(`registerPageTool: 工具 "${a.name}" 在 route "${o}" 上重复定义。`);s[a.name]=i=>a.handler(i,e.context)}),!Object.keys(s).length)throw new Error(`registerPageTool: route "${o}" 下未找到可激活的工具定义。`);return{route:o,handlers:s}}function Hp(e){const{route:t,handlers:r}=NN(e),n=Object.keys(r),o=async s=>{if(s.source!==window||s.data?.type!==$w||Kt(String(s.data?.route??""))!==t||!(s.data.toolName in r))return;const{callId:a,toolName:i,input:l}=s.data;try{const c=await r[i](l);window.postMessage({type:Lp,callId:a,result:c},window.location.origin||"*")}catch(c){window.postMessage({type:Lp,callId:a,error:c instanceof Error?c.message:String(c)},window.location.origin||"*")}};return Ea.set(t,new Set(n)),window.addEventListener("message",o),Mw(jp,t,{toolNames:n}),()=>{Ea.delete(t),window.removeEventListener("message",o),Mw(Rw,t)}}const Uw=/^\.\/[^/]+\/SKILL\.md$/,ON=/^---\s*\n([\s\S]+?)\s*\n---/;function Bp(e){const t=e.match(ON);if(!t?.[1])return null;const r=t[1],n=r.match(/^name:\s*(.+)$/m),o=r.match(/^description:\s*(.+)$/m),s=n?.[1]?.trim(),a=o?.[1]?.trim();return s&&a?{name:s,description:a}:null}function ss(e){const t={};for(const[r,n]of Object.entries(e)){const o=r.replace(/\\/g,"/"),s=o.lastIndexOf("skills/"),a=s>=0?o.slice(s+7):o,i=a.startsWith("./")?a:`./${a}`;t[i]=n}return t}function zw(e){const t=ss(e);return Object.keys(t).filter(r=>Uw.test(r))}function AN(e){const t=ss(e),r=Object.keys(t).filter(o=>Uw.test(o)),n=[];for(const o of r){const s=t[o];if(!s)continue;const a=Bp(s);a&&n.push({name:a.name,description:a.description,path:o})}return n}function qN(e){return e.length===0?"":`## 可用技能
806
+ `,document.head.appendChild(e),Rw=e}function mO(){if(!Ma()||Tn)return;hO();const e=document.createElement("div");e.className="next-sdk-tool-overlay";const t=document.createElement("div");t.className="next-sdk-tool-overlay__glow-ring";const r=document.createElement("div");r.className="next-sdk-tool-overlay__panel";const n=document.createElement("div");n.className="next-sdk-tool-overlay__indicator";const o=document.createElement("div");o.className="next-sdk-tool-overlay__indicator-orbit";const s=document.createElement("div");s.className="next-sdk-tool-overlay__indicator-core";const a=document.createElement("div");a.className="next-sdk-tool-overlay__content";const i=document.createElement("div");i.className="next-sdk-tool-overlay__title",i.textContent="AI 正在调用页面工具";const l=document.createElement("span");l.className="next-sdk-tool-overlay__title-dot";const c=document.createElement("div");c.className="next-sdk-tool-overlay__label",i.prepend(l),a.appendChild(i),a.appendChild(c),n.appendChild(o),n.appendChild(s),r.appendChild(n),r.appendChild(a),e.appendChild(t),e.appendChild(r),document.body.appendChild(e),Tn=e,rc=c}function gO(e){Ma()&&(mO(),!(!Tn||!rc)&&(Tn.classList.remove("next-sdk-tool-overlay--exit"),rc.textContent=e.label))}function yO(){if(!Tn)return;Tn.classList.add("next-sdk-tool-overlay--exit");const e=Tn;let t=!1,r;const n=()=>{t||(t=!0,r!==void 0&&(clearTimeout(r),r=void 0),e.parentNode&&e.parentNode.removeChild(e),Tn===e&&(Tn=null,rc=null),e.removeEventListener("animationend",n))};e.addEventListener("animationend",n),r=setTimeout(n,500)}function vO(e){Ma()&&(nc+=1,gO(e))}function _O(){!Ma()||nc<=0||(nc-=1,nc===0&&yO())}function Pw(e,t,r){if(!r)return;const n=t||e;return typeof r=="boolean"?r?{label:n}:void 0:{label:r.label||n}}const Mw="next-sdk:tool-call",Fp="next-sdk:tool-response",To="next-sdk:tool-registered",oc="next-sdk:tool-unregistered",Ow="next-sdk:remoter-ready",Vp=new Map,Oa=e=>e.replace(/\/+$/,"")||"/",Hp=new Set;function wO(){zn()&&Hp.add({win:window,origin:window.location.origin||"*"})}wO();function So(e){if(!zn())return;const t={type:e};Hp.forEach(({win:r,origin:n})=>{try{r.postMessage(t,n)}catch{}})}function bO(){zn()&&window.addEventListener("message",e=>{if(e.data?.type!==Ow||!e.source||e.origin!==window.location.origin)return;const t=e.source;Hp.add({win:t,origin:e.origin||"*"})})}bO();function Bp(e){if(!e)return;const t=e;try{typeof t.sendToolListChanged=="function"?t.sendToolListChanged():t.server&&typeof t.server.sendToolListChanged=="function"&&t.server.sendToolListChanged()}catch{}}function Nw(e,t){const r=Vp.get(e);return!!r&&r.has(t)}let Na=null;function kO(e){Na=e}function TO(e){if(!zn())return!1;const t=Oa(e);return Oa(window.location.pathname)===t}function SO(e){return zn()?new Promise(t=>{let r=!1;const n=()=>{r||(r=!0,window.removeEventListener("message",o),t())},o=s=>{s.source===window&&s.data?.type===To&&n()};window.addEventListener("message",o),setTimeout(n,e)}):Promise.resolve()}function CO(e,t){const r=t?.name??"navigate_to_page",n=t?.title??"页面跳转",o=t?.description??'当需要的工具在当前页面不可用时,使用此工具跳转到特定页面。例如:要查询订单时跳转到 "/orders",要创建价保时跳转到 "/price-protection"。',s=t?.timeoutMs??5e3,a={type:"object",properties:{path:{type:"string",description:'目标页面的路由地址,例如 "/orders"、"/inventory"、"/price-protection" 等。'}},required:["path"]},i=async({path:l})=>{if(!zn())return{content:[{type:"text",text:"当前环境不支持页面跳转(window 不存在)。"}]};if(!Na)return{content:[{type:"text",text:"页面跳转失败:尚未在应用入口调用 setNavigator 注册导航函数,无法执行路由跳转。"}]};try{if(TO(l))return{content:[{type:"text",text:`当前已在页面:${l}。请继续你的下一步操作。`}]};const c=SO(s);return await Na(l)!==!0&&(await c,await new Promise(f=>setTimeout(f,500))),{content:[{type:"text",text:`已成功跳转至页面:${l}。请继续你的下一步操作。`}]}}catch(c){return{content:[{type:"text",text:`页面跳转失败:${c instanceof Error?c.message:String(c)}。`}]}}};if(e&&typeof e.registerTool=="function")return e.__isNextSdkBridgeSetup?e.registerTool({name:r,title:n,description:o,inputSchema:a,execute:i}):e.registerTool(r,{title:n,description:o,inputSchema:a},i);throw new Error("Failed to register navigate tool: invalid server instance.")}function Aw(e,t,r=3e4,n){return o=>{const s=yd();return new Promise((a,i)=>{let l,c;const u=()=>{clearTimeout(l),window.removeEventListener("message",f),c&&window.removeEventListener("message",c),n&&_O()};l=setTimeout(()=>{u(),i(new Error(`工具 [${e}] 调用超时 (${r}ms),请检查目标页面是否正确调用了 registerPageTool`))},r);const f=g=>{g.source===window&&g.data?.type===Fp&&g.data.callId===s&&(u(),g.data.error?i(new Error(g.data.error)):a(g.data.result))};window.addEventListener("message",f);const p=()=>{window.postMessage({type:Mw,callId:s,toolName:e,route:t,input:o},window.location.origin||"*")};let h=!1;const m=()=>{h||(h=!0,p())};(async()=>{try{if(n&&vO(n),Nw(t,e)){m();return}if(c=g=>{g.source!==window||g.data?.type!==To||(window.removeEventListener("message",c),m())},window.addEventListener("message",c),Na&&await Na(t)===!0){c&&window.removeEventListener("message",c),m();return}Nw(t,e)&&(window.removeEventListener("message",c),m())}catch(g){u(),i(g instanceof Error?g:new Error(String(g)))}})()})}}function xO(e){const t=new Map,r=(n,o,s=!1)=>{const a=t.get(o),i=!!a;if(t.delete(o),a)try{a.remove()}catch{}return!s&&i&&(Bp(n),So(oc)),!!a};return new Proxy(e,{get(n,o,s){return o==="unregisterTool"?a=>r(n,a,!1):o==="registerTool"?(a,i,l)=>{r(n,a,!0);const c=n.registerTool.bind(n);if(typeof l=="function"){const w=c(a,i,l);return t.set(a,w),Bp(n),So(To),w}const{route:u,timeout:f,invokeEffect:p}=l,h=Oa(u),m=Pw(a,i?.title,p),_=Aw(a,h,f,m),g=c(a,i,_);return t.set(a,g),Bp(n),So(To),g}:Reflect.get(n,o,s)}})}function IO(e){const{route:t,handlers:r}=e,n=Oa(t??window.location.pathname),o=Object.keys(r),s=async a=>{if(a.source!==window||a.data?.type!==Mw||!(a.data.toolName in r))return;const{callId:i,toolName:l,input:c}=a.data;try{const u=r[l];if(!u)throw new Error(`Tool "${l}" handler not found.`);const f=await u(c);window.postMessage({type:Fp,callId:i,result:f},window.location.origin||"*")}catch(u){window.postMessage({type:Fp,callId:i,error:u instanceof Error?u.message:String(u)},window.location.origin||"*")}};return Vp.set(n,new Set(o)),window.addEventListener("message",s),So(To),()=>{Vp.delete(n),window.removeEventListener("message",s),So(oc)}}function qw(){if(typeof navigator>"u")return;const t=navigator.modelContext;if(!t||t.__isNextSdkBridgeSetup)return;const r=t.registerTool?.bind(t),n=t.unregisterTool?.bind(t);typeof r=="function"&&(t.registerTool=o=>{const s=o.name,a={...o},i=a.routeConfig&&typeof a.routeConfig=="object"&&"route"in a.routeConfig?a.routeConfig:null;if(i){const l=Oa(i.route),c=Pw(s,a.title,i.invokeEffect),u=Aw(s,l,i.timeout,c);a.execute=u,delete a.routeConfig}try{r(a),So(To)}catch{}}),typeof n=="function"&&(t.unregisterTool=o=>{try{n(o),So(oc)}catch{}}),t.__isNextSdkBridgeSetup=!0}const jw=/^\.\/[^/]+\/SKILL\.md$/,$O=/^---\s*\n([\s\S]+?)\s*\n---/;function Jp(e){const t=e.match($O);if(!t?.[1])return null;const r=t[1],n=r.match(/^name:\s*(.+)$/m),o=r.match(/^description:\s*(.+)$/m),s=n?.[1]?.trim(),a=o?.[1]?.trim();return s&&a?{name:s,description:a}:null}function cs(e){const t={};for(const[r,n]of Object.entries(e)){const o=r.replace(/\\/g,"/"),s=o.lastIndexOf("skills/"),a=s>=0?o.slice(s+7):o,i=a.startsWith("./")?a:`./${a}`;t[i]=n}return t}function Lw(e){const t=cs(e);return Object.keys(t).filter(r=>jw.test(r))}function EO(e){const t=cs(e),r=Object.keys(t).filter(o=>jw.test(o)),n=[];for(const o of r){const s=t[o];if(!s)continue;const a=Jp(s);a&&n.push({name:a.name,description:a.description,path:o})}return n}function RO(e){return e.length===0?"":`## 可用技能
807
807
 
808
808
  ${e.map(r=>`- **${r.name}**: ${r.description}`).join(`
809
809
  `)}
810
810
 
811
- 当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`}function LN(e){const t=ss(e);return Object.keys(t)}function sc(e,t){const r=ss(e),n=r[t];if(n)return n;const o=t.replace(/^\.?\//,"/"),s=Object.keys(r).find(a=>a.endsWith(o));return s?r[s]:void 0}function Zw(e,t){const r=ss(e),n=zw(r),o=n.find(s=>s.startsWith(`./${t}/SKILL.md`));if(o)return o;for(const s of n){const a=r[s];if(a){const i=Bp(a);if(i&&i.name===t)return s}}}const jN=Qt({skillName:Fe().optional().describe('进入某个技能的主入口名称。优先匹配技能的目录名(如 ecommerce),或者技能的中文名称(如"客户价保单创建及审核")。'),path:Fe().optional().describe("你想查阅的文档的路径。如 ./calculator/SKILL.md 或从其他文档里看到的相对路径 ./reference/inventory.md。"),currentPath:Fe().optional().describe("你当前正在阅读的文档路径(如果有)。比如你刚刚读取了 ./ecommerce/SKILL.md,请把这个路径原样传回来,这样系统才能根据你的相对路径准确找到下一份文件。")});function DN(e){const t=ss(e);return{get_skill_content:{description:"根据技能名称或文档路径获取该技能的完整文档内容。如果你想根据相对路径查阅文件,请务必同时提供你当前所在的文件路径 currentPath。",inputSchema:jN,execute:n=>{const{skillName:o,path:s,currentPath:a}=n;let i,l="";if(s){let c=".";if(a){const p=a.lastIndexOf("/");p>=0&&(c=a.slice(0,p))}const u=`http://localhost/${c}/`;if(l="."+new URL(s,u).pathname,i=sc(t,l),i===void 0&&(s.startsWith("./")||s.startsWith("../"))&&a){const p=a.split("/");if(p.length>=2){const m=`http://localhost/${p[1]}/`,y="."+new URL(s,m).pathname;i=sc(t,y),i&&(l=y)}}if(i&&!t[l]){const p=l.replace(/^\.?\//,"/"),h=Object.keys(t).find(m=>m.endsWith(p));h&&(l=h)}}else if(o){const c=Zw(t,o);c&&(l=c,i=sc(t,c))}return i===void 0?{error:"未找到对应技能文档",skillName:o,path:s,providedCurrentPath:a,attemptedPath:l}:{content:i,path:l}}}}}me.AgentModelProvider=eN,me.Ajv=Ch,me.AuthClientProvider=rI,me.ContentScriptServerTransport=RI,me.ExtensionClientTransport=h2,me.ExtensionPageServerTransport=$I,me.InMemoryTransport=oa,me.MSG_PAGE_LEAVE=Rw,me.MSG_REMOTER_READY=Pw,me.MSG_ROUTE_STATE_INITIAL=cN,me.MSG_TOOL_CATALOG_CHANGED=Dp,me.QrCode=G2,me.ResourceTemplate=pI,me.UriTemplate=mn,me.WebMcpClient=d2,me.WebMcpServer=yI,me.completable=sI,me.createMessageChannelClientTransport=SI,me.createMessageChannelPairTransport=_I,me.createMessageChannelServerTransport=vI,me.createRemoter=i5,me.createSSEClientTransport=TI,me.createSkillTools=DN,me.createStreamableHTTPClientTransport=kI,me.definePageTool=IN,me.executeBuiltinWebMcpTool=kN,me.forceResetBuiltinWebMcpTools=bN,me.formatSkillsForSystemPrompt=qN,me.getAISDKTools=Iw,me.getActivePageTools=hN,me.getActiveRoutes=fN,me.getDisplayName=gI,me.getMainSkillPathByName=Zw,me.getMainSkillPaths=zw,me.getSkillMdContent=sc,me.getSkillMdPaths=LN,me.getSkillOverviews=AN,me.getToolRouteMap=pN,me.hasBuiltinWebMcpTool=wN,me.isBuiltinWebMcpSupported=yN,me.isMcpClient=xI,me.isMcpServer=bI,me.isMessageChannelClientTransport=II,me.isMessageChannelServerTransport=wI,me.isSSEClientTransport=CI,me.isStreamableHTTPClientTransport=p2,me.listBuiltinWebMcpTools=TN,me.mountPageTools=EN,me.parseSkillFrontMatter=Bp,me.registerBuiltinWebMcpTool=nc,me.registerNavigateTool=RN,me.registerPageTool=Hp,me.registerPageTools=xN,me.registerRuntimePageTools=$N,me.setNavigator=SN,me.unregisterBuiltinWebMcpTool=oc,me.withPageTools=MN,me.z=V3,Object.defineProperty(me,Symbol.toStringTag,{value:"Module"})}));
811
+ 当需要用到某技能时,请使用 get_skill_content 工具获取该技能的完整文档内容。`}function PO(e){const t=cs(e);return Object.keys(t)}function sc(e,t){const r=cs(e),n=r[t];if(n)return n;const o=t.replace(/^\.?\//,"/"),s=Object.keys(r).find(a=>a.endsWith(o));return s?r[s]:void 0}function Dw(e,t){const r=cs(e),n=Lw(r),o=n.find(s=>s.startsWith(`./${t}/SKILL.md`));if(o)return o;for(const s of n){const a=r[s];if(a){const i=Jp(a);if(i&&i.name===t)return s}}}const MO=tr({skillName:Ye().optional().describe('进入某个技能的主入口名称。优先匹配技能的目录名(如 ecommerce),或者技能的中文名称(如"客户价保单创建及审核")。'),path:Ye().optional().describe("你想查阅的文档的路径。如 ./calculator/SKILL.md 或从其他文档里看到的相对路径 ./reference/inventory.md。"),currentPath:Ye().optional().describe("你当前正在阅读的文档路径(如果有)。比如你刚刚读取了 ./ecommerce/SKILL.md,请把这个路径原样传回来,这样系统才能根据你的相对路径准确找到下一份文件。")});function OO(e){const t=cs(e);return{get_skill_content:{description:"根据技能名称或文档路径获取该技能的完整文档内容。如果你想根据相对路径查阅文件,请务必同时提供你当前所在的文件路径 currentPath。",inputSchema:MO,execute:n=>{const{skillName:o,path:s,currentPath:a}=n;let i,l="";if(s){let c=".";if(a){const p=a.lastIndexOf("/");p>=0&&(c=a.slice(0,p))}const u=`http://localhost/${c}/`;if(l="."+new URL(s,u).pathname,i=sc(t,l),i===void 0&&(s.startsWith("./")||s.startsWith("../"))&&a){const p=a.split("/");if(p.length>=2){const m=`http://localhost/${p[1]}/`,g="."+new URL(s,m).pathname;i=sc(t,g),i&&(l=g)}}if(i&&!t[l]){const p=l.replace(/^\.?\//,"/"),h=Object.keys(t).find(m=>m.endsWith(p));h&&(l=h)}}else if(o){const c=Dw(t,o);c&&(l=c,i=sc(t,c))}return i===void 0?{error:"未找到对应技能文档",skillName:o,path:s,providedCurrentPath:a,attemptedPath:l}:{content:i,path:l}}}}}function Aa(e,t){const r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const n=e.length;if(n!==t.length)return!1;for(let o=0;o<n;o++)if(!Aa(e[o],t[o]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;const n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(const a of n)if(!Aa(e[a],t[a]))return!1;return!0}return e===t}function Br(e){return encodeURI(NO(e))}function NO(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}const AO={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},qO={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},jO={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!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};let LO=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Co(e,t=Object.create(null),r=LO,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){const s=e.$id||e.id;if(s){const a=new URL(s,r.href);a.hash.length>1?t[a.href]=e:(a.hash="",n===""?r=a:Co(e,t,r))}}else if(e!==!0&&e!==!1)return t;const o=r.href+(n?"#"+n:"");if(t[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o}),e.$ref&&e.__absolute_ref__===void 0){const s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){const s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){const s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(jO[s])continue;const a=`${n}/${Br(s)}`,i=e[s];if(Array.isArray(i)){if(AO[s]){const l=i.length;for(let c=0;c<l;c++)Co(i[c],t,r,`${a}/${c}`)}}else if(qO[s])for(let l in i)Co(i[l],t,r,`${a}/${Br(l)}`);else Co(i,t,r,a)}return t}const DO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,UO=[0,31,28,31,30,31,30,31,31,30,31,30,31],zO=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,ZO=/^(?=.{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,FO=/^(?:[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,VO=/^(?:(?:[^\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,HO=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!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-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,BO=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,JO=/^(?:\/(?:[^~/]|~0|~1)*)*$/,WO=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,GO=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,KO=e=>{if(e[0]==='"')return!1;const[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},YO=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,QO=/^((([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,XO=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function rn(e){return e.test.bind(e)}const Uw={date:zw,time:Zw.bind(void 0,!1),"date-time":rN,duration:XO,uri:sN,"uri-reference":rn(FO),"uri-template":rn(VO),url:rn(HO),email:KO,hostname:rn(ZO),ipv4:rn(YO),ipv6:rn(QO),regex:iN,uuid:rn(BO),"json-pointer":rn(JO),"json-pointer-uri-fragment":rn(WO),"relative-json-pointer":rn(GO)};function eN(e){return e%4===0&&(e%100!==0||e%400===0)}function zw(e){const t=e.match(DO);if(!t)return!1;const r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&eN(r)?29:UO[n])}function Zw(e,t){const r=t.match(zO);if(!r)return!1;const n=+r[1],o=+r[2],s=+r[3],a=!!r[5];return(n<=23&&o<=59&&s<=59||n==23&&o==59&&s==60)&&(!e||a)}const tN=/t|\s/i;function rN(e){const t=e.split(tN);return t.length==2&&zw(t[0])&&Zw(!0,t[1])}const nN=/\/|:/,oN=/^(?:[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 sN(e){return nN.test(e)&&oN.test(e)}const aN=/[^\\]\\Z/;function iN(e){if(aN.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}function lN(e){let t=0,r=e.length,n=0,o;for(;n<r;)t++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=e.charCodeAt(n),(o&64512)==56320&&n++);return t}function bt(e,t,r="2019-09",n=Co(t),o=!0,s=null,a="#",i="#",l=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:a,keyword:"false",keywordLocation:a,error:"False boolean schema."}]};const c=typeof e;let u;switch(c){case"boolean":case"number":case"string":u=c;break;case"object":e===null?u="null":Array.isArray(e)?u="array":u="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}const{$ref:f,$recursiveRef:p,$recursiveAnchor:h,type:m,const:_,enum:g,required:w,not:v,anyOf:y,allOf:S,oneOf:b,if:T,then:x,else:R,format:C,properties:L,patternProperties:O,additionalProperties:q,unevaluatedProperties:z,minProperties:H,maxProperties:ee,propertyNames:re,dependentRequired:X,dependentSchemas:V,dependencies:ie,prefixItems:D,items:E,additionalItems:U,unevaluatedItems:Z,contains:I,minContains:M,maxContains:B,minItems:oe,maxItems:ne,uniqueItems:be,minimum:W,maximum:A,exclusiveMinimum:F,exclusiveMaximum:J,multipleOf:Q,minLength:he,maxLength:Pe,pattern:Ke,__absolute_ref__:it,__absolute_recursive_ref__:gt}=t,ae=[];if(h===!0&&s===null&&(s=t),p==="#"){const _e=s===null?n[gt]:s,ue=`${i}/$recursiveRef`,Ie=bt(e,s===null?t:s,r,n,o,_e,a,ue,l);Ie.valid||ae.push({instanceLocation:a,keyword:"$recursiveRef",keywordLocation:ue,error:"A subschema had errors."},...Ie.errors)}if(f!==void 0){const ue=n[it||f];if(ue===void 0){let te=`Unresolved $ref "${f}".`;throw it&&it!==f&&(te+=` Absolute URI "${it}".`),te+=`
812
+ Known schemas:
813
+ - ${Object.keys(n).join(`
814
+ - `)}`,new Error(te)}const Ie=`${i}/$ref`,ce=bt(e,ue,r,n,o,s,a,Ie,l);if(ce.valid||ae.push({instanceLocation:a,keyword:"$ref",keywordLocation:Ie,error:"A subschema had errors."},...ce.errors),r==="4"||r==="7")return{valid:ae.length===0,errors:ae}}if(Array.isArray(m)){let _e=m.length,ue=!1;for(let Ie=0;Ie<_e;Ie++)if(u===m[Ie]||m[Ie]==="integer"&&u==="number"&&e%1===0&&e===e){ue=!0;break}ue||ae.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(u!=="number"||e%1||e!==e)&&ae.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&ae.push({instanceLocation:a,keyword:"type",keywordLocation:`${i}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(_!==void 0&&(u==="object"||u==="array"?Aa(e,_)||ae.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(_)}.`}):e!==_&&ae.push({instanceLocation:a,keyword:"const",keywordLocation:`${i}/const`,error:`Instance does not match ${JSON.stringify(_)}.`})),g!==void 0&&(u==="object"||u==="array"?g.some(_e=>Aa(e,_e))||ae.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(_e=>e===_e)||ae.push({instanceLocation:a,keyword:"enum",keywordLocation:`${i}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){const _e=`${i}/not`;bt(e,v,r,n,o,s,a,_e).valid&&ae.push({instanceLocation:a,keyword:"not",keywordLocation:_e,error:'Instance matched "not" schema.'})}let rt=[];if(y!==void 0){const _e=`${i}/anyOf`,ue=ae.length;let Ie=!1;for(let ce=0;ce<y.length;ce++){const te=y[ce],Ce=Object.create(l),$=bt(e,te,r,n,o,h===!0?s:null,a,`${_e}/${ce}`,Ce);ae.push(...$.errors),Ie=Ie||$.valid,$.valid&&rt.push(Ce)}Ie?ae.length=ue:ae.splice(ue,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:_e,error:"Instance does not match any subschemas."})}if(S!==void 0){const _e=`${i}/allOf`,ue=ae.length;let Ie=!0;for(let ce=0;ce<S.length;ce++){const te=S[ce],Ce=Object.create(l),$=bt(e,te,r,n,o,h===!0?s:null,a,`${_e}/${ce}`,Ce);ae.push(...$.errors),Ie=Ie&&$.valid,$.valid&&rt.push(Ce)}Ie?ae.length=ue:ae.splice(ue,0,{instanceLocation:a,keyword:"allOf",keywordLocation:_e,error:"Instance does not match every subschema."})}if(b!==void 0){const _e=`${i}/oneOf`,ue=ae.length,Ie=b.filter((ce,te)=>{const Ce=Object.create(l),$=bt(e,ce,r,n,o,h===!0?s:null,a,`${_e}/${te}`,Ce);return ae.push(...$.errors),$.valid&&rt.push(Ce),$.valid}).length;Ie===1?ae.length=ue:ae.splice(ue,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:_e,error:`Instance does not match exactly one subschema (${Ie} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...rt),T!==void 0){const _e=`${i}/if`;if(bt(e,T,r,n,o,s,a,_e,l).valid){if(x!==void 0){const Ie=bt(e,x,r,n,o,s,a,`${i}/then`,l);Ie.valid||ae.push({instanceLocation:a,keyword:"if",keywordLocation:_e,error:'Instance does not match "then" schema.'},...Ie.errors)}}else if(R!==void 0){const Ie=bt(e,R,r,n,o,s,a,`${i}/else`,l);Ie.valid||ae.push({instanceLocation:a,keyword:"if",keywordLocation:_e,error:'Instance does not match "else" schema.'},...Ie.errors)}}if(u==="object"){if(w!==void 0)for(const ce of w)ce in e||ae.push({instanceLocation:a,keyword:"required",keywordLocation:`${i}/required`,error:`Instance does not have required property "${ce}".`});const _e=Object.keys(e);if(H!==void 0&&_e.length<H&&ae.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${i}/minProperties`,error:`Instance does not have at least ${H} properties.`}),ee!==void 0&&_e.length>ee&&ae.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${i}/maxProperties`,error:`Instance does not have at least ${ee} properties.`}),re!==void 0){const ce=`${i}/propertyNames`;for(const te in e){const Ce=`${a}/${Br(te)}`,$=bt(te,re,r,n,o,s,Ce,ce);$.valid||ae.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:ce,error:`Property name "${te}" does not match schema.`},...$.errors)}}if(X!==void 0){const ce=`${i}/dependantRequired`;for(const te in X)if(te in e){const Ce=X[te];for(const $ of Ce)$ in e||ae.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:ce,error:`Instance has "${te}" but does not have "${$}".`})}}if(V!==void 0)for(const ce in V){const te=`${i}/dependentSchemas`;if(ce in e){const Ce=bt(e,V[ce],r,n,o,s,a,`${te}/${Br(ce)}`,l);Ce.valid||ae.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:te,error:`Instance has "${ce}" but does not match dependant schema.`},...Ce.errors)}}if(ie!==void 0){const ce=`${i}/dependencies`;for(const te in ie)if(te in e){const Ce=ie[te];if(Array.isArray(Ce))for(const $ of Ce)$ in e||ae.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ce,error:`Instance has "${te}" but does not have "${$}".`});else{const $=bt(e,Ce,r,n,o,s,a,`${ce}/${Br(te)}`);$.valid||ae.push({instanceLocation:a,keyword:"dependencies",keywordLocation:ce,error:`Instance has "${te}" but does not match dependant schema.`},...$.errors)}}}const ue=Object.create(null);let Ie=!1;if(L!==void 0){const ce=`${i}/properties`;for(const te in L){if(!(te in e))continue;const Ce=`${a}/${Br(te)}`,$=bt(e[te],L[te],r,n,o,s,Ce,`${ce}/${Br(te)}`);if($.valid)l[te]=ue[te]=!0;else if(Ie=o,ae.push({instanceLocation:a,keyword:"properties",keywordLocation:ce,error:`Property "${te}" does not match schema.`},...$.errors),Ie)break}}if(!Ie&&O!==void 0){const ce=`${i}/patternProperties`;for(const te in O){const Ce=new RegExp(te,"u"),$=O[te];for(const Y in e){if(!Ce.test(Y))continue;const Fe=`${a}/${Br(Y)}`,Ae=bt(e[Y],$,r,n,o,s,Fe,`${ce}/${Br(te)}`);Ae.valid?l[Y]=ue[Y]=!0:(Ie=o,ae.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:ce,error:`Property "${Y}" matches pattern "${te}" but does not match associated schema.`},...Ae.errors))}}}if(!Ie&&q!==void 0){const ce=`${i}/additionalProperties`;for(const te in e){if(ue[te])continue;const Ce=`${a}/${Br(te)}`,$=bt(e[te],q,r,n,o,s,Ce,ce);$.valid?l[te]=!0:(Ie=o,ae.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:ce,error:`Property "${te}" does not match additional properties schema.`},...$.errors))}}else if(!Ie&&z!==void 0){const ce=`${i}/unevaluatedProperties`;for(const te in e)if(!l[te]){const Ce=`${a}/${Br(te)}`,$=bt(e[te],z,r,n,o,s,Ce,ce);$.valid?l[te]=!0:ae.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:ce,error:`Property "${te}" does not match unevaluated properties schema.`},...$.errors)}}}else if(u==="array"){ne!==void 0&&e.length>ne&&ae.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${i}/maxItems`,error:`Array has too many items (${e.length} > ${ne}).`}),oe!==void 0&&e.length<oe&&ae.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${i}/minItems`,error:`Array has too few items (${e.length} < ${oe}).`});const _e=e.length;let ue=0,Ie=!1;if(D!==void 0){const ce=`${i}/prefixItems`,te=Math.min(D.length,_e);for(;ue<te;ue++){const Ce=bt(e[ue],D[ue],r,n,o,s,`${a}/${ue}`,`${ce}/${ue}`);if(l[ue]=!0,!Ce.valid&&(Ie=o,ae.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:ce,error:"Items did not match schema."},...Ce.errors),Ie))break}}if(E!==void 0){const ce=`${i}/items`;if(Array.isArray(E)){const te=Math.min(E.length,_e);for(;ue<te;ue++){const Ce=bt(e[ue],E[ue],r,n,o,s,`${a}/${ue}`,`${ce}/${ue}`);if(l[ue]=!0,!Ce.valid&&(Ie=o,ae.push({instanceLocation:a,keyword:"items",keywordLocation:ce,error:"Items did not match schema."},...Ce.errors),Ie))break}}else for(;ue<_e;ue++){const te=bt(e[ue],E,r,n,o,s,`${a}/${ue}`,ce);if(l[ue]=!0,!te.valid&&(Ie=o,ae.push({instanceLocation:a,keyword:"items",keywordLocation:ce,error:"Items did not match schema."},...te.errors),Ie))break}if(!Ie&&U!==void 0){const te=`${i}/additionalItems`;for(;ue<_e;ue++){const Ce=bt(e[ue],U,r,n,o,s,`${a}/${ue}`,te);l[ue]=!0,Ce.valid||(Ie=o,ae.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:te,error:"Items did not match additional items schema."},...Ce.errors))}}}if(I!==void 0)if(_e===0&&M===void 0)ae.push({instanceLocation:a,keyword:"contains",keywordLocation:`${i}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(M!==void 0&&_e<M)ae.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array has less items (${_e}) than minContains (${M}).`});else{const ce=`${i}/contains`,te=ae.length;let Ce=0;for(let $=0;$<_e;$++){const Y=bt(e[$],I,r,n,o,s,`${a}/${$}`,ce);Y.valid?(l[$]=!0,Ce++):ae.push(...Y.errors)}Ce>=(M||0)&&(ae.length=te),M===void 0&&B===void 0&&Ce===0?ae.splice(te,0,{instanceLocation:a,keyword:"contains",keywordLocation:ce,error:"Array does not contain item matching schema."}):M!==void 0&&Ce<M?ae.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${i}/minContains`,error:`Array must contain at least ${M} items matching schema. Only ${Ce} items were found.`}):B!==void 0&&Ce>B&&ae.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${i}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${Ce} items were found.`})}if(!Ie&&Z!==void 0){const ce=`${i}/unevaluatedItems`;for(ue;ue<_e;ue++){if(l[ue])continue;const te=bt(e[ue],Z,r,n,o,s,`${a}/${ue}`,ce);l[ue]=!0,te.valid||ae.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:ce,error:"Items did not match unevaluated items schema."},...te.errors)}}if(be)for(let ce=0;ce<_e;ce++){const te=e[ce],Ce=typeof te=="object"&&te!==null;for(let $=0;$<_e;$++){if(ce===$)continue;const Y=e[$];(te===Y||Ce&&(typeof Y=="object"&&Y!==null)&&Aa(te,Y))&&(ae.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${i}/uniqueItems`,error:`Duplicate items at indexes ${ce} and ${$}.`}),ce=Number.MAX_SAFE_INTEGER,$=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(r==="4"?(W!==void 0&&(F===!0&&e<=W||e<W)&&ae.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${F?"or equal to ":""} ${W}.`}),A!==void 0&&(J===!0&&e>=A||e>A)&&ae.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${J?"or equal to ":""} ${A}.`})):(W!==void 0&&e<W&&ae.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${i}/minimum`,error:`${e} is less than ${W}.`}),A!==void 0&&e>A&&ae.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${i}/maximum`,error:`${e} is greater than ${A}.`}),F!==void 0&&e<=F&&ae.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${i}/exclusiveMinimum`,error:`${e} is less than ${F}.`}),J!==void 0&&e>=J&&ae.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${i}/exclusiveMaximum`,error:`${e} is greater than or equal to ${J}.`})),Q!==void 0){const _e=e%Q;Math.abs(0-_e)>=11920929e-14&&Math.abs(Q-_e)>=11920929e-14&&ae.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${i}/multipleOf`,error:`${e} is not a multiple of ${Q}.`})}}else if(u==="string"){const _e=he===void 0&&Pe===void 0?0:lN(e);he!==void 0&&_e<he&&ae.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${i}/minLength`,error:`String is too short (${_e} < ${he}).`}),Pe!==void 0&&_e>Pe&&ae.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${i}/maxLength`,error:`String is too long (${_e} > ${Pe}).`}),Ke!==void 0&&!new RegExp(Ke,"u").test(e)&&ae.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${i}/pattern`,error:"String does not match pattern."}),C!==void 0&&Uw[C]&&!Uw[C](e)&&ae.push({instanceLocation:a,keyword:"format",keywordLocation:`${i}/format`,error:`String does not match format "${C}".`})}return{valid:ae.length===0,errors:ae}}class cN{schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=Co(t)}validate(t){return bt(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),Co(t,this.lookup)}}const Fw="Failed to parse input arguments",ac="Tool was executed but the invocation failed. For example, the script function threw an error",Wp="Tool was cancelled",ic={type:"object",properties:{}},uN=["draft-2020-12","draft-07"],dN="__isWebMCPPolyfill",Vw=Symbol("standardValidator"),nn={installed:!1,previousModelContextDescriptor:void 0,previousModelContextTestingDescriptor:void 0};var pN=class{tools=new Map;toolsChangedCallback=null;provideContextDeprecationWarned=!1;clearContextDeprecationWarned=!1;provideContext(e={}){this.warnProvideContextDeprecationOnce();const t=new Map;for(const r of e.tools??[]){const n=Jw(r,t);t.set(n.name,n)}this.tools=t,this.notifyToolsChanged()}clearContext(){this.warnClearContextDeprecationOnce(),this.tools.clear(),this.notifyToolsChanged()}registerTool(e){const t=Jw(e,this.tools);this.tools.set(t.name,t),this.notifyToolsChanged()}unregisterTool(e){const t=hN(e);this.tools.delete(t)&&this.notifyToolsChanged()}getTestingShim(){return{listTools:()=>[...this.tools.values()].map(e=>{const t={name:e.name,description:e.description};try{t.inputSchema=JSON.stringify(e.inputSchema)}catch{}return t}),executeTool:(e,t,r)=>this.executeToolForTesting(e,t,r),registerToolsChangedCallback:e=>{if(typeof e!="function")throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");this.toolsChangedCallback=e},getCrossDocumentScriptToolResult:async()=>"[]"}}async executeToolForTesting(e,t,r){if(r?.signal?.aborted)throw on(Wp);const n=this.tools.get(e);if(!n)throw on(`Tool not found: ${e}`);const o=fN(t),s=await bN(o,n);if(s)throw on(s);let a=!0;const i={requestUserInteraction:async l=>{if(!a)throw new Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof l!="function")throw new TypeError("requestUserInteraction(callback) requires a function callback");return l()}};try{const l=n.execute(o,i);return $N(xN(await EN(Promise.resolve(l),r?.signal)))}catch(l){throw on(l instanceof Error?`${ac}: ${l.message}`:ac)}finally{a=!1}}notifyToolsChanged(){this.toolsChangedCallback&&queueMicrotask(()=>{try{this.toolsChangedCallback?.()}catch(e){console.warn("[WebMCPPolyfill] toolsChanged callback threw:",e)}})}warnProvideContextDeprecationOnce(){this.provideContextDeprecationWarned||(this.provideContextDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.provideContext() is deprecated and will be removed in the next major version. Register tools individually with registerTool() instead."))}warnClearContextDeprecationOnce(){this.clearContextDeprecationWarned||(this.clearContextDeprecationWarned=!0,console.warn("[WebMCPPolyfill] navigator.modelContext.clearContext() is deprecated and will be removed in the next major version. Unregister individual tools instead."))}};function on(e){try{return new DOMException(e,"UnknownError")}catch{const t=new Error(e);return t.name="UnknownError",t}}function fN(e){let t;try{t=JSON.parse(e)}catch{throw on(Fw)}if(!t||typeof t!="object"||Array.isArray(t))throw on(Fw);return t}function hN(e){if(typeof e=="string")return e;if(zt(e)&&typeof e.name=="string")return e.name;throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.")}function zt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Hw(e){if(!zt(e))return null;const t=e["~standard"];return zt(t)?t:null}function mN(e){const t=Hw(e);return!!(t&&t.version===1&&typeof t.validate=="function")}function gN(e){const t=Hw(e);return!t||t.version!==1||!zt(t.jsonSchema)?!1:typeof t.jsonSchema.input=="function"}function lc(e){return{"~standard":{version:1,vendor:"@mcp-b/webmcp-polyfill-json-schema",validate(t){if(!zt(t))return{issues:[{message:"expected object arguments"}]};const r=Ww(t,e);return r?{issues:[r]}:{value:t}}}}}function yN(e){for(const t of uN)try{const r=e["~standard"].jsonSchema.input({target:t});return Bw(r),r}catch(r){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,r)}throw new Error("Failed to convert Standard JSON Schema inputSchema to a JSON Schema object")}function vN(e){if(e===void 0){const r=ic;return{inputSchema:r,standardValidator:lc(r)}}if(gN(e)){const r=yN(e);return{inputSchema:r,standardValidator:lc(r)}}if(mN(e))return{inputSchema:ic,standardValidator:e};if(Bw(e),Object.keys(e).length===0)return{inputSchema:ic,standardValidator:lc(ic)};const t=e.type===void 0?{type:"object",...e}:e;return{inputSchema:t,standardValidator:lc(t)}}function Bw(e){if(!zt(e))throw new Error("inputSchema must be a JSON Schema object");us(e,"$")}function us(e,t){const r=e.type;if(r!==void 0&&typeof r!="string"&&!(Array.isArray(r)&&r.every(i=>typeof i=="string"&&i.length>0)))throw new Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);const n=e.required;if(n!==void 0&&!(Array.isArray(n)&&n.every(i=>typeof i=="string")))throw new Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);const o=e.properties;if(o!==void 0){if(!zt(o))throw new Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(const[i,l]of Object.entries(o)){if(!zt(l))throw new Error(`Invalid JSON Schema at ${t}.properties.${i}: expected object schema`);us(l,`${t}.properties.${i}`)}}const s=e.items;if(s!==void 0)if(Array.isArray(s))for(const[i,l]of s.entries()){if(!zt(l))throw new Error(`Invalid JSON Schema at ${t}.items[${i}]: expected object schema`);us(l,`${t}.items[${i}]`)}else if(zt(s))us(s,`${t}.items`);else throw new Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(const i of["allOf","anyOf","oneOf"]){const l=e[i];if(l!==void 0){if(!Array.isArray(l))throw new Error(`Invalid JSON Schema at ${t}: "${i}" must be an array`);for(const[c,u]of l.entries()){if(!zt(u))throw new Error(`Invalid JSON Schema at ${t}.${i}[${c}]: expected object schema`);us(u,`${t}.${i}[${c}]`)}}}const a=e.not;if(a!==void 0){if(!zt(a))throw new Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);us(a,`${t}.not`)}try{JSON.stringify(e)}catch{throw new Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function Jw(e,t){if(!e||typeof e!="object")throw new TypeError("registerTool(tool) requires a tool object");if(typeof e.name!="string"||e.name.length===0)throw new TypeError('Tool "name" must be a non-empty string');if(typeof e.description!="string"||e.description.length===0)throw new TypeError('Tool "description" must be a non-empty string');if(typeof e.execute!="function")throw new TypeError('Tool "execute" must be a function');if(t.has(e.name))throw new Error(`Tool already registered: ${e.name}`);const r=vN(e.inputSchema),n=e.annotations,o=n?{...n,...n.readOnlyHint==="true"?{readOnlyHint:!0}:n.readOnlyHint==="false"?{readOnlyHint:!1}:{},...n.destructiveHint==="true"?{destructiveHint:!0}:n.destructiveHint==="false"?{destructiveHint:!1}:{},...n.idempotentHint==="true"?{idempotentHint:!0}:n.idempotentHint==="false"?{idempotentHint:!1}:{},...n.openWorldHint==="true"?{openWorldHint:!0}:n.openWorldHint==="false"?{openWorldHint:!1}:{}}:void 0;return{...e,...o?{annotations:o}:{},inputSchema:r.inputSchema,[Vw]:r.standardValidator}}function Ww(e,t){const r=new cN(t,"2020-12",!0).validate(e);if(r.valid)return null;const n=r.errors[r.errors.length-1];return n?{message:n.error}:{message:"Input validation failed"}}function _N(e){if(!e||e.length===0)return null;const t=e.map(r=>zt(r)&&"key"in r?r.key:r).map(r=>String(r)).filter(r=>r.length>0);return t.length===0?null:t.join(".")}async function wN(e,t){let r;try{r=await Promise.resolve(t["~standard"].validate(e))}catch(s){const a=s instanceof Error?`: ${s.message}`:"";return console.error("[WebMCPPolyfill] Standard Schema validation threw unexpectedly:",s),`Input validation error: schema validation failed${a}`}if(!r.issues||r.issues.length===0)return null;const n=r.issues[0];if(!n)return"Input validation error";const o=_N(n?.path);return o?`Input validation error: ${n.message} at ${o}`:`Input validation error: ${n.message}`}async function bN(e,t){return wN(e,t[Vw])}function kN(e){return zt(e)&&Array.isArray(e.content)}function TN(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Gp(e){return TN(e)?Number.isFinite(e)||typeof e!="number":Array.isArray(e)?e.every(t=>Gp(t)):zt(e)?Object.values(e).every(t=>Gp(t)):!1}function SN(e){if(!(!zt(e)||!Gp(e)))return e}function CN(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function xN(e){if(kN(e))return e;const t=SN(e);return{content:[{type:"text",text:CN(e)}],...t?{structuredContent:t}:{},isError:!1}}function IN(e){for(const t of e.content??[])if(t.type==="text"&&"text"in t&&typeof t.text=="string")return t.text;return null}function $N(e){if(e.isError)throw on(IN(e)?.replace(/^Error:\s*/i,"").trim()||ac);const t=e.metadata;if(t&&typeof t=="object"&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw on(ac)}}function EN(e,t){return t?t.aborted?Promise.reject(on(Wp)):new Promise((r,n)=>{const o=()=>{s(),n(on(Wp))},s=()=>{t.removeEventListener("abort",o)};t.addEventListener("abort",o,{once:!0}),e.then(a=>{s(),r(a)},a=>{s(),n(a)})}):e}function Gw(){return typeof navigator<"u"?navigator:null}function Kw(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:r})}function cc(e){const t=Gw();if(!t||t.modelContext)return;nn.installed&&Yw();const r=new pN,n=r;n[dN]=!0,nn.previousModelContextDescriptor=Object.getOwnPropertyDescriptor(t,"modelContext"),nn.previousModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,"modelContextTesting"),Kw(t,"modelContext",n);const o=e?.installTestingShim??"if-missing",s=!!t.modelContextTesting;(o==="always"||(o===!0||o==="if-missing")&&!s)&&Kw(t,"modelContextTesting",r.getTestingShim()),nn.installed=!0}function Yw(){const e=Gw();if(!e||!nn.installed)return;const t=(r,n)=>{if(n){Object.defineProperty(e,r,n);return}delete e[r]};t("modelContext",nn.previousModelContextDescriptor),t("modelContextTesting",nn.previousModelContextTestingDescriptor),nn.installed=!1,nn.previousModelContextDescriptor=void 0,nn.previousModelContextTestingDescriptor=void 0}if(typeof window<"u"&&typeof document<"u"){const e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{cc(e)}catch(t){console.error("[WebMCPPolyfill] Auto-initialization failed:",t)}}const RN=()=>{if(zn())try{cc(),qw()}catch(e){console.warn("[next-sdk] 自动注入 modelContext polyfill 和桥接同步失败:",e)}};Ee.AgentModelProvider=dO,Ee.Ajv=$h,Ee.AuthClientProvider=dI,Ee.ContentScriptServerTransport=UI,Ee.ExtensionClientTransport=y2,Ee.ExtensionPageServerTransport=DI,Ee.InMemoryTransport=ca,Ee.MSG_REMOTER_READY=Ow,Ee.MSG_TOOL_REGISTERED=To,Ee.MSG_TOOL_UNREGISTERED=oc,Ee.QrCode=Y2,Ee.ResourceTemplate=bI,Ee.UriTemplate=vn,Ee.WebMcpClient=h2,Ee.WebMcpServer=xI,Ee.cleanupWebMCPPolyfill=Yw,Ee.completable=hI,Ee.createMessageChannelClientTransport=NI,Ee.createMessageChannelPairTransport=$I,Ee.createMessageChannelServerTransport=II,Ee.createRemoter=y6,Ee.createSSEClientTransport=MI,Ee.createSkillTools=OO,Ee.createStreamableHTTPClientTransport=OI,Ee.formatSkillsForSystemPrompt=RO,Ee.getAISDKTools=$w,Ee.getDisplayName=CI,Ee.getMainSkillPathByName=Dw,Ee.getMainSkillPaths=Lw,Ee.getSkillMdContent=sc,Ee.getSkillMdPaths=PO,Ee.getSkillOverviews=EO,Ee.initializeBuiltinWebMCP=RN,Ee.initializeWebMCPPolyfill=cc,Ee.initializeWebModelContextPolyfill=cc,Ee.isMcpClient=jI,Ee.isMcpServer=RI,Ee.isMessageChannelClientTransport=qI,Ee.isMessageChannelServerTransport=EI,Ee.isPlainObject=zt,Ee.isSSEClientTransport=AI,Ee.isStreamableHTTPClientTransport=m2,Ee.parseSkillFrontMatter=Jp,Ee.registerNavigateTool=CO,Ee.registerPageTool=IO,Ee.setNavigator=kO,Ee.setupModelContextBridge=qw,Ee.validateArgsWithSchema=Ww,Ee.withPageTools=xO,Ee.z=X3,Object.defineProperty(Ee,Symbol.toStringTag,{value:"Module"})}));