@opentiny/next-sdk 0.1.12 → 0.1.14

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,26 +1,26 @@
1
- (function(Ve,os){typeof exports=="object"&&typeof module<"u"?os(exports):typeof define=="function"&&define.amd?define(["exports"],os):(Ve=typeof globalThis<"u"?globalThis:Ve||self,os(Ve.WebMCP={}))})(this,function(Ve){"use strict";var os=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Pp(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Al={exports:{}},kp={},kr={},ya={},is={},Me={},ls={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(_){if(super(),!t.IDENTIFIER.test(_))throw new Error("CodeGen: name must be a valid identifier");this.str=_}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class a extends e{constructor(_){super(),this._items=typeof _=="string"?[_]:_}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const _=this._items[0];return _===""||_==='""'}get str(){var _;return(_=this._str)!==null&&_!==void 0?_:this._str=this._items.reduce((w,b)=>`${w}${b}`,"")}get names(){var _;return(_=this._names)!==null&&_!==void 0?_:this._names=this._items.reduce((w,b)=>(b instanceof r&&(w[b.str]=(w[b.str]||0)+1),w),{})}}t._Code=a,t.nil=new a("");function n(p,..._){const w=[p[0]];let b=0;for(;b<_.length;)i(w,_[b]),w.push(p[++b]);return new a(w)}t._=n;const s=new a("+");function o(p,..._){const w=[d(p[0])];let b=0;for(;b<_.length;)w.push(s),i(w,_[b]),w.push(s,d(p[++b]));return l(w),new a(w)}t.str=o;function i(p,_){_ instanceof a?p.push(..._._items):_ instanceof r?p.push(_):p.push(f(_))}t.addCodeArg=i;function l(p){let _=1;for(;_<p.length-1;){if(p[_]===s){const w=c(p[_-1],p[_+1]);if(w!==void 0){p.splice(_-1,3,w);continue}p[_++]="+"}_++}}function c(p,_){if(_==='""')return p;if(p==='""')return _;if(typeof p=="string")return _ instanceof r||p[p.length-1]!=='"'?void 0:typeof _!="string"?`${p.slice(0,-1)}${_}"`:_[0]==='"'?p.slice(0,-1)+_.slice(1):void 0;if(typeof _=="string"&&_[0]==='"'&&!(p instanceof r))return`"${p}${_.slice(1)}`}function u(p,_){return _.emptyStr()?p:p.emptyStr()?_:o`${p}${_}`}t.strConcat=u;function f(p){return typeof p=="number"||typeof p=="boolean"||p===null?p:d(Array.isArray(p)?p.join(","):p)}function g(p){return new a(d(p))}t.stringify=g;function d(p){return JSON.stringify(p).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=d;function h(p){return typeof p=="string"&&t.IDENTIFIER.test(p)?new a(`.${p}`):n`[${p}]`}t.getProperty=h;function v(p){if(typeof p=="string"&&t.IDENTIFIER.test(p))return new a(`${p}`);throw new Error(`CodeGen: invalid export name: ${p}, use explicit $id name mapping`)}t.getEsmExportName=v;function m(p){return new a(p.toString())}t.regexpCode=m})(ls);var Ml={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=ls;class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var a;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(a||(t.UsedValueState=a={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class n{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof e.Name?c:this.name(c)}name(c){return new e.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,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}}}t.Scope=n;class s extends e.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:f}){this.value=c,this.scopePath=(0,e._)`.${new e.Name(u)}[${f}]`}}t.ValueScopeName=s;const o=(0,e._)`\n`;class i extends n{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?o:e.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 g=this.toName(c),{prefix:d}=g,h=(f=u.key)!==null&&f!==void 0?f:u.ref;let v=this._values[d];if(v){const _=v.get(h);if(_)return _}else v=this._values[d]=new Map;v.set(h,g);const m=this._scope[d]||(this._scope[d]=[]),p=m.length;return m[p]=u.ref,g.setValue(u,{property:d,itemIndex:p}),g}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,e._)`${c}${f.scopePath}`})}scopeCode(c=this._values,u,f){return this._reduceValues(c,g=>{if(g.value===void 0)throw new Error(`CodeGen: name "${g}" has no value`);return g.value.code},u,f)}_reduceValues(c,u,f={},g){let d=e.nil;for(const h in c){const v=c[h];if(!v)continue;const m=f[h]=f[h]||new Map;v.forEach(p=>{if(m.has(p))return;m.set(p,a.Started);let _=u(p);if(_){const w=this.opts.es5?t.varKinds.var:t.varKinds.const;d=(0,e._)`${d}${w} ${p} = ${_};${this.opts._n}`}else if(_=g==null?void 0:g(p))d=(0,e._)`${d}${_}${this.opts._n}`;else throw new r(p);m.set(p,a.Completed)})}return d}}t.ValueScope=i})(Ml),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=ls,r=Ml;var a=ls;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return a._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return a.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return a.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return a.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return a.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return a.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return a.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return a.Name}});var n=Ml;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(y,P){return this}}class o extends s{constructor(y,P,j){super(),this.varKind=y,this.name=P,this.rhs=j}render({es5:y,_n:P}){const j=y?r.varKinds.var:this.varKind,Q=this.rhs===void 0?"":` = ${this.rhs}`;return`${j} ${this.name}${Q};`+P}optimizeNames(y,P){if(y[this.name.str])return this.rhs&&(this.rhs=U(this.rhs,y,P)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(y,P,j){super(),this.lhs=y,this.rhs=P,this.sideEffects=j}render({_n:y}){return`${this.lhs} = ${this.rhs};`+y}optimizeNames(y,P){if(!(this.lhs instanceof e.Name&&!y[this.lhs.str]&&!this.sideEffects))return this.rhs=U(this.rhs,y,P),this}get names(){const y=this.lhs instanceof e.Name?{}:{...this.lhs.names};return z(y,this.rhs)}}class l extends i{constructor(y,P,j,Q){super(y,j,Q),this.op=P}render({_n:y}){return`${this.lhs} ${this.op}= ${this.rhs};`+y}}class c extends s{constructor(y){super(),this.label=y,this.names={}}render({_n:y}){return`${this.label}:`+y}}class u extends s{constructor(y){super(),this.label=y,this.names={}}render({_n:y}){return`break${this.label?` ${this.label}`:""};`+y}}class f extends s{constructor(y){super(),this.error=y}render({_n:y}){return`throw ${this.error};`+y}get names(){return this.error.names}}class g extends s{constructor(y){super(),this.code=y}render({_n:y}){return`${this.code};`+y}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(y,P){return this.code=U(this.code,y,P),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class d extends s{constructor(y=[]){super(),this.nodes=y}render(y){return this.nodes.reduce((P,j)=>P+j.render(y),"")}optimizeNodes(){const{nodes:y}=this;let P=y.length;for(;P--;){const j=y[P].optimizeNodes();Array.isArray(j)?y.splice(P,1,...j):j?y[P]=j:y.splice(P,1)}return y.length>0?this:void 0}optimizeNames(y,P){const{nodes:j}=this;let Q=j.length;for(;Q--;){const ee=j[Q];ee.optimizeNames(y,P)||(G(y,ee.names),j.splice(Q,1))}return j.length>0?this:void 0}get names(){return this.nodes.reduce((y,P)=>K(y,P.names),{})}}class h extends d{render(y){return"{"+y._n+super.render(y)+"}"+y._n}}class v extends d{}class m extends h{}m.kind="else";class p extends h{constructor(y,P){super(P),this.condition=y}render(y){let P=`if(${this.condition})`+super.render(y);return this.else&&(P+="else "+this.else.render(y)),P}optimizeNodes(){super.optimizeNodes();const y=this.condition;if(y===!0)return this.nodes;let P=this.else;if(P){const j=P.optimizeNodes();P=this.else=Array.isArray(j)?new m(j):j}if(P)return y===!1?P instanceof p?P:P.nodes:this.nodes.length?this:new p(se(y),P instanceof p?[P]:P.nodes);if(!(y===!1||!this.nodes.length))return this}optimizeNames(y,P){var j;if(this.else=(j=this.else)===null||j===void 0?void 0:j.optimizeNames(y,P),!!(super.optimizeNames(y,P)||this.else))return this.condition=U(this.condition,y,P),this}get names(){const y=super.names;return z(y,this.condition),this.else&&K(y,this.else.names),y}}p.kind="if";class _ extends h{}_.kind="for";class w extends _{constructor(y){super(),this.iteration=y}render(y){return`for(${this.iteration})`+super.render(y)}optimizeNames(y,P){if(super.optimizeNames(y,P))return this.iteration=U(this.iteration,y,P),this}get names(){return K(super.names,this.iteration.names)}}class b extends _{constructor(y,P,j,Q){super(),this.varKind=y,this.name=P,this.from=j,this.to=Q}render(y){const P=y.es5?r.varKinds.var:this.varKind,{name:j,from:Q,to:ee}=this;return`for(${P} ${j}=${Q}; ${j}<${ee}; ${j}++)`+super.render(y)}get names(){const y=z(super.names,this.from);return z(y,this.to)}}class S extends _{constructor(y,P,j,Q){super(),this.loop=y,this.varKind=P,this.name=j,this.iterable=Q}render(y){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(y)}optimizeNames(y,P){if(super.optimizeNames(y,P))return this.iterable=U(this.iterable,y,P),this}get names(){return K(super.names,this.iterable.names)}}class I extends h{constructor(y,P,j){super(),this.name=y,this.args=P,this.async=j}render(y){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(y)}}I.kind="func";class k extends d{render(y){return"return "+super.render(y)}}k.kind="return";class A extends h{render(y){let P="try"+super.render(y);return this.catch&&(P+=this.catch.render(y)),this.finally&&(P+=this.finally.render(y)),P}optimizeNodes(){var y,P;return super.optimizeNodes(),(y=this.catch)===null||y===void 0||y.optimizeNodes(),(P=this.finally)===null||P===void 0||P.optimizeNodes(),this}optimizeNames(y,P){var j,Q;return super.optimizeNames(y,P),(j=this.catch)===null||j===void 0||j.optimizeNames(y,P),(Q=this.finally)===null||Q===void 0||Q.optimizeNames(y,P),this}get names(){const y=super.names;return this.catch&&K(y,this.catch.names),this.finally&&K(y,this.finally.names),y}}class O extends h{constructor(y){super(),this.error=y}render(y){return`catch(${this.error})`+super.render(y)}}O.kind="catch";class H extends h{render(y){return"finally"+super.render(y)}}H.kind="finally";class J{constructor(y,P={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...P,_n:P.lines?`
2
- `:""},this._extScope=y,this._scope=new r.Scope({parent:y}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(y){return this._scope.name(y)}scopeName(y){return this._extScope.name(y)}scopeValue(y,P){const j=this._extScope.value(y,P);return(this._values[j.prefix]||(this._values[j.prefix]=new Set)).add(j),j}getScopeValue(y,P){return this._extScope.getValue(y,P)}scopeRefs(y){return this._extScope.scopeRefs(y,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(y,P,j,Q){const ee=this._scope.toName(P);return j!==void 0&&Q&&(this._constants[ee.str]=j),this._leafNode(new o(y,ee,j)),ee}const(y,P,j){return this._def(r.varKinds.const,y,P,j)}let(y,P,j){return this._def(r.varKinds.let,y,P,j)}var(y,P,j){return this._def(r.varKinds.var,y,P,j)}assign(y,P,j){return this._leafNode(new i(y,P,j))}add(y,P){return this._leafNode(new l(y,t.operators.ADD,P))}code(y){return typeof y=="function"?y():y!==e.nil&&this._leafNode(new g(y)),this}object(...y){const P=["{"];for(const[j,Q]of y)P.length>1&&P.push(","),P.push(j),(j!==Q||this.opts.es5)&&(P.push(":"),(0,e.addCodeArg)(P,Q));return P.push("}"),new e._Code(P)}if(y,P,j){if(this._blockNode(new p(y)),P&&j)this.code(P).else().code(j).endIf();else if(P)this.code(P).endIf();else if(j)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(y){return this._elseNode(new p(y))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(p,m)}_for(y,P){return this._blockNode(y),P&&this.code(P).endFor(),this}for(y,P){return this._for(new w(y),P)}forRange(y,P,j,Q,ee=this.opts.es5?r.varKinds.var:r.varKinds.let){const Se=this._scope.toName(y);return this._for(new b(ee,Se,P,j),()=>Q(Se))}forOf(y,P,j,Q=r.varKinds.const){const ee=this._scope.toName(y);if(this.opts.es5){const Se=P instanceof e.Name?P:this.var("_arr",P);return this.forRange("_i",0,(0,e._)`${Se}.length`,de=>{this.var(ee,(0,e._)`${Se}[${de}]`),j(ee)})}return this._for(new S("of",Q,ee,P),()=>j(ee))}forIn(y,P,j,Q=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(y,(0,e._)`Object.keys(${P})`,j);const ee=this._scope.toName(y);return this._for(new S("in",Q,ee,P),()=>j(ee))}endFor(){return this._endBlockNode(_)}label(y){return this._leafNode(new c(y))}break(y){return this._leafNode(new u(y))}return(y){const P=new k;if(this._blockNode(P),this.code(y),P.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(k)}try(y,P,j){if(!P&&!j)throw new Error('CodeGen: "try" without "catch" and "finally"');const Q=new A;if(this._blockNode(Q),this.code(y),P){const ee=this.name("e");this._currNode=Q.catch=new O(ee),P(ee)}return j&&(this._currNode=Q.finally=new H,this.code(j)),this._endBlockNode(O,H)}throw(y){return this._leafNode(new f(y))}block(y,P){return this._blockStarts.push(this._nodes.length),y&&this.code(y).endBlock(P),this}endBlock(y){const P=this._blockStarts.pop();if(P===void 0)throw new Error("CodeGen: not in self-balancing block");const j=this._nodes.length-P;if(j<0||y!==void 0&&j!==y)throw new Error(`CodeGen: wrong number of nodes: ${j} vs ${y} expected`);return this._nodes.length=P,this}func(y,P=e.nil,j,Q){return this._blockNode(new I(y,P,j)),Q&&this.code(Q).endFunc(),this}endFunc(){return this._endBlockNode(I)}optimize(y=1){for(;y-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(y){return this._currNode.nodes.push(y),this}_blockNode(y){this._currNode.nodes.push(y),this._nodes.push(y)}_endBlockNode(y,P){const j=this._currNode;if(j instanceof y||P&&j instanceof P)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${P?`${y.kind}/${P.kind}`:y.kind}"`)}_elseNode(y){const P=this._currNode;if(!(P instanceof p))throw new Error('CodeGen: "else" without "if"');return this._currNode=P.else=y,this}get _root(){return this._nodes[0]}get _currNode(){const y=this._nodes;return y[y.length-1]}set _currNode(y){const P=this._nodes;P[P.length-1]=y}}t.CodeGen=J;function K(N,y){for(const P in y)N[P]=(N[P]||0)+(y[P]||0);return N}function z(N,y){return y instanceof e._CodeOrName?K(N,y.names):N}function U(N,y,P){if(N instanceof e.Name)return j(N);if(!Q(N))return N;return new e._Code(N._items.reduce((ee,Se)=>(Se instanceof e.Name&&(Se=j(Se)),Se instanceof e._Code?ee.push(...Se._items):ee.push(Se),ee),[]));function j(ee){const Se=P[ee.str];return Se===void 0||y[ee.str]!==1?ee:(delete y[ee.str],Se)}function Q(ee){return ee instanceof e._Code&&ee._items.some(Se=>Se instanceof e.Name&&y[Se.str]===1&&P[Se.str]!==void 0)}}function G(N,y){for(const P in y)N[P]=(N[P]||0)-(y[P]||0)}function se(N){return typeof N=="boolean"||typeof N=="number"||N===null?!N:(0,e._)`!${D(N)}`}t.not=se;const ne=R(t.operators.AND);function ce(...N){return N.reduce(ne)}t.and=ce;const pe=R(t.operators.OR);function M(...N){return N.reduce(pe)}t.or=M;function R(N){return(y,P)=>y===e.nil?P:P===e.nil?y:(0,e._)`${D(y)} ${N} ${D(P)}`}function D(N){return N instanceof e.Name?N:(0,e._)`(${N})`}}(Me);var ie={};Object.defineProperty(ie,"__esModule",{value:!0}),ie.checkStrictMode=ie.getErrorPath=ie.Type=ie.useFunc=ie.setEvaluated=ie.evaluatedPropsToName=ie.mergeEvaluated=ie.eachItem=ie.unescapeJsonPointer=ie.escapeJsonPointer=ie.escapeFragment=ie.unescapeFragment=ie.schemaRefOrVal=ie.schemaHasRulesButRef=ie.schemaHasRules=ie.checkUnknownRules=ie.alwaysValidSchema=ie.toHash=void 0;const Ye=Me,cw=ls;function uw(t){const e={};for(const r of t)e[r]=!0;return e}ie.toHash=uw;function dw(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Ip(t,e),!xp(e,t.self.RULES.all))}ie.alwaysValidSchema=dw;function Ip(t,e=t.schema){const{opts:r,self:a}=t;if(!r.strictSchema||typeof e=="boolean")return;const n=a.RULES.keywords;for(const s in e)n[s]||Np(t,`unknown keyword: "${s}"`)}ie.checkUnknownRules=Ip;function xp(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(e[r])return!0;return!1}ie.schemaHasRules=xp;function pw(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ie.schemaHasRulesButRef=pw;function fw({topSchemaRef:t,schemaPath:e},r,a,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ye._)`${r}`}return(0,Ye._)`${t}${e}${(0,Ye.getProperty)(a)}`}ie.schemaRefOrVal=fw;function hw(t){return Tp(decodeURIComponent(t))}ie.unescapeFragment=hw;function mw(t){return encodeURIComponent(jl(t))}ie.escapeFragment=mw;function jl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ie.escapeJsonPointer=jl;function Tp(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ie.unescapeJsonPointer=Tp;function vw(t,e){if(Array.isArray(t))for(const r of t)e(r);else e(t)}ie.eachItem=vw;function Cp({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:a}){return(n,s,o,i)=>{const l=o===void 0?s:o instanceof Ye.Name?(s instanceof Ye.Name?t(n,s,o):e(n,s,o),o):s instanceof Ye.Name?(e(n,o,s),s):r(s,o);return i===Ye.Name&&!(l instanceof Ye.Name)?a(n,l):l}}ie.mergeEvaluated={props:Cp({mergeNames:(t,e,r)=>t.if((0,Ye._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ye._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ye._)`${r} || {}`).code((0,Ye._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ye._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ye._)`${r} || {}`),Dl(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Rp}),items:Cp({mergeNames:(t,e,r)=>t.if((0,Ye._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ye._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ye._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ye._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Rp(t,e){if(e===!0)return t.var("props",!0);const r=t.var("props",(0,Ye._)`{}`);return e!==void 0&&Dl(t,r,e),r}ie.evaluatedPropsToName=Rp;function Dl(t,e,r){Object.keys(r).forEach(a=>t.assign((0,Ye._)`${e}${(0,Ye.getProperty)(a)}`,!0))}ie.setEvaluated=Dl;const Op={};function gw(t,e){return t.scopeValue("func",{ref:e,code:Op[e.code]||(Op[e.code]=new cw._Code(e.code))})}ie.useFunc=gw;var Ll;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ll||(ie.Type=Ll={}));function yw(t,e,r){if(t instanceof Ye.Name){const a=e===Ll.Num;return r?a?(0,Ye._)`"[" + ${t} + "]"`:(0,Ye._)`"['" + ${t} + "']"`:a?(0,Ye._)`"/" + ${t}`:(0,Ye._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ye.getProperty)(t).toString():"/"+jl(t)}ie.getErrorPath=yw;function Np(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ie.checkStrictMode=Np;var Zr={};Object.defineProperty(Zr,"__esModule",{value:!0});const Ft=Me,_w={data:new Ft.Name("data"),valCxt:new Ft.Name("valCxt"),instancePath:new Ft.Name("instancePath"),parentData:new Ft.Name("parentData"),parentDataProperty:new Ft.Name("parentDataProperty"),rootData:new Ft.Name("rootData"),dynamicAnchors:new Ft.Name("dynamicAnchors"),vErrors:new Ft.Name("vErrors"),errors:new Ft.Name("errors"),this:new Ft.Name("this"),self:new Ft.Name("self"),scope:new Ft.Name("scope"),json:new Ft.Name("json"),jsonPos:new Ft.Name("jsonPos"),jsonLen:new Ft.Name("jsonLen"),jsonPart:new Ft.Name("jsonPart")};Zr.default=_w,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=Me,r=ie,a=Zr;t.keywordError={message:({keyword:m})=>(0,e.str)`must pass "${m}" keyword validation`},t.keyword$DataError={message:({keyword:m,schemaType:p})=>p?(0,e.str)`"${m}" keyword must be ${p} ($data)`:(0,e.str)`"${m}" keyword is invalid ($data)`};function n(m,p=t.keywordError,_,w){const{it:b}=m,{gen:S,compositeRule:I,allErrors:k}=b,A=f(m,p,_);w??(I||k)?l(S,A):c(b,(0,e._)`[${A}]`)}t.reportError=n;function s(m,p=t.keywordError,_){const{it:w}=m,{gen:b,compositeRule:S,allErrors:I}=w,k=f(m,p,_);l(b,k),S||I||c(w,a.default.vErrors)}t.reportExtraError=s;function o(m,p){m.assign(a.default.errors,p),m.if((0,e._)`${a.default.vErrors} !== null`,()=>m.if(p,()=>m.assign((0,e._)`${a.default.vErrors}.length`,p),()=>m.assign(a.default.vErrors,null)))}t.resetErrorsCount=o;function i({gen:m,keyword:p,schemaValue:_,data:w,errsCount:b,it:S}){if(b===void 0)throw new Error("ajv implementation error");const I=m.name("err");m.forRange("i",b,a.default.errors,k=>{m.const(I,(0,e._)`${a.default.vErrors}[${k}]`),m.if((0,e._)`${I}.instancePath === undefined`,()=>m.assign((0,e._)`${I}.instancePath`,(0,e.strConcat)(a.default.instancePath,S.errorPath))),m.assign((0,e._)`${I}.schemaPath`,(0,e.str)`${S.errSchemaPath}/${p}`),S.opts.verbose&&(m.assign((0,e._)`${I}.schema`,_),m.assign((0,e._)`${I}.data`,w))})}t.extendErrors=i;function l(m,p){const _=m.const("err",p);m.if((0,e._)`${a.default.vErrors} === null`,()=>m.assign(a.default.vErrors,(0,e._)`[${_}]`),(0,e._)`${a.default.vErrors}.push(${_})`),m.code((0,e._)`${a.default.errors}++`)}function c(m,p){const{gen:_,validateName:w,schemaEnv:b}=m;b.$async?_.throw((0,e._)`new ${m.ValidationError}(${p})`):(_.assign((0,e._)`${w}.errors`,p),_.return(!1))}const u={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function f(m,p,_){const{createErrors:w}=m.it;return w===!1?(0,e._)`{}`:g(m,p,_)}function g(m,p,_={}){const{gen:w,it:b}=m,S=[d(b,_),h(m,_)];return v(m,p,S),w.object(...S)}function d({errorPath:m},{instancePath:p}){const _=p?(0,e.str)`${m}${(0,r.getErrorPath)(p,r.Type.Str)}`:m;return[a.default.instancePath,(0,e.strConcat)(a.default.instancePath,_)]}function h({keyword:m,it:{errSchemaPath:p}},{schemaPath:_,parentSchema:w}){let b=w?p:(0,e.str)`${p}/${m}`;return _&&(b=(0,e.str)`${b}${(0,r.getErrorPath)(_,r.Type.Str)}`),[u.schemaPath,b]}function v(m,{params:p,message:_},w){const{keyword:b,data:S,schemaValue:I,it:k}=m,{opts:A,propertyName:O,topSchemaRef:H,schemaPath:J}=k;w.push([u.keyword,b],[u.params,typeof p=="function"?p(m):p||(0,e._)`{}`]),A.messages&&w.push([u.message,typeof _=="function"?_(m):_]),A.verbose&&w.push([u.schema,I],[u.parentSchema,(0,e._)`${H}${J}`],[a.default.data,S]),O&&w.push([u.propertyName,O])}}(is),Object.defineProperty(ya,"__esModule",{value:!0}),ya.boolOrEmptySchema=ya.topBoolOrEmptySchema=void 0;const ww=is,bw=Me,Ew=Zr,Sw={message:"boolean schema is false"};function $w(t){const{gen:e,schema:r,validateName:a}=t;r===!1?Ap(t,!1):typeof r=="object"&&r.$async===!0?e.return(Ew.default.data):(e.assign((0,bw._)`${a}.errors`,null),e.return(!0))}ya.topBoolOrEmptySchema=$w;function Pw(t,e){const{gen:r,schema:a}=t;a===!1?(r.var(e,!1),Ap(t)):r.var(e,!0)}ya.boolOrEmptySchema=Pw;function Ap(t,e){const{gen:r,data:a}=t,n={gen:r,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,ww.reportError)(n,Sw,void 0,e)}var Tt={},Zn={};Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.getRules=Zn.isJSONType=void 0;const kw=["string","number","integer","boolean","null","object","array"],Iw=new Set(kw);function xw(t){return typeof t=="string"&&Iw.has(t)}Zn.isJSONType=xw;function Tw(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Zn.getRules=Tw;var dn={};Object.defineProperty(dn,"__esModule",{value:!0}),dn.shouldUseRule=dn.shouldUseGroup=dn.schemaHasRulesForType=void 0;function Cw({schema:t,self:e},r){const a=e.RULES.types[r];return a&&a!==!0&&Mp(t,a)}dn.schemaHasRulesForType=Cw;function Mp(t,e){return e.rules.some(r=>jp(t,r))}dn.shouldUseGroup=Mp;function jp(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(a=>t[a]!==void 0))}dn.shouldUseRule=jp,Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.reportTypeError=Tt.checkDataTypes=Tt.checkDataType=Tt.coerceAndCheckDataType=Tt.getJSONTypes=Tt.getSchemaTypes=Tt.DataType=void 0;const Rw=Zn,Ow=dn,Nw=is,Re=Me,Dp=ie;var _a;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(_a||(Tt.DataType=_a={}));function Aw(t){const e=Lp(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Tt.getSchemaTypes=Aw;function Lp(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(Rw.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Tt.getJSONTypes=Lp;function Mw(t,e){const{gen:r,data:a,opts:n}=t,s=jw(e,n.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,Ow.schemaHasRulesForType)(t,e[0]));if(o){const i=Ul(e,a,n.strictNumbers,_a.Wrong);r.if(i,()=>{s.length?Dw(t,e,s):ql(t)})}return o}Tt.coerceAndCheckDataType=Mw;const zp=new Set(["string","number","integer","boolean","null"]);function jw(t,e){return e?t.filter(r=>zp.has(r)||e==="array"&&r==="array"):[]}function Dw(t,e,r){const{gen:a,data:n,opts:s}=t,o=a.let("dataType",(0,Re._)`typeof ${n}`),i=a.let("coerced",(0,Re._)`undefined`);s.coerceTypes==="array"&&a.if((0,Re._)`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>a.assign(n,(0,Re._)`${n}[0]`).assign(o,(0,Re._)`typeof ${n}`).if(Ul(e,n,s.strictNumbers),()=>a.assign(i,n))),a.if((0,Re._)`${i} !== undefined`);for(const c of r)(zp.has(c)||c==="array"&&s.coerceTypes==="array")&&l(c);a.else(),ql(t),a.endIf(),a.if((0,Re._)`${i} !== undefined`,()=>{a.assign(n,i),Lw(t,i)});function l(c){switch(c){case"string":a.elseIf((0,Re._)`${o} == "number" || ${o} == "boolean"`).assign(i,(0,Re._)`"" + ${n}`).elseIf((0,Re._)`${n} === null`).assign(i,(0,Re._)`""`);return;case"number":a.elseIf((0,Re._)`${o} == "boolean" || ${n} === null
1
+ (function(Fe,es){typeof exports=="object"&&typeof module<"u"?es(exports):typeof define=="function"&&define.amd?define(["exports"],es):(Fe=typeof globalThis<"u"?globalThis:Fe||self,es(Fe.WebMCP={}))})(this,function(Fe){"use strict";var es=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Tf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Sl={exports:{}},xf={},wr={},fa={},ts={},Me={},rs={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(y){if(super(),!t.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class a extends e{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((_,w)=>`${_}${w}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((_,w)=>(w instanceof r&&(_[w.str]=(_[w.str]||0)+1),_),{})}}t._Code=a,t.nil=new a("");function n(p,...y){const _=[p[0]];let w=0;for(;w<y.length;)i(_,y[w]),_.push(p[++w]);return new a(_)}t._=n;const s=new a("+");function o(p,...y){const _=[d(p[0])];let w=0;for(;w<y.length;)_.push(s),i(_,y[w]),_.push(s,d(p[++w]));return l(_),new a(_)}t.str=o;function i(p,y){y instanceof a?p.push(...y._items):y instanceof r?p.push(y):p.push(h(y))}t.addCodeArg=i;function l(p){let y=1;for(;y<p.length-1;){if(p[y]===s){const _=c(p[y-1],p[y+1]);if(_!==void 0){p.splice(y-1,3,_);continue}p[y++]="+"}y++}}function c(p,y){if(y==='""')return p;if(p==='""')return y;if(typeof p=="string")return y instanceof r||p[p.length-1]!=='"'?void 0:typeof y!="string"?`${p.slice(0,-1)}${y}"`:y[0]==='"'?p.slice(0,-1)+y.slice(1):void 0;if(typeof y=="string"&&y[0]==='"'&&!(p instanceof r))return`"${p}${y.slice(1)}`}function u(p,y){return y.emptyStr()?p:p.emptyStr()?y:o`${p}${y}`}t.strConcat=u;function h(p){return typeof p=="number"||typeof p=="boolean"||p===null?p:d(Array.isArray(p)?p.join(","):p)}function g(p){return new a(d(p))}t.stringify=g;function d(p){return JSON.stringify(p).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=d;function f(p){return typeof p=="string"&&t.IDENTIFIER.test(p)?new a(`.${p}`):n`[${p}]`}t.getProperty=f;function v(p){if(typeof p=="string"&&t.IDENTIFIER.test(p))return new a(`${p}`);throw new Error(`CodeGen: invalid export name: ${p}, use explicit $id name mapping`)}t.getEsmExportName=v;function m(p){return new a(p.toString())}t.regexpCode=m})(rs);var Pl={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=rs;class r extends Error{constructor(c){super(`CodeGen: "code" for ${c} not defined`),this.value=c.value}}var a;(function(l){l[l.Started=0]="Started",l[l.Completed=1]="Completed"})(a||(t.UsedValueState=a={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class n{constructor({prefixes:c,parent:u}={}){this._names={},this._prefixes=c,this._parent=u}toName(c){return c instanceof e.Name?c:this.name(c)}name(c){return new e.Name(this._newName(c))}_newName(c){const u=this._names[c]||this._nameGroup(c);return`${c}${u.index++}`}_nameGroup(c){var u,h;if(!((h=(u=this._parent)===null||u===void 0?void 0:u._prefixes)===null||h===void 0)&&h.has(c)||this._prefixes&&!this._prefixes.has(c))throw new Error(`CodeGen: prefix "${c}" is not allowed in this scope`);return this._names[c]={prefix:c,index:0}}}t.Scope=n;class s extends e.Name{constructor(c,u){super(u),this.prefix=c}setValue(c,{property:u,itemIndex:h}){this.value=c,this.scopePath=(0,e._)`.${new e.Name(u)}[${h}]`}}t.ValueScopeName=s;const o=(0,e._)`\n`;class i extends n{constructor(c){super(c),this._values={},this._scope=c.scope,this.opts={...c,_n:c.lines?o:e.nil}}get(){return this._scope}name(c){return new s(c,this._newName(c))}value(c,u){var h;if(u.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const g=this.toName(c),{prefix:d}=g,f=(h=u.key)!==null&&h!==void 0?h:u.ref;let v=this._values[d];if(v){const y=v.get(f);if(y)return y}else v=this._values[d]=new Map;v.set(f,g);const m=this._scope[d]||(this._scope[d]=[]),p=m.length;return m[p]=u.ref,g.setValue(u,{property:d,itemIndex:p}),g}getValue(c,u){const h=this._values[c];if(h)return h.get(u)}scopeRefs(c,u=this._values){return this._reduceValues(u,h=>{if(h.scopePath===void 0)throw new Error(`CodeGen: name "${h}" has no value`);return(0,e._)`${c}${h.scopePath}`})}scopeCode(c=this._values,u,h){return this._reduceValues(c,g=>{if(g.value===void 0)throw new Error(`CodeGen: name "${g}" has no value`);return g.value.code},u,h)}_reduceValues(c,u,h={},g){let d=e.nil;for(const f in c){const v=c[f];if(!v)continue;const m=h[f]=h[f]||new Map;v.forEach(p=>{if(m.has(p))return;m.set(p,a.Started);let y=u(p);if(y){const _=this.opts.es5?t.varKinds.var:t.varKinds.const;d=(0,e._)`${d}${_} ${p} = ${y};${this.opts._n}`}else if(y=g==null?void 0:g(p))d=(0,e._)`${d}${y}${this.opts._n}`;else throw new r(p);m.set(p,a.Completed)})}return d}}t.ValueScope=i})(Pl),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=rs,r=Pl;var a=rs;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return a._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return a.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return a.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return a.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return a.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return a.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return a.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return a.Name}});var n=Pl;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return n.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return n.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return n.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return n.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(b,x){return this}}class o extends s{constructor(b,x,L){super(),this.varKind=b,this.name=x,this.rhs=L}render({es5:b,_n:x}){const L=b?r.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${L} ${this.name}${W};`+x}optimizeNames(b,x){if(b[this.name.str])return this.rhs&&(this.rhs=Z(this.rhs,b,x)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class i extends s{constructor(b,x,L){super(),this.lhs=b,this.rhs=x,this.sideEffects=L}render({_n:b}){return`${this.lhs} = ${this.rhs};`+b}optimizeNames(b,x){if(!(this.lhs instanceof e.Name&&!b[this.lhs.str]&&!this.sideEffects))return this.rhs=Z(this.rhs,b,x),this}get names(){const b=this.lhs instanceof e.Name?{}:{...this.lhs.names};return F(b,this.rhs)}}class l extends i{constructor(b,x,L,W){super(b,L,W),this.op=x}render({_n:b}){return`${this.lhs} ${this.op}= ${this.rhs};`+b}}class c extends s{constructor(b){super(),this.label=b,this.names={}}render({_n:b}){return`${this.label}:`+b}}class u extends s{constructor(b){super(),this.label=b,this.names={}}render({_n:b}){return`break${this.label?` ${this.label}`:""};`+b}}class h extends s{constructor(b){super(),this.error=b}render({_n:b}){return`throw ${this.error};`+b}get names(){return this.error.names}}class g extends s{constructor(b){super(),this.code=b}render({_n:b}){return`${this.code};`+b}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(b,x){return this.code=Z(this.code,b,x),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class d extends s{constructor(b=[]){super(),this.nodes=b}render(b){return this.nodes.reduce((x,L)=>x+L.render(b),"")}optimizeNodes(){const{nodes:b}=this;let x=b.length;for(;x--;){const L=b[x].optimizeNodes();Array.isArray(L)?b.splice(x,1,...L):L?b[x]=L:b.splice(x,1)}return b.length>0?this:void 0}optimizeNames(b,x){const{nodes:L}=this;let W=L.length;for(;W--;){const X=L[W];X.optimizeNames(b,x)||(te(b,X.names),L.splice(W,1))}return L.length>0?this:void 0}get names(){return this.nodes.reduce((b,x)=>G(b,x.names),{})}}class f extends d{render(b){return"{"+b._n+super.render(b)+"}"+b._n}}class v extends d{}class m extends f{}m.kind="else";class p extends f{constructor(b,x){super(x),this.condition=b}render(b){let x=`if(${this.condition})`+super.render(b);return this.else&&(x+="else "+this.else.render(b)),x}optimizeNodes(){super.optimizeNodes();const b=this.condition;if(b===!0)return this.nodes;let x=this.else;if(x){const L=x.optimizeNodes();x=this.else=Array.isArray(L)?new m(L):L}if(x)return b===!1?x instanceof p?x:x.nodes:this.nodes.length?this:new p(pe(b),x instanceof p?[x]:x.nodes);if(!(b===!1||!this.nodes.length))return this}optimizeNames(b,x){var L;if(this.else=(L=this.else)===null||L===void 0?void 0:L.optimizeNames(b,x),!!(super.optimizeNames(b,x)||this.else))return this.condition=Z(this.condition,b,x),this}get names(){const b=super.names;return F(b,this.condition),this.else&&G(b,this.else.names),b}}p.kind="if";class y extends f{}y.kind="for";class _ extends y{constructor(b){super(),this.iteration=b}render(b){return`for(${this.iteration})`+super.render(b)}optimizeNames(b,x){if(super.optimizeNames(b,x))return this.iteration=Z(this.iteration,b,x),this}get names(){return G(super.names,this.iteration.names)}}class w extends y{constructor(b,x,L,W){super(),this.varKind=b,this.name=x,this.from=L,this.to=W}render(b){const x=b.es5?r.varKinds.var:this.varKind,{name:L,from:W,to:X}=this;return`for(${x} ${L}=${W}; ${L}<${X}; ${L}++)`+super.render(b)}get names(){const b=F(super.names,this.from);return F(b,this.to)}}class E extends y{constructor(b,x,L,W){super(),this.loop=b,this.varKind=x,this.name=L,this.iterable=W}render(b){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(b)}optimizeNames(b,x){if(super.optimizeNames(b,x))return this.iterable=Z(this.iterable,b,x),this}get names(){return G(super.names,this.iterable.names)}}class P extends f{constructor(b,x,L){super(),this.name=b,this.args=x,this.async=L}render(b){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(b)}}P.kind="func";class T extends d{render(b){return"return "+super.render(b)}}T.kind="return";class O extends f{render(b){let x="try"+super.render(b);return this.catch&&(x+=this.catch.render(b)),this.finally&&(x+=this.finally.render(b)),x}optimizeNodes(){var b,x;return super.optimizeNodes(),(b=this.catch)===null||b===void 0||b.optimizeNodes(),(x=this.finally)===null||x===void 0||x.optimizeNodes(),this}optimizeNames(b,x){var L,W;return super.optimizeNames(b,x),(L=this.catch)===null||L===void 0||L.optimizeNames(b,x),(W=this.finally)===null||W===void 0||W.optimizeNames(b,x),this}get names(){const b=super.names;return this.catch&&G(b,this.catch.names),this.finally&&G(b,this.finally.names),b}}class M extends f{constructor(b){super(),this.error=b}render(b){return`catch(${this.error})`+super.render(b)}}M.kind="catch";class J extends f{render(b){return"finally"+super.render(b)}}J.kind="finally";class H{constructor(b,x={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...x,_n:x.lines?`
2
+ `:""},this._extScope=b,this._scope=new r.Scope({parent:b}),this._nodes=[new v]}toString(){return this._root.render(this.opts)}name(b){return this._scope.name(b)}scopeName(b){return this._extScope.name(b)}scopeValue(b,x){const L=this._extScope.value(b,x);return(this._values[L.prefix]||(this._values[L.prefix]=new Set)).add(L),L}getScopeValue(b,x){return this._extScope.getValue(b,x)}scopeRefs(b){return this._extScope.scopeRefs(b,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(b,x,L,W){const X=this._scope.toName(x);return L!==void 0&&W&&(this._constants[X.str]=L),this._leafNode(new o(b,X,L)),X}const(b,x,L){return this._def(r.varKinds.const,b,x,L)}let(b,x,L){return this._def(r.varKinds.let,b,x,L)}var(b,x,L){return this._def(r.varKinds.var,b,x,L)}assign(b,x,L){return this._leafNode(new i(b,x,L))}add(b,x){return this._leafNode(new l(b,t.operators.ADD,x))}code(b){return typeof b=="function"?b():b!==e.nil&&this._leafNode(new g(b)),this}object(...b){const x=["{"];for(const[L,W]of b)x.length>1&&x.push(","),x.push(L),(L!==W||this.opts.es5)&&(x.push(":"),(0,e.addCodeArg)(x,W));return x.push("}"),new e._Code(x)}if(b,x,L){if(this._blockNode(new p(b)),x&&L)this.code(x).else().code(L).endIf();else if(x)this.code(x).endIf();else if(L)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(b){return this._elseNode(new p(b))}else(){return this._elseNode(new m)}endIf(){return this._endBlockNode(p,m)}_for(b,x){return this._blockNode(b),x&&this.code(x).endFor(),this}for(b,x){return this._for(new _(b),x)}forRange(b,x,L,W,X=this.opts.es5?r.varKinds.var:r.varKinds.let){const $e=this._scope.toName(b);return this._for(new w(X,$e,x,L),()=>W($e))}forOf(b,x,L,W=r.varKinds.const){const X=this._scope.toName(b);if(this.opts.es5){const $e=x instanceof e.Name?x:this.var("_arr",x);return this.forRange("_i",0,(0,e._)`${$e}.length`,le=>{this.var(X,(0,e._)`${$e}[${le}]`),L(X)})}return this._for(new E("of",W,X,x),()=>L(X))}forIn(b,x,L,W=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(b,(0,e._)`Object.keys(${x})`,L);const X=this._scope.toName(b);return this._for(new E("in",W,X,x),()=>L(X))}endFor(){return this._endBlockNode(y)}label(b){return this._leafNode(new c(b))}break(b){return this._leafNode(new u(b))}return(b){const x=new T;if(this._blockNode(x),this.code(b),x.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(b,x,L){if(!x&&!L)throw new Error('CodeGen: "try" without "catch" and "finally"');const W=new O;if(this._blockNode(W),this.code(b),x){const X=this.name("e");this._currNode=W.catch=new M(X),x(X)}return L&&(this._currNode=W.finally=new J,this.code(L)),this._endBlockNode(M,J)}throw(b){return this._leafNode(new h(b))}block(b,x){return this._blockStarts.push(this._nodes.length),b&&this.code(b).endBlock(x),this}endBlock(b){const x=this._blockStarts.pop();if(x===void 0)throw new Error("CodeGen: not in self-balancing block");const L=this._nodes.length-x;if(L<0||b!==void 0&&L!==b)throw new Error(`CodeGen: wrong number of nodes: ${L} vs ${b} expected`);return this._nodes.length=x,this}func(b,x=e.nil,L,W){return this._blockNode(new P(b,x,L)),W&&this.code(W).endFunc(),this}endFunc(){return this._endBlockNode(P)}optimize(b=1){for(;b-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(b){return this._currNode.nodes.push(b),this}_blockNode(b){this._currNode.nodes.push(b),this._nodes.push(b)}_endBlockNode(b,x){const L=this._currNode;if(L instanceof b||x&&L instanceof x)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${x?`${b.kind}/${x.kind}`:b.kind}"`)}_elseNode(b){const x=this._currNode;if(!(x instanceof p))throw new Error('CodeGen: "else" without "if"');return this._currNode=x.else=b,this}get _root(){return this._nodes[0]}get _currNode(){const b=this._nodes;return b[b.length-1]}set _currNode(b){const x=this._nodes;x[x.length-1]=b}}t.CodeGen=H;function G(A,b){for(const x in b)A[x]=(A[x]||0)+(b[x]||0);return A}function F(A,b){return b instanceof e._CodeOrName?G(A,b.names):A}function Z(A,b,x){if(A instanceof e.Name)return L(A);if(!W(A))return A;return new e._Code(A._items.reduce((X,$e)=>($e instanceof e.Name&&($e=L($e)),$e instanceof e._Code?X.push(...$e._items):X.push($e),X),[]));function L(X){const $e=x[X.str];return $e===void 0||b[X.str]!==1?X:(delete b[X.str],$e)}function W(X){return X instanceof e._Code&&X._items.some($e=>$e instanceof e.Name&&b[$e.str]===1&&x[$e.str]!==void 0)}}function te(A,b){for(const x in b)A[x]=(A[x]||0)-(b[x]||0)}function pe(A){return typeof A=="boolean"||typeof A=="number"||A===null?!A:(0,e._)`!${z(A)}`}t.not=pe;const ve=C(t.operators.AND);function N(...A){return A.reduce(ve)}t.and=N;const ie=C(t.operators.OR);function D(...A){return A.reduce(ie)}t.or=D;function C(A){return(b,x)=>b===e.nil?x:x===e.nil?b:(0,e._)`${z(b)} ${A} ${z(x)}`}function z(A){return A instanceof e.Name?A:(0,e._)`(${A})`}}(Me);var se={};Object.defineProperty(se,"__esModule",{value:!0}),se.checkStrictMode=se.getErrorPath=se.Type=se.useFunc=se.setEvaluated=se.evaluatedPropsToName=se.mergeEvaluated=se.eachItem=se.unescapeJsonPointer=se.escapeJsonPointer=se.escapeFragment=se.unescapeFragment=se.schemaRefOrVal=se.schemaHasRulesButRef=se.schemaHasRules=se.checkUnknownRules=se.alwaysValidSchema=se.toHash=void 0;const Qe=Me,yw=rs;function _w(t){const e={};for(const r of t)e[r]=!0;return e}se.toHash=_w;function ww(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(kf(t,e),!If(e,t.self.RULES.all))}se.alwaysValidSchema=ww;function kf(t,e=t.schema){const{opts:r,self:a}=t;if(!r.strictSchema||typeof e=="boolean")return;const n=a.RULES.keywords;for(const s in e)n[s]||Nf(t,`unknown keyword: "${s}"`)}se.checkUnknownRules=kf;function If(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(e[r])return!0;return!1}se.schemaHasRules=If;function bw(t,e){if(typeof t=="boolean")return!t;for(const r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}se.schemaHasRulesButRef=bw;function Ew({topSchemaRef:t,schemaPath:e},r,a,n){if(!n){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Qe._)`${r}`}return(0,Qe._)`${t}${e}${(0,Qe.getProperty)(a)}`}se.schemaRefOrVal=Ew;function $w(t){return Cf(decodeURIComponent(t))}se.unescapeFragment=$w;function Sw(t){return encodeURIComponent(Tl(t))}se.escapeFragment=Sw;function Tl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=Tl;function Cf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=Cf;function Pw(t,e){if(Array.isArray(t))for(const r of t)e(r);else e(t)}se.eachItem=Pw;function Rf({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:a}){return(n,s,o,i)=>{const l=o===void 0?s:o instanceof Qe.Name?(s instanceof Qe.Name?t(n,s,o):e(n,s,o),o):s instanceof Qe.Name?(e(n,o,s),s):r(s,o);return i===Qe.Name&&!(l instanceof Qe.Name)?a(n,l):l}}se.mergeEvaluated={props:Rf({mergeNames:(t,e,r)=>t.if((0,Qe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Qe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Qe._)`${r} || {}`).code((0,Qe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Qe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Qe._)`${r} || {}`),xl(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Of}),items:Rf({mergeNames:(t,e,r)=>t.if((0,Qe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Qe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Qe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Qe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Of(t,e){if(e===!0)return t.var("props",!0);const r=t.var("props",(0,Qe._)`{}`);return e!==void 0&&xl(t,r,e),r}se.evaluatedPropsToName=Of;function xl(t,e,r){Object.keys(r).forEach(a=>t.assign((0,Qe._)`${e}${(0,Qe.getProperty)(a)}`,!0))}se.setEvaluated=xl;const Af={};function Tw(t,e){return t.scopeValue("func",{ref:e,code:Af[e.code]||(Af[e.code]=new yw._Code(e.code))})}se.useFunc=Tw;var kl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(kl||(se.Type=kl={}));function xw(t,e,r){if(t instanceof Qe.Name){const a=e===kl.Num;return r?a?(0,Qe._)`"[" + ${t} + "]"`:(0,Qe._)`"['" + ${t} + "']"`:a?(0,Qe._)`"/" + ${t}`:(0,Qe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Qe.getProperty)(t).toString():"/"+Tl(t)}se.getErrorPath=xw;function Nf(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}se.checkStrictMode=Nf;var Nr={};Object.defineProperty(Nr,"__esModule",{value:!0});const jt=Me,kw={data:new jt.Name("data"),valCxt:new jt.Name("valCxt"),instancePath:new jt.Name("instancePath"),parentData:new jt.Name("parentData"),parentDataProperty:new jt.Name("parentDataProperty"),rootData:new jt.Name("rootData"),dynamicAnchors:new jt.Name("dynamicAnchors"),vErrors:new jt.Name("vErrors"),errors:new jt.Name("errors"),this:new jt.Name("this"),self:new jt.Name("self"),scope:new jt.Name("scope"),json:new jt.Name("json"),jsonPos:new jt.Name("jsonPos"),jsonLen:new jt.Name("jsonLen"),jsonPart:new jt.Name("jsonPart")};Nr.default=kw,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=Me,r=se,a=Nr;t.keywordError={message:({keyword:m})=>(0,e.str)`must pass "${m}" keyword validation`},t.keyword$DataError={message:({keyword:m,schemaType:p})=>p?(0,e.str)`"${m}" keyword must be ${p} ($data)`:(0,e.str)`"${m}" keyword is invalid ($data)`};function n(m,p=t.keywordError,y,_){const{it:w}=m,{gen:E,compositeRule:P,allErrors:T}=w,O=h(m,p,y);_??(P||T)?l(E,O):c(w,(0,e._)`[${O}]`)}t.reportError=n;function s(m,p=t.keywordError,y){const{it:_}=m,{gen:w,compositeRule:E,allErrors:P}=_,T=h(m,p,y);l(w,T),E||P||c(_,a.default.vErrors)}t.reportExtraError=s;function o(m,p){m.assign(a.default.errors,p),m.if((0,e._)`${a.default.vErrors} !== null`,()=>m.if(p,()=>m.assign((0,e._)`${a.default.vErrors}.length`,p),()=>m.assign(a.default.vErrors,null)))}t.resetErrorsCount=o;function i({gen:m,keyword:p,schemaValue:y,data:_,errsCount:w,it:E}){if(w===void 0)throw new Error("ajv implementation error");const P=m.name("err");m.forRange("i",w,a.default.errors,T=>{m.const(P,(0,e._)`${a.default.vErrors}[${T}]`),m.if((0,e._)`${P}.instancePath === undefined`,()=>m.assign((0,e._)`${P}.instancePath`,(0,e.strConcat)(a.default.instancePath,E.errorPath))),m.assign((0,e._)`${P}.schemaPath`,(0,e.str)`${E.errSchemaPath}/${p}`),E.opts.verbose&&(m.assign((0,e._)`${P}.schema`,y),m.assign((0,e._)`${P}.data`,_))})}t.extendErrors=i;function l(m,p){const y=m.const("err",p);m.if((0,e._)`${a.default.vErrors} === null`,()=>m.assign(a.default.vErrors,(0,e._)`[${y}]`),(0,e._)`${a.default.vErrors}.push(${y})`),m.code((0,e._)`${a.default.errors}++`)}function c(m,p){const{gen:y,validateName:_,schemaEnv:w}=m;w.$async?y.throw((0,e._)`new ${m.ValidationError}(${p})`):(y.assign((0,e._)`${_}.errors`,p),y.return(!1))}const u={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function h(m,p,y){const{createErrors:_}=m.it;return _===!1?(0,e._)`{}`:g(m,p,y)}function g(m,p,y={}){const{gen:_,it:w}=m,E=[d(w,y),f(m,y)];return v(m,p,E),_.object(...E)}function d({errorPath:m},{instancePath:p}){const y=p?(0,e.str)`${m}${(0,r.getErrorPath)(p,r.Type.Str)}`:m;return[a.default.instancePath,(0,e.strConcat)(a.default.instancePath,y)]}function f({keyword:m,it:{errSchemaPath:p}},{schemaPath:y,parentSchema:_}){let w=_?p:(0,e.str)`${p}/${m}`;return y&&(w=(0,e.str)`${w}${(0,r.getErrorPath)(y,r.Type.Str)}`),[u.schemaPath,w]}function v(m,{params:p,message:y},_){const{keyword:w,data:E,schemaValue:P,it:T}=m,{opts:O,propertyName:M,topSchemaRef:J,schemaPath:H}=T;_.push([u.keyword,w],[u.params,typeof p=="function"?p(m):p||(0,e._)`{}`]),O.messages&&_.push([u.message,typeof y=="function"?y(m):y]),O.verbose&&_.push([u.schema,P],[u.parentSchema,(0,e._)`${J}${H}`],[a.default.data,E]),M&&_.push([u.propertyName,M])}}(ts),Object.defineProperty(fa,"__esModule",{value:!0}),fa.boolOrEmptySchema=fa.topBoolOrEmptySchema=void 0;const Iw=ts,Cw=Me,Rw=Nr,Ow={message:"boolean schema is false"};function Aw(t){const{gen:e,schema:r,validateName:a}=t;r===!1?Mf(t,!1):typeof r=="object"&&r.$async===!0?e.return(Rw.default.data):(e.assign((0,Cw._)`${a}.errors`,null),e.return(!0))}fa.topBoolOrEmptySchema=Aw;function Nw(t,e){const{gen:r,schema:a}=t;a===!1?(r.var(e,!1),Mf(t)):r.var(e,!0)}fa.boolOrEmptySchema=Nw;function Mf(t,e){const{gen:r,data:a}=t,n={gen:r,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Iw.reportError)(n,Ow,void 0,e)}var Tt={},jn={};Object.defineProperty(jn,"__esModule",{value:!0}),jn.getRules=jn.isJSONType=void 0;const Mw=["string","number","integer","boolean","null","object","array"],jw=new Set(Mw);function Dw(t){return typeof t=="string"&&jw.has(t)}jn.isJSONType=Dw;function Lw(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}jn.getRules=Lw;var tn={};Object.defineProperty(tn,"__esModule",{value:!0}),tn.shouldUseRule=tn.shouldUseGroup=tn.schemaHasRulesForType=void 0;function zw({schema:t,self:e},r){const a=e.RULES.types[r];return a&&a!==!0&&jf(t,a)}tn.schemaHasRulesForType=zw;function jf(t,e){return e.rules.some(r=>Df(t,r))}tn.shouldUseGroup=jf;function Df(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(a=>t[a]!==void 0))}tn.shouldUseRule=Df,Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.reportTypeError=Tt.checkDataTypes=Tt.checkDataType=Tt.coerceAndCheckDataType=Tt.getJSONTypes=Tt.getSchemaTypes=Tt.DataType=void 0;const Uw=jn,qw=tn,Fw=ts,Re=Me,Lf=se;var pa;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(pa||(Tt.DataType=pa={}));function Zw(t){const e=zf(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Tt.getSchemaTypes=Zw;function zf(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(Uw.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Tt.getJSONTypes=zf;function Vw(t,e){const{gen:r,data:a,opts:n}=t,s=Hw(e,n.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,qw.schemaHasRulesForType)(t,e[0]));if(o){const i=Cl(e,a,n.strictNumbers,pa.Wrong);r.if(i,()=>{s.length?Bw(t,e,s):Rl(t)})}return o}Tt.coerceAndCheckDataType=Vw;const Uf=new Set(["string","number","integer","boolean","null"]);function Hw(t,e){return e?t.filter(r=>Uf.has(r)||e==="array"&&r==="array"):[]}function Bw(t,e,r){const{gen:a,data:n,opts:s}=t,o=a.let("dataType",(0,Re._)`typeof ${n}`),i=a.let("coerced",(0,Re._)`undefined`);s.coerceTypes==="array"&&a.if((0,Re._)`${o} == 'object' && Array.isArray(${n}) && ${n}.length == 1`,()=>a.assign(n,(0,Re._)`${n}[0]`).assign(o,(0,Re._)`typeof ${n}`).if(Cl(e,n,s.strictNumbers),()=>a.assign(i,n))),a.if((0,Re._)`${i} !== undefined`);for(const c of r)(Uf.has(c)||c==="array"&&s.coerceTypes==="array")&&l(c);a.else(),Rl(t),a.endIf(),a.if((0,Re._)`${i} !== undefined`,()=>{a.assign(n,i),Jw(t,i)});function l(c){switch(c){case"string":a.elseIf((0,Re._)`${o} == "number" || ${o} == "boolean"`).assign(i,(0,Re._)`"" + ${n}`).elseIf((0,Re._)`${n} === null`).assign(i,(0,Re._)`""`);return;case"number":a.elseIf((0,Re._)`${o} == "boolean" || ${n} === null
3
3
  || (${o} == "string" && ${n} && ${n} == +${n})`).assign(i,(0,Re._)`+${n}`);return;case"integer":a.elseIf((0,Re._)`${o} === "boolean" || ${n} === null
4
4
  || (${o} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(i,(0,Re._)`+${n}`);return;case"boolean":a.elseIf((0,Re._)`${n} === "false" || ${n} === 0 || ${n} === null`).assign(i,!1).elseIf((0,Re._)`${n} === "true" || ${n} === 1`).assign(i,!0);return;case"null":a.elseIf((0,Re._)`${n} === "" || ${n} === 0 || ${n} === false`),a.assign(i,null);return;case"array":a.elseIf((0,Re._)`${o} === "string" || ${o} === "number"
5
- || ${o} === "boolean" || ${n} === null`).assign(i,(0,Re._)`[${n}]`)}}}function Lw({gen:t,parentData:e,parentDataProperty:r},a){t.if((0,Re._)`${e} !== undefined`,()=>t.assign((0,Re._)`${e}[${r}]`,a))}function zl(t,e,r,a=_a.Correct){const n=a===_a.Correct?Re.operators.EQ:Re.operators.NEQ;let s;switch(t){case"null":return(0,Re._)`${e} ${n} null`;case"array":s=(0,Re._)`Array.isArray(${e})`;break;case"object":s=(0,Re._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,Re._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,Re._)`typeof ${e} ${n} ${t}`}return a===_a.Correct?s:(0,Re.not)(s);function o(i=Re.nil){return(0,Re.and)((0,Re._)`typeof ${e} == "number"`,i,r?(0,Re._)`isFinite(${e})`:Re.nil)}}Tt.checkDataType=zl;function Ul(t,e,r,a){if(t.length===1)return zl(t[0],e,r,a);let n;const s=(0,Dp.toHash)(t);if(s.array&&s.object){const o=(0,Re._)`typeof ${e} != "object"`;n=s.null?o:(0,Re._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else n=Re.nil;s.number&&delete s.integer;for(const o in s)n=(0,Re.and)(n,zl(o,e,r,a));return n}Tt.checkDataTypes=Ul;const zw={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Re._)`{type: ${t}}`:(0,Re._)`{type: ${e}}`};function ql(t){const e=Uw(t);(0,Nw.reportError)(e,zw)}Tt.reportTypeError=ql;function Uw(t){const{gen:e,data:r,schema:a}=t,n=(0,Dp.schemaRefOrVal)(t,a,"type");return{gen:e,keyword:"type",data:r,schema:a.type,schemaCode:n,schemaValue:n,parentSchema:a,params:{},it:t}}var No={};Object.defineProperty(No,"__esModule",{value:!0}),No.assignDefaults=void 0;const wa=Me,qw=ie;function Fw(t,e){const{properties:r,items:a}=t.schema;if(e==="object"&&r)for(const n in r)Up(t,n,r[n].default);else e==="array"&&Array.isArray(a)&&a.forEach((n,s)=>Up(t,s,n.default))}No.assignDefaults=Fw;function Up(t,e,r){const{gen:a,compositeRule:n,data:s,opts:o}=t;if(r===void 0)return;const i=(0,wa._)`${s}${(0,wa.getProperty)(e)}`;if(n){(0,qw.checkStrictMode)(t,`default is ignored for: ${i}`);return}let l=(0,wa._)`${i} === undefined`;o.useDefaults==="empty"&&(l=(0,wa._)`${l} || ${i} === null || ${i} === ""`),a.if(l,(0,wa._)`${i} = ${(0,wa.stringify)(r)}`)}var Vr={},je={};Object.defineProperty(je,"__esModule",{value:!0}),je.validateUnion=je.validateArray=je.usePattern=je.callValidateCode=je.schemaProperties=je.allSchemaProperties=je.noPropertyInData=je.propertyInData=je.isOwnProperty=je.hasPropFunc=je.reportMissingProp=je.checkMissingProp=je.checkReportMissingProp=void 0;const at=Me,Fl=ie,Sn=Zr,Zw=ie;function Vw(t,e){const{gen:r,data:a,it:n}=t;r.if(Vl(r,a,e,n.opts.ownProperties),()=>{t.setParams({missingProperty:(0,at._)`${e}`},!0),t.error()})}je.checkReportMissingProp=Vw;function Hw({gen:t,data:e,it:{opts:r}},a,n){return(0,at.or)(...a.map(s=>(0,at.and)(Vl(t,e,s,r.ownProperties),(0,at._)`${n} = ${s}`)))}je.checkMissingProp=Hw;function Bw(t,e){t.setParams({missingProperty:e},!0),t.error()}je.reportMissingProp=Bw;function qp(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,at._)`Object.prototype.hasOwnProperty`})}je.hasPropFunc=qp;function Zl(t,e,r){return(0,at._)`${qp(t)}.call(${e}, ${r})`}je.isOwnProperty=Zl;function Jw(t,e,r,a){const n=(0,at._)`${e}${(0,at.getProperty)(r)} !== undefined`;return a?(0,at._)`${n} && ${Zl(t,e,r)}`:n}je.propertyInData=Jw;function Vl(t,e,r,a){const n=(0,at._)`${e}${(0,at.getProperty)(r)} === undefined`;return a?(0,at.or)(n,(0,at.not)(Zl(t,e,r))):n}je.noPropertyInData=Vl;function Fp(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}je.allSchemaProperties=Fp;function Gw(t,e){return Fp(e).filter(r=>!(0,Fl.alwaysValidSchema)(t,e[r]))}je.schemaProperties=Gw;function Kw({schemaCode:t,data:e,it:{gen:r,topSchemaRef:a,schemaPath:n,errorPath:s},it:o},i,l,c){const u=c?(0,at._)`${t}, ${e}, ${a}${n}`:e,f=[[Sn.default.instancePath,(0,at.strConcat)(Sn.default.instancePath,s)],[Sn.default.parentData,o.parentData],[Sn.default.parentDataProperty,o.parentDataProperty],[Sn.default.rootData,Sn.default.rootData]];o.opts.dynamicRef&&f.push([Sn.default.dynamicAnchors,Sn.default.dynamicAnchors]);const g=(0,at._)`${u}, ${r.object(...f)}`;return l!==at.nil?(0,at._)`${i}.call(${l}, ${g})`:(0,at._)`${i}(${g})`}je.callValidateCode=Kw;const Ww=(0,at._)`new RegExp`;function Qw({gen:t,it:{opts:e}},r){const a=e.unicodeRegExp?"u":"",{regExp:n}=e.code,s=n(r,a);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,at._)`${n.code==="new RegExp"?Ww:(0,Zw.useFunc)(t,n)}(${r}, ${a})`})}je.usePattern=Qw;function Yw(t){const{gen:e,data:r,keyword:a,it:n}=t,s=e.name("valid");if(n.allErrors){const i=e.let("valid",!0);return o(()=>e.assign(i,!1)),i}return e.var(s,!0),o(()=>e.break()),s;function o(i){const l=e.const("len",(0,at._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:a,dataProp:c,dataPropType:Fl.Type.Num},s),e.if((0,at.not)(s),i)})}}je.validateArray=Yw;function Xw(t){const{gen:e,schema:r,keyword:a,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Fl.alwaysValidSchema)(n,l))&&!n.opts.unevaluated)return;const o=e.let("valid",!1),i=e.name("_valid");e.block(()=>r.forEach((l,c)=>{const u=t.subschema({keyword:a,schemaProp:c,compositeRule:!0},i);e.assign(o,(0,at._)`${o} || ${i}`),t.mergeValidEvaluated(u,i)||e.if((0,at.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}je.validateUnion=Xw,Object.defineProperty(Vr,"__esModule",{value:!0}),Vr.validateKeywordUsage=Vr.validSchemaType=Vr.funcKeywordCode=Vr.macroKeywordCode=void 0;const Bt=Me,Vn=Zr,eb=je,tb=is;function rb(t,e){const{gen:r,keyword:a,schema:n,parentSchema:s,it:o}=t,i=e.macro.call(o.self,n,s,o),l=Vp(r,a,i);o.opts.validateSchema!==!1&&o.self.validateSchema(i,!0);const c=r.name("valid");t.subschema({schema:i,schemaPath:Bt.nil,errSchemaPath:`${o.errSchemaPath}/${a}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Vr.macroKeywordCode=rb;function nb(t,e){var r;const{gen:a,keyword:n,schema:s,parentSchema:o,$data:i,it:l}=t;sb(l,e);const c=!i&&e.compile?e.compile.call(l.self,s,o,l):e.validate,u=Vp(a,n,c),f=a.let("valid");t.block$data(f,g),t.ok((r=e.valid)!==null&&r!==void 0?r:f);function g(){if(e.errors===!1)v(),e.modifying&&Zp(t),m(()=>t.error());else{const p=e.async?d():h();e.modifying&&Zp(t),m(()=>ab(t,p))}}function d(){const p=a.let("ruleErrs",null);return a.try(()=>v((0,Bt._)`await `),_=>a.assign(f,!1).if((0,Bt._)`${_} instanceof ${l.ValidationError}`,()=>a.assign(p,(0,Bt._)`${_}.errors`),()=>a.throw(_))),p}function h(){const p=(0,Bt._)`${u}.errors`;return a.assign(p,null),v(Bt.nil),p}function v(p=e.async?(0,Bt._)`await `:Bt.nil){const _=l.opts.passContext?Vn.default.this:Vn.default.self,w=!("compile"in e&&!i||e.schema===!1);a.assign(f,(0,Bt._)`${p}${(0,eb.callValidateCode)(t,u,_,w)}`,e.modifying)}function m(p){var _;a.if((0,Bt.not)((_=e.valid)!==null&&_!==void 0?_:f),p)}}Vr.funcKeywordCode=nb;function Zp(t){const{gen:e,data:r,it:a}=t;e.if(a.parentData,()=>e.assign(r,(0,Bt._)`${a.parentData}[${a.parentDataProperty}]`))}function ab(t,e){const{gen:r}=t;r.if((0,Bt._)`Array.isArray(${e})`,()=>{r.assign(Vn.default.vErrors,(0,Bt._)`${Vn.default.vErrors} === null ? ${e} : ${Vn.default.vErrors}.concat(${e})`).assign(Vn.default.errors,(0,Bt._)`${Vn.default.vErrors}.length`),(0,tb.extendErrors)(t)},()=>t.error())}function sb({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Vp(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Bt.stringify)(r)})}function ob(t,e,r=!1){return!e.length||e.some(a=>a==="array"?Array.isArray(t):a==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==a||r&&typeof t>"u")}Vr.validSchemaType=ob;function ib({schema:t,opts:e,self:r,errSchemaPath:a},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw new Error("ajv implementation error");const o=n.dependencies;if(o!=null&&o.some(i=>!Object.prototype.hasOwnProperty.call(t,i)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(n.validateSchema&&!n.validateSchema(t[s])){const l=`keyword "${s}" value is invalid at path "${a}": `+r.errorsText(n.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Vr.validateKeywordUsage=ib;var $n={};Object.defineProperty($n,"__esModule",{value:!0}),$n.extendSubschemaMode=$n.extendSubschemaData=$n.getSubschema=void 0;const Hr=Me,Hp=ie;function lb(t,{keyword:e,schemaProp:r,schema:a,schemaPath:n,errSchemaPath:s,topSchemaRef:o}){if(e!==void 0&&a!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const i=t.schema[e];return r===void 0?{schema:i,schemaPath:(0,Hr._)`${t.schemaPath}${(0,Hr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:i[r],schemaPath:(0,Hr._)`${t.schemaPath}${(0,Hr.getProperty)(e)}${(0,Hr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Hp.escapeFragment)(r)}`}}if(a!==void 0){if(n===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:n,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}$n.getSubschema=lb;function cb(t,e,{dataProp:r,dataPropType:a,data:n,dataTypes:s,propertyName:o}){if(n!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:i}=e;if(r!==void 0){const{errorPath:c,dataPathArr:u,opts:f}=e,g=i.let("data",(0,Hr._)`${e.data}${(0,Hr.getProperty)(r)}`,!0);l(g),t.errorPath=(0,Hr.str)`${c}${(0,Hp.getErrorPath)(r,a,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Hr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(n!==void 0){const c=n instanceof Hr.Name?n:i.let("data",n,!0);l(c),o!==void 0&&(t.propertyName=o)}s&&(t.dataTypes=s);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}$n.extendSubschemaData=cb;function ub(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:a,createErrors:n,allErrors:s}){a!==void 0&&(t.compositeRule=a),n!==void 0&&(t.createErrors=n),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}$n.extendSubschemaMode=ub;var Lt={},cs=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var a,n,s;if(Array.isArray(e)){if(a=e.length,a!=r.length)return!1;for(n=a;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),a=s.length,a!==Object.keys(r).length)return!1;for(n=a;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=a;n--!==0;){var o=s[n];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r},Bp={exports:{}},Pn=Bp.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};Ao(e,a,n,t,"",t)};Pn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},Pn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Pn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Pn.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 Ao(t,e,r,a,n,s,o,i,l,c){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,n,s,o,i,l,c);for(var u in a){var f=a[u];if(Array.isArray(f)){if(u in Pn.arrayKeywords)for(var g=0;g<f.length;g++)Ao(t,e,r,f[g],n+"/"+u+"/"+g,s,n,u,a,g)}else if(u in Pn.propsKeywords){if(f&&typeof f=="object")for(var d in f)Ao(t,e,r,f[d],n+"/"+u+"/"+db(d),s,n,u,a,d)}else(u in Pn.keywords||t.allKeys&&!(u in Pn.skipKeywords))&&Ao(t,e,r,f,n+"/"+u,s,n,u,a)}r(a,n,s,o,i,l,c)}}function db(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var pb=Bp.exports;Object.defineProperty(Lt,"__esModule",{value:!0}),Lt.getSchemaRefs=Lt.resolveUrl=Lt.normalizeId=Lt._getFullPath=Lt.getFullPath=Lt.inlineRef=void 0;const fb=ie,hb=cs,mb=pb,vb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function gb(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Hl(t):e?Jp(t)<=e:!1}Lt.inlineRef=gb;const yb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Hl(t){for(const e in t){if(yb.has(e))return!0;const r=t[e];if(Array.isArray(r)&&r.some(Hl)||typeof r=="object"&&Hl(r))return!0}return!1}function Jp(t){let e=0;for(const r in t){if(r==="$ref")return 1/0;if(e++,!vb.has(r)&&(typeof t[r]=="object"&&(0,fb.eachItem)(t[r],a=>e+=Jp(a)),e===1/0))return 1/0}return e}function Gp(t,e="",r){r!==!1&&(e=ba(e));const a=t.parse(e);return Kp(t,a)}Lt.getFullPath=Gp;function Kp(t,e){return t.serialize(e).split("#")[0]+"#"}Lt._getFullPath=Kp;const _b=/#\/?$/;function ba(t){return t?t.replace(_b,""):""}Lt.normalizeId=ba;function wb(t,e,r){return r=ba(r),t.resolve(e,r)}Lt.resolveUrl=wb;const bb=/^[a-z_][-a-z0-9._]*$/i;function Eb(t,e){if(typeof t=="boolean")return{};const{schemaId:r,uriResolver:a}=this.opts,n=ba(t[r]||e),s={"":n},o=Gp(a,n,!1),i={},l=new Set;return mb(t,{allKeys:!0},(f,g,d,h)=>{if(h===void 0)return;const v=o+g;let m=s[h];typeof f[r]=="string"&&(m=p.call(this,f[r])),_.call(this,f.$anchor),_.call(this,f.$dynamicAnchor),s[g]=m;function p(w){const b=this.opts.uriResolver.resolve;if(w=ba(m?b(m,w):w),l.has(w))throw u(w);l.add(w);let S=this.refs[w];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?c(f,S.schema,w):w!==ba(v)&&(w[0]==="#"?(c(f,i[w],w),i[w]=f):this.refs[w]=v),w}function _(w){if(typeof w=="string"){if(!bb.test(w))throw new Error(`invalid anchor "${w}"`);p.call(this,`#${w}`)}}}),i;function c(f,g,d){if(g!==void 0&&!hb(f,g))throw u(d)}function u(f){return new Error(`reference "${f}" resolves to more than one schema`)}}Lt.getSchemaRefs=Eb,Object.defineProperty(kr,"__esModule",{value:!0}),kr.getData=kr.KeywordCxt=kr.validateFunctionCode=void 0;const Wp=ya,Qp=Tt,Bl=dn,Mo=Tt,Sb=No,us=Vr,Jl=$n,ve=Me,Pe=Zr,$b=Lt,pn=ie,ds=is;function Pb(t){if(tf(t)&&(rf(t),ef(t))){xb(t);return}Yp(t,()=>(0,Wp.topBoolOrEmptySchema)(t))}kr.validateFunctionCode=Pb;function Yp({gen:t,validateName:e,schema:r,schemaEnv:a,opts:n},s){n.code.es5?t.func(e,(0,ve._)`${Pe.default.data}, ${Pe.default.valCxt}`,a.$async,()=>{t.code((0,ve._)`"use strict"; ${Xp(r,n)}`),Ib(t,n),t.code(s)}):t.func(e,(0,ve._)`${Pe.default.data}, ${kb(n)}`,a.$async,()=>t.code(Xp(r,n)).code(s))}function kb(t){return(0,ve._)`{${Pe.default.instancePath}="", ${Pe.default.parentData}, ${Pe.default.parentDataProperty}, ${Pe.default.rootData}=${Pe.default.data}${t.dynamicRef?(0,ve._)`, ${Pe.default.dynamicAnchors}={}`:ve.nil}}={}`}function Ib(t,e){t.if(Pe.default.valCxt,()=>{t.var(Pe.default.instancePath,(0,ve._)`${Pe.default.valCxt}.${Pe.default.instancePath}`),t.var(Pe.default.parentData,(0,ve._)`${Pe.default.valCxt}.${Pe.default.parentData}`),t.var(Pe.default.parentDataProperty,(0,ve._)`${Pe.default.valCxt}.${Pe.default.parentDataProperty}`),t.var(Pe.default.rootData,(0,ve._)`${Pe.default.valCxt}.${Pe.default.rootData}`),e.dynamicRef&&t.var(Pe.default.dynamicAnchors,(0,ve._)`${Pe.default.valCxt}.${Pe.default.dynamicAnchors}`)},()=>{t.var(Pe.default.instancePath,(0,ve._)`""`),t.var(Pe.default.parentData,(0,ve._)`undefined`),t.var(Pe.default.parentDataProperty,(0,ve._)`undefined`),t.var(Pe.default.rootData,Pe.default.data),e.dynamicRef&&t.var(Pe.default.dynamicAnchors,(0,ve._)`{}`)})}function xb(t){const{schema:e,opts:r,gen:a}=t;Yp(t,()=>{r.$comment&&e.$comment&&af(t),Nb(t),a.let(Pe.default.vErrors,null),a.let(Pe.default.errors,0),r.unevaluated&&Tb(t),nf(t),jb(t)})}function Tb(t){const{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,ve._)`${r}.evaluated`),e.if((0,ve._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,ve._)`${t.evaluated}.props`,(0,ve._)`undefined`)),e.if((0,ve._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,ve._)`${t.evaluated}.items`,(0,ve._)`undefined`))}function Xp(t,e){const r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,ve._)`/*# sourceURL=${r} */`:ve.nil}function Cb(t,e){if(tf(t)&&(rf(t),ef(t))){Rb(t,e);return}(0,Wp.boolOrEmptySchema)(t,e)}function ef({schema:t,self:e}){if(typeof t=="boolean")return!t;for(const r in t)if(e.RULES.all[r])return!0;return!1}function tf(t){return typeof t.schema!="boolean"}function Rb(t,e){const{schema:r,gen:a,opts:n}=t;n.$comment&&r.$comment&&af(t),Ab(t),Mb(t);const s=a.const("_errs",Pe.default.errors);nf(t,s),a.var(e,(0,ve._)`${s} === ${Pe.default.errors}`)}function rf(t){(0,pn.checkUnknownRules)(t),Ob(t)}function nf(t,e){if(t.opts.jtd)return sf(t,[],!1,e);const r=(0,Qp.getSchemaTypes)(t.schema),a=(0,Qp.coerceAndCheckDataType)(t,r);sf(t,r,!a,e)}function Ob(t){const{schema:e,errSchemaPath:r,opts:a,self:n}=t;e.$ref&&a.ignoreKeywordsWithRef&&(0,pn.schemaHasRulesButRef)(e,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Nb(t){const{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,pn.checkStrictMode)(t,"default is ignored in the schema root")}function Ab(t){const e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,$b.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Mb(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function af({gen:t,schemaEnv:e,schema:r,errSchemaPath:a,opts:n}){const s=r.$comment;if(n.$comment===!0)t.code((0,ve._)`${Pe.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){const o=(0,ve.str)`${a}/$comment`,i=t.scopeValue("root",{ref:e.root});t.code((0,ve._)`${Pe.default.self}.opts.$comment(${s}, ${o}, ${i}.schema)`)}}function jb(t){const{gen:e,schemaEnv:r,validateName:a,ValidationError:n,opts:s}=t;r.$async?e.if((0,ve._)`${Pe.default.errors} === 0`,()=>e.return(Pe.default.data),()=>e.throw((0,ve._)`new ${n}(${Pe.default.vErrors})`)):(e.assign((0,ve._)`${a}.errors`,Pe.default.vErrors),s.unevaluated&&Db(t),e.return((0,ve._)`${Pe.default.errors} === 0`))}function Db({gen:t,evaluated:e,props:r,items:a}){r instanceof ve.Name&&t.assign((0,ve._)`${e}.props`,r),a instanceof ve.Name&&t.assign((0,ve._)`${e}.items`,a)}function sf(t,e,r,a){const{gen:n,schema:s,data:o,allErrors:i,opts:l,self:c}=t,{RULES:u}=c;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,pn.schemaHasRulesButRef)(s,u))){n.block(()=>uf(t,"$ref",u.all.$ref.definition));return}l.jtd||Lb(t,e),n.block(()=>{for(const g of u.rules)f(g);f(u.post)});function f(g){(0,Bl.shouldUseGroup)(s,g)&&(g.type?(n.if((0,Mo.checkDataType)(g.type,o,l.strictNumbers)),of(t,g),e.length===1&&e[0]===g.type&&r&&(n.else(),(0,Mo.reportTypeError)(t)),n.endIf()):of(t,g),i||n.if((0,ve._)`${Pe.default.errors} === ${a||0}`))}}function of(t,e){const{gen:r,schema:a,opts:{useDefaults:n}}=t;n&&(0,Sb.assignDefaults)(t,e.type),r.block(()=>{for(const s of e.rules)(0,Bl.shouldUseRule)(a,s)&&uf(t,s.keyword,s.definition,e.type)})}function Lb(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(zb(t,e),t.opts.allowUnionTypes||Ub(t,e),qb(t,t.dataTypes))}function zb(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{lf(t.dataTypes,r)||Gl(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Zb(t,e)}}function Ub(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Gl(t,"use allowUnionTypes to allow union type keyword")}function qb(t,e){const r=t.self.RULES.all;for(const a in r){const n=r[a];if(typeof n=="object"&&(0,Bl.shouldUseRule)(t.schema,n)){const{type:s}=n.definition;s.length&&!s.some(o=>Fb(e,o))&&Gl(t,`missing type "${s.join(",")}" for keyword "${a}"`)}}}function Fb(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function lf(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Zb(t,e){const r=[];for(const a of t.dataTypes)lf(e,a)?r.push(a):e.includes("integer")&&a==="number"&&r.push("integer");t.dataTypes=r}function Gl(t,e){const r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,pn.checkStrictMode)(t,e,t.opts.strictTypes)}class cf{constructor(e,r,a){if((0,us.validateKeywordUsage)(e,r,a),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=a,this.data=e.data,this.schema=e.schema[a],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,pn.schemaRefOrVal)(e,this.schema,a,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",df(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,us.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${a} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Pe.default.errors))}result(e,r,a){this.failResult((0,ve.not)(e),r,a)}failResult(e,r,a){this.gen.if(e),a?a():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,ve.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:r}=this;this.fail((0,ve._)`${r} !== undefined && (${(0,ve.or)(this.invalid$data(),e)})`)}error(e,r,a){if(r){this.setParams(r),this._error(e,a),this.setParams({});return}this._error(e,a)}_error(e,r){(e?ds.reportExtraError:ds.reportError)(this,this.def.error,r)}$dataError(){(0,ds.reportError)(this,this.def.$dataError||ds.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ds.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,a=ve.nil){this.gen.block(()=>{this.check$data(e,a),r()})}check$data(e=ve.nil,r=ve.nil){if(!this.$data)return;const{gen:a,schemaCode:n,schemaType:s,def:o}=this;a.if((0,ve.or)((0,ve._)`${n} === undefined`,r)),e!==ve.nil&&a.assign(e,!0),(s.length||o.validateSchema)&&(a.elseIf(this.invalid$data()),this.$dataError(),e!==ve.nil&&a.assign(e,!1)),a.else()}invalid$data(){const{gen:e,schemaCode:r,schemaType:a,def:n,it:s}=this;return(0,ve.or)(o(),i());function o(){if(a.length){if(!(r instanceof ve.Name))throw new Error("ajv implementation error");const l=Array.isArray(a)?a:[a];return(0,ve._)`${(0,Mo.checkDataTypes)(l,r,s.opts.strictNumbers,Mo.DataType.Wrong)}`}return ve.nil}function i(){if(n.validateSchema){const l=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,ve._)`!${l}(${r})`}return ve.nil}}subschema(e,r){const a=(0,Jl.getSubschema)(this.it,e);(0,Jl.extendSubschemaData)(a,this.it,e),(0,Jl.extendSubschemaMode)(a,e);const n={...this.it,...a,items:void 0,props:void 0};return Cb(n,r),n}mergeEvaluated(e,r){const{it:a,gen:n}=this;a.opts.unevaluated&&(a.props!==!0&&e.props!==void 0&&(a.props=pn.mergeEvaluated.props(n,e.props,a.props,r)),a.items!==!0&&e.items!==void 0&&(a.items=pn.mergeEvaluated.items(n,e.items,a.items,r)))}mergeValidEvaluated(e,r){const{it:a,gen:n}=this;if(a.opts.unevaluated&&(a.props!==!0||a.items!==!0))return n.if(r,()=>this.mergeEvaluated(e,ve.Name)),!0}}kr.KeywordCxt=cf;function uf(t,e,r,a){const n=new cf(t,r,e);"code"in r?r.code(n,a):n.$data&&r.validate?(0,us.funcKeywordCode)(n,r):"macro"in r?(0,us.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,us.funcKeywordCode)(n,r)}const Vb=/^\/(?:[^~]|~0|~1)*$/,Hb=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function df(t,{dataLevel:e,dataNames:r,dataPathArr:a}){let n,s;if(t==="")return Pe.default.rootData;if(t[0]==="/"){if(!Vb.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);n=t,s=Pe.default.rootData}else{const c=Hb.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);const u=+c[1];if(n=c[2],n==="#"){if(u>=e)throw new Error(l("property/index",u));return a[e-u]}if(u>e)throw new Error(l("data",u));if(s=r[e-u],!n)return s}let o=s;const i=n.split("/");for(const c of i)c&&(s=(0,ve._)`${s}${(0,ve.getProperty)((0,pn.unescapeJsonPointer)(c))}`,o=(0,ve._)`${o} && ${s}`);return o;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}kr.getData=df;var ps={};Object.defineProperty(ps,"__esModule",{value:!0});let Bb=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ps.default=Bb;var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0});const Kl=Lt;let Jb=class extends Error{constructor(e,r,a,n){super(n||`can't resolve reference ${a} from id ${r}`),this.missingRef=(0,Kl.resolveUrl)(e,r,a),this.missingSchema=(0,Kl.normalizeId)((0,Kl.getFullPath)(e,this.missingRef))}};Ea.default=Jb;var Qt={};Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.resolveSchema=Qt.getCompilingSchema=Qt.resolveRef=Qt.compileSchema=Qt.SchemaEnv=void 0;const Ir=Me,Gb=ps,Hn=Zr,xr=Lt,pf=ie,Kb=kr;class jo{constructor(e){var r;this.refs={},this.dynamicAnchors={};let a;typeof e.schema=="object"&&(a=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,xr.normalizeId)(a==null?void 0:a[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=a==null?void 0:a.$async,this.refs={}}}Qt.SchemaEnv=jo;function Wl(t){const e=ff.call(this,t);if(e)return e;const r=(0,xr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:a,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new Ir.CodeGen(this.scope,{es5:a,lines:n,ownProperties:s});let i;t.$async&&(i=o.scopeValue("Error",{ref:Gb.default,code:(0,Ir._)`require("ajv/dist/runtime/validation_error").default`}));const l=o.scopeName("validate");t.validateName=l;const c={gen:o,allErrors:this.opts.allErrors,data:Hn.default.data,parentData:Hn.default.parentData,parentDataProperty:Hn.default.parentDataProperty,dataNames:[Hn.default.data],dataPathArr:[Ir.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Ir.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:i,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Ir.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ir._)`""`,opts:this.opts,self:this};let u;try{this._compilations.add(t),(0,Kb.validateFunctionCode)(c),o.optimize(this.opts.code.optimize);const f=o.toString();u=`${o.scopeRefs(Hn.default.scope)}return ${f}`,this.opts.code.process&&(u=this.opts.code.process(u,t));const d=new Function(`${Hn.default.self}`,`${Hn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:d}),d.errors=null,d.schema=t.schema,d.schemaEnv=t,t.$async&&(d.$async=!0),this.opts.code.source===!0&&(d.source={validateName:l,validateCode:f,scopeValues:o._values}),this.opts.unevaluated){const{props:h,items:v}=c;d.evaluated={props:h instanceof Ir.Name?void 0:h,items:v instanceof Ir.Name?void 0:v,dynamicProps:h instanceof Ir.Name,dynamicItems:v instanceof Ir.Name},d.source&&(d.source.evaluated=(0,Ir.stringify)(d.evaluated))}return t.validate=d,t}catch(f){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),f}finally{this._compilations.delete(t)}}Qt.compileSchema=Wl;function Wb(t,e,r){var a;r=(0,xr.resolveUrl)(this.opts.uriResolver,e,r);const n=t.refs[r];if(n)return n;let s=Xb.call(this,t,r);if(s===void 0){const o=(a=t.localRefs)===null||a===void 0?void 0:a[r],{schemaId:i}=this.opts;o&&(s=new jo({schema:o,schemaId:i,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Qb.call(this,s)}Qt.resolveRef=Wb;function Qb(t){return(0,xr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Wl.call(this,t)}function ff(t){for(const e of this._compilations)if(Yb(e,t))return e}Qt.getCompilingSchema=ff;function Yb(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Xb(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Do.call(this,t,e)}function Do(t,e){const r=this.opts.uriResolver.parse(e),a=(0,xr._getFullPath)(this.opts.uriResolver,r);let n=(0,xr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&a===n)return Ql.call(this,r,t);const s=(0,xr.normalizeId)(a),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){const i=Do.call(this,t,o);return typeof(i==null?void 0:i.schema)!="object"?void 0:Ql.call(this,r,i)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Wl.call(this,o),s===(0,xr.normalizeId)(e)){const{schema:i}=o,{schemaId:l}=this.opts,c=i[l];return c&&(n=(0,xr.resolveUrl)(this.opts.uriResolver,n,c)),new jo({schema:i,schemaId:l,root:t,baseId:n})}return Ql.call(this,r,o)}}Qt.resolveSchema=Do;const e1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ql(t,{baseId:e,schema:r,root:a}){var n;if(((n=t.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(const i of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;const l=r[(0,pf.unescapeFragment)(i)];if(l===void 0)return;r=l;const c=typeof r=="object"&&r[this.opts.schemaId];!e1.has(i)&&c&&(e=(0,xr.resolveUrl)(this.opts.uriResolver,e,c))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,pf.schemaHasRulesButRef)(r,this.RULES)){const i=(0,xr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Do.call(this,a,i)}const{schemaId:o}=this.opts;if(s=s||new jo({schema:r,schemaId:o,root:a,baseId:e}),s.schema!==s.root.schema)return s}const t1={$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 Yl={},Lo={exports:{}};const r1=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),hf=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 mf(t){let e="",r=0,a=0;for(a=0;a<t.length;a++)if(r=t[a].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[a];break}for(a+=1;a<t.length;a++){if(r=t[a].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[a]}return e}const n1=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function vf(t){return t.length=0,!0}function a1(t,e,r){if(t.length){const a=mf(t);if(a!=="")e.push(a);else return r.error=!0,!1;t.length=0}return!0}function s1(t){let e=0;const r={error:!1,address:"",zone:""},a=[],n=[];let s=!1,o=!1,i=a1;for(let l=0;l<t.length;l++){const c=t[l];if(!(c==="["||c==="]"))if(c===":"){if(s===!0&&(o=!0),!i(n,a,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(s=!0),a.push(":");continue}else if(c==="%"){if(!i(n,a,r))break;i=vf}else{n.push(c);continue}}return n.length&&(i===vf?r.zone=n.join(""):o?a.push(n.join("")):a.push(mf(n))),r.address=a.join(""),r}function gf(t){if(o1(t,":")<2)return{host:t,isIPV6:!1};const e=s1(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,a=e.address;return e.zone&&(r+="%"+e.zone,a+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:a}}}function o1(t,e){let r=0;for(let a=0;a<t.length;a++)t[a]===e&&r++;return r}function i1(t){let e=t;const r=[];let a=-1,n=0;for(;n=e.length;){if(n===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(n===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(n===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((a=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,a)),e=e.slice(a)}return r.join("")}function l1(t,e){const r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function c1(t){const e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!hf(r)){const a=gf(r);a.isIPV6===!0?r=`[${a.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}var yf={nonSimpleDomain:n1,recomposeAuthority:c1,normalizeComponentEncoding:l1,removeDotSegments:i1,isIPv4:hf,isUUID:r1,normalizeIPv6:gf};const{isUUID:u1}=yf,d1=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function _f(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function wf(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function bf(t){const e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function p1(t){return t.secure=_f(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function f1(t){if((t.port===(_f(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){const[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function h1(t,e){if(!t.path)return t.error="URN can not be parsed",t;const r=t.path.match(d1);if(r){const a=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];const n=`${a}:${e.nid||t.nid}`,s=Xl(n);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function m1(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");const r=e.scheme||t.scheme||"urn",a=t.nid.toLowerCase(),n=`${r}:${e.nid||a}`,s=Xl(n);s&&(t=s.serialize(t,e));const o=t,i=t.nss;return o.path=`${a||e.nid}:${i}`,e.skipEscape=!0,o}function v1(t,e){const r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!u1(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function g1(t){const e=t;return e.nss=(t.uuid||"").toLowerCase(),e}const Ef={scheme:"http",domainHost:!0,parse:wf,serialize:bf},y1={scheme:"https",domainHost:Ef.domainHost,parse:wf,serialize:bf},zo={scheme:"ws",domainHost:!0,parse:p1,serialize:f1},_1={scheme:"wss",domainHost:zo.domainHost,parse:zo.parse,serialize:zo.serialize},Uo={http:Ef,https:y1,ws:zo,wss:_1,urn:{scheme:"urn",parse:h1,serialize:m1,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:v1,serialize:g1,skipNormalize:!0}};Object.setPrototypeOf(Uo,null);function Xl(t){return t&&(Uo[t]||Uo[t.toLowerCase()])||void 0}var w1={SCHEMES:Uo,getSchemeHandler:Xl};const{normalizeIPv6:b1,removeDotSegments:fs,recomposeAuthority:E1,normalizeComponentEncoding:qo,isIPv4:S1,nonSimpleDomain:$1}=yf,{SCHEMES:P1,getSchemeHandler:Sf}=w1;function k1(t,e){return typeof t=="string"?t=Br(fn(t,e),e):typeof t=="object"&&(t=fn(Br(t,e),e)),t}function I1(t,e,r){const a=r?Object.assign({scheme:"null"},r):{scheme:"null"},n=$f(fn(t,a),fn(e,a),a,!0);return a.skipEscape=!0,Br(n,a)}function $f(t,e,r,a){const n={};return a||(t=fn(Br(t,r),r),e=fn(Br(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=fs(e.path||""),n.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=fs(e.path||""),n.query=e.query):(e.path?(e.path[0]==="/"?n.path=fs(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?n.path="/"+e.path:t.path?n.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:n.path=e.path,n.path=fs(n.path)),n.query=e.query):(n.path=t.path,e.query!==void 0?n.query=e.query:n.query=t.query),n.userinfo=t.userinfo,n.host=t.host,n.port=t.port),n.scheme=t.scheme),n.fragment=e.fragment,n}function x1(t,e,r){return typeof t=="string"?(t=unescape(t),t=Br(qo(fn(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Br(qo(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Br(qo(fn(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Br(qo(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Br(t,e){const r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},a=Object.assign({},e),n=[],s=Sf(a.scheme||r.scheme);s&&s.serialize&&s.serialize(r,a),r.path!==void 0&&(a.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),a.reference!=="suffix"&&r.scheme&&n.push(r.scheme,":");const o=E1(r);if(o!==void 0&&(a.reference!=="suffix"&&n.push("//"),n.push(o),r.path&&r.path[0]!=="/"&&n.push("/")),r.path!==void 0){let i=r.path;!a.absolutePath&&(!s||!s.absolutePath)&&(i=fs(i)),o===void 0&&i[0]==="/"&&i[1]==="/"&&(i="/%2F"+i.slice(2)),n.push(i)}return r.query!==void 0&&n.push("?",r.query),r.fragment!==void 0&&n.push("#",r.fragment),n.join("")}const T1=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function fn(t,e){const r=Object.assign({},e),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let n=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);const s=t.match(T1);if(s){if(a.scheme=s[1],a.userinfo=s[3],a.host=s[4],a.port=parseInt(s[5],10),a.path=s[6]||"",a.query=s[7],a.fragment=s[8],isNaN(a.port)&&(a.port=s[5]),a.host)if(S1(a.host)===!1){const l=b1(a.host);a.host=l.host.toLowerCase(),n=l.isIPV6}else n=!0;a.scheme===void 0&&a.userinfo===void 0&&a.host===void 0&&a.port===void 0&&a.query===void 0&&!a.path?a.reference="same-document":a.scheme===void 0?a.reference="relative":a.fragment===void 0?a.reference="absolute":a.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==a.reference&&(a.error=a.error||"URI is not a "+r.reference+" reference.");const o=Sf(r.scheme||a.scheme);if(!r.unicodeSupport&&(!o||!o.unicodeSupport)&&a.host&&(r.domainHost||o&&o.domainHost)&&n===!1&&$1(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(i){a.error=a.error||"Host's domain name can not be converted to ASCII: "+i}(!o||o&&!o.skipNormalize)&&(t.indexOf("%")!==-1&&(a.scheme!==void 0&&(a.scheme=unescape(a.scheme)),a.host!==void 0&&(a.host=unescape(a.host))),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),o&&o.parse&&o.parse(a,r)}else a.error=a.error||"URI can not be parsed.";return a}const ec={SCHEMES:P1,normalize:k1,resolve:I1,resolveComponent:$f,equal:x1,serialize:Br,parse:fn};Lo.exports=ec,Lo.exports.default=ec,Lo.exports.fastUri=ec;var C1=Lo.exports;Object.defineProperty(Yl,"__esModule",{value:!0});const Pf=C1;Pf.code='require("ajv/dist/runtime/uri").default',Yl.default=Pf,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=kr;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Me;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const a=ps,n=Ea,s=Zn,o=Qt,i=Me,l=Lt,c=Tt,u=ie,f=t1,g=Yl,d=(M,R)=>new RegExp(M,R);d.code="new RegExp";const h=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},p={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_=200;function w(M){var R,D,N,y,P,j,Q,ee,Se,de,ge,vt,Te,me,Ne,Ae,ke,tt,Ze,re,ze,Be,Ee,Qe,ir;const Mt=M.strict,wt=(R=M.code)===null||R===void 0?void 0:R.optimize,lr=wt===!0||wt===void 0?1:wt||0,jt=(N=(D=M.code)===null||D===void 0?void 0:D.regExp)!==null&&N!==void 0?N:d,cr=(y=M.uriResolver)!==null&&y!==void 0?y:g.default;return{strictSchema:(j=(P=M.strictSchema)!==null&&P!==void 0?P:Mt)!==null&&j!==void 0?j:!0,strictNumbers:(ee=(Q=M.strictNumbers)!==null&&Q!==void 0?Q:Mt)!==null&&ee!==void 0?ee:!0,strictTypes:(de=(Se=M.strictTypes)!==null&&Se!==void 0?Se:Mt)!==null&&de!==void 0?de:"log",strictTuples:(vt=(ge=M.strictTuples)!==null&&ge!==void 0?ge:Mt)!==null&&vt!==void 0?vt:"log",strictRequired:(me=(Te=M.strictRequired)!==null&&Te!==void 0?Te:Mt)!==null&&me!==void 0?me:!1,code:M.code?{...M.code,optimize:lr,regExp:jt}:{optimize:lr,regExp:jt},loopRequired:(Ne=M.loopRequired)!==null&&Ne!==void 0?Ne:_,loopEnum:(Ae=M.loopEnum)!==null&&Ae!==void 0?Ae:_,meta:(ke=M.meta)!==null&&ke!==void 0?ke:!0,messages:(tt=M.messages)!==null&&tt!==void 0?tt:!0,inlineRefs:(Ze=M.inlineRefs)!==null&&Ze!==void 0?Ze:!0,schemaId:(re=M.schemaId)!==null&&re!==void 0?re:"$id",addUsedSchema:(ze=M.addUsedSchema)!==null&&ze!==void 0?ze:!0,validateSchema:(Be=M.validateSchema)!==null&&Be!==void 0?Be:!0,validateFormats:(Ee=M.validateFormats)!==null&&Ee!==void 0?Ee:!0,unicodeRegExp:(Qe=M.unicodeRegExp)!==null&&Qe!==void 0?Qe:!0,int32range:(ir=M.int32range)!==null&&ir!==void 0?ir:!0,uriResolver:cr}}class b{constructor(R={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,R=this.opts={...R,...w(R)};const{es5:D,lines:N}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:D,lines:N}),this.logger=K(R.logger);const y=R.validateFormats;R.validateFormats=!1,this.RULES=(0,s.getRules)(),S.call(this,m,R,"NOT SUPPORTED"),S.call(this,p,R,"DEPRECATED","warn"),this._metaOpts=H.call(this),R.formats&&A.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),R.keywords&&O.call(this,R.keywords),typeof R.meta=="object"&&this.addMetaSchema(R.meta),k.call(this),R.validateFormats=y}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:R,meta:D,schemaId:N}=this.opts;let y=f;N==="id"&&(y={...f},y.id=y.$id,delete y.$id),D&&R&&this.addMetaSchema(y,y[N],!1)}defaultMeta(){const{meta:R,schemaId:D}=this.opts;return this.opts.defaultMeta=typeof R=="object"?R[D]||R:void 0}validate(R,D){let N;if(typeof R=="string"){if(N=this.getSchema(R),!N)throw new Error(`no schema with key or ref "${R}"`)}else N=this.compile(R);const y=N(D);return"$async"in N||(this.errors=N.errors),y}compile(R,D){const N=this._addSchema(R,D);return N.validate||this._compileSchemaEnv(N)}compileAsync(R,D){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:N}=this.opts;return y.call(this,R,D);async function y(de,ge){await P.call(this,de.$schema);const vt=this._addSchema(de,ge);return vt.validate||j.call(this,vt)}async function P(de){de&&!this.getSchema(de)&&await y.call(this,{$ref:de},!0)}async function j(de){try{return this._compileSchemaEnv(de)}catch(ge){if(!(ge instanceof n.default))throw ge;return Q.call(this,ge),await ee.call(this,ge.missingSchema),j.call(this,de)}}function Q({missingSchema:de,missingRef:ge}){if(this.refs[de])throw new Error(`AnySchema ${de} is loaded but ${ge} cannot be resolved`)}async function ee(de){const ge=await Se.call(this,de);this.refs[de]||await P.call(this,ge.$schema),this.refs[de]||this.addSchema(ge,de,D)}async function Se(de){const ge=this._loading[de];if(ge)return ge;try{return await(this._loading[de]=N(de))}finally{delete this._loading[de]}}}addSchema(R,D,N,y=this.opts.validateSchema){if(Array.isArray(R)){for(const j of R)this.addSchema(j,void 0,N,y);return this}let P;if(typeof R=="object"){const{schemaId:j}=this.opts;if(P=R[j],P!==void 0&&typeof P!="string")throw new Error(`schema ${j} must be string`)}return D=(0,l.normalizeId)(D||P),this._checkUnique(D),this.schemas[D]=this._addSchema(R,N,D,y,!0),this}addMetaSchema(R,D,N=this.opts.validateSchema){return this.addSchema(R,D,!0,N),this}validateSchema(R,D){if(typeof R=="boolean")return!0;let N;if(N=R.$schema,N!==void 0&&typeof N!="string")throw new Error("$schema must be a string");if(N=N||this.opts.defaultMeta||this.defaultMeta(),!N)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const y=this.validate(N,R);if(!y&&D){const P="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(P);else throw new Error(P)}return y}getSchema(R){let D;for(;typeof(D=I.call(this,R))=="string";)R=D;if(D===void 0){const{schemaId:N}=this.opts,y=new o.SchemaEnv({schema:{},schemaId:N});if(D=o.resolveSchema.call(this,y,R),!D)return;this.refs[R]=D}return D.validate||this._compileSchemaEnv(D)}removeSchema(R){if(R instanceof RegExp)return this._removeAllSchemas(this.schemas,R),this._removeAllSchemas(this.refs,R),this;switch(typeof R){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const D=I.call(this,R);return typeof D=="object"&&this._cache.delete(D.schema),delete this.schemas[R],delete this.refs[R],this}case"object":{const D=R;this._cache.delete(D);let N=R[this.opts.schemaId];return N&&(N=(0,l.normalizeId)(N),delete this.schemas[N],delete this.refs[N]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(R){for(const D of R)this.addKeyword(D);return this}addKeyword(R,D){let N;if(typeof R=="string")N=R,typeof D=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),D.keyword=N);else if(typeof R=="object"&&D===void 0){if(D=R,N=D.keyword,Array.isArray(N)&&!N.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(U.call(this,N,D),!D)return(0,u.eachItem)(N,P=>G.call(this,P)),this;ne.call(this,D);const y={...D,type:(0,c.getJSONTypes)(D.type),schemaType:(0,c.getJSONTypes)(D.schemaType)};return(0,u.eachItem)(N,y.type.length===0?P=>G.call(this,P,y):P=>y.type.forEach(j=>G.call(this,P,y,j))),this}getKeyword(R){const D=this.RULES.all[R];return typeof D=="object"?D.definition:!!D}removeKeyword(R){const{RULES:D}=this;delete D.keywords[R],delete D.all[R];for(const N of D.rules){const y=N.rules.findIndex(P=>P.keyword===R);y>=0&&N.rules.splice(y,1)}return this}addFormat(R,D){return typeof D=="string"&&(D=new RegExp(D)),this.formats[R]=D,this}errorsText(R=this.errors,{separator:D=", ",dataVar:N="data"}={}){return!R||R.length===0?"No errors":R.map(y=>`${N}${y.instancePath} ${y.message}`).reduce((y,P)=>y+D+P)}$dataMetaSchema(R,D){const N=this.RULES.all;R=JSON.parse(JSON.stringify(R));for(const y of D){const P=y.split("/").slice(1);let j=R;for(const Q of P)j=j[Q];for(const Q in N){const ee=N[Q];if(typeof ee!="object")continue;const{$data:Se}=ee.definition,de=j[Q];Se&&de&&(j[Q]=pe(de))}}return R}_removeAllSchemas(R,D){for(const N in R){const y=R[N];(!D||D.test(N))&&(typeof y=="string"?delete R[N]:y&&!y.meta&&(this._cache.delete(y.schema),delete R[N]))}}_addSchema(R,D,N,y=this.opts.validateSchema,P=this.opts.addUsedSchema){let j;const{schemaId:Q}=this.opts;if(typeof R=="object")j=R[Q];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof R!="boolean")throw new Error("schema must be object or boolean")}let ee=this._cache.get(R);if(ee!==void 0)return ee;N=(0,l.normalizeId)(j||N);const Se=l.getSchemaRefs.call(this,R,N);return ee=new o.SchemaEnv({schema:R,schemaId:Q,meta:D,baseId:N,localRefs:Se}),this._cache.set(ee.schema,ee),P&&!N.startsWith("#")&&(N&&this._checkUnique(N),this.refs[N]=ee),y&&this.validateSchema(R,!0),ee}_checkUnique(R){if(this.schemas[R]||this.refs[R])throw new Error(`schema with key or id "${R}" already exists`)}_compileSchemaEnv(R){if(R.meta?this._compileMetaSchema(R):o.compileSchema.call(this,R),!R.validate)throw new Error("ajv implementation error");return R.validate}_compileMetaSchema(R){const D=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,R)}finally{this.opts=D}}}b.ValidationError=a.default,b.MissingRefError=n.default,t.default=b;function S(M,R,D,N="error"){for(const y in M){const P=y;P in R&&this.logger[N](`${D}: option ${y}. ${M[P]}`)}}function I(M){return M=(0,l.normalizeId)(M),this.schemas[M]||this.refs[M]}function k(){const M=this.opts.schemas;if(M)if(Array.isArray(M))this.addSchema(M);else for(const R in M)this.addSchema(M[R],R)}function A(){for(const M in this.opts.formats){const R=this.opts.formats[M];R&&this.addFormat(M,R)}}function O(M){if(Array.isArray(M)){this.addVocabulary(M);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const R in M){const D=M[R];D.keyword||(D.keyword=R),this.addKeyword(D)}}function H(){const M={...this.opts};for(const R of h)delete M[R];return M}const J={log(){},warn(){},error(){}};function K(M){if(M===!1)return J;if(M===void 0)return console;if(M.log&&M.warn&&M.error)return M;throw new Error("logger must implement log, warn and error methods")}const z=/^[a-z_$][a-z0-9_$:-]*$/i;function U(M,R){const{RULES:D}=this;if((0,u.eachItem)(M,N=>{if(D.keywords[N])throw new Error(`Keyword ${N} is already defined`);if(!z.test(N))throw new Error(`Keyword ${N} has invalid name`)}),!!R&&R.$data&&!("code"in R||"validate"in R))throw new Error('$data keyword must have "code" or "validate" function')}function G(M,R,D){var N;const y=R==null?void 0:R.post;if(D&&y)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:P}=this;let j=y?P.post:P.rules.find(({type:ee})=>ee===D);if(j||(j={type:D,rules:[]},P.rules.push(j)),P.keywords[M]=!0,!R)return;const Q={keyword:M,definition:{...R,type:(0,c.getJSONTypes)(R.type),schemaType:(0,c.getJSONTypes)(R.schemaType)}};R.before?se.call(this,j,Q,R.before):j.rules.push(Q),P.all[M]=Q,(N=R.implements)===null||N===void 0||N.forEach(ee=>this.addKeyword(ee))}function se(M,R,D){const N=M.rules.findIndex(y=>y.keyword===D);N>=0?M.rules.splice(N,0,R):(M.rules.push(R),this.logger.warn(`rule ${D} is not defined`))}function ne(M){let{metaSchema:R}=M;R!==void 0&&(M.$data&&this.opts.$data&&(R=pe(R)),M.validateSchema=this.compile(R,!0))}const ce={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pe(M){return{anyOf:[M,ce]}}}(kp);var tc={},rc={},nc={};Object.defineProperty(nc,"__esModule",{value:!0});const R1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};nc.default=R1;var Bn={};Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.callRef=Bn.getValidate=void 0;const O1=Ea,kf=je,Yt=Me,Sa=Zr,If=Qt,Fo=ie,N1={keyword:"$ref",schemaType:"string",code(t){const{gen:e,schema:r,it:a}=t,{baseId:n,schemaEnv:s,validateName:o,opts:i,self:l}=a,{root:c}=s;if((r==="#"||r==="#/")&&n===c.baseId)return f();const u=If.resolveRef.call(l,c,n,r);if(u===void 0)throw new O1.default(a.opts.uriResolver,n,r);if(u instanceof If.SchemaEnv)return g(u);return d(u);function f(){if(s===c)return Zo(t,o,s,s.$async);const h=e.scopeValue("root",{ref:c});return Zo(t,(0,Yt._)`${h}.validate`,c,c.$async)}function g(h){const v=xf(t,h);Zo(t,v,h,h.$async)}function d(h){const v=e.scopeValue("schema",i.code.source===!0?{ref:h,code:(0,Yt.stringify)(h)}:{ref:h}),m=e.name("valid"),p=t.subschema({schema:h,dataTypes:[],schemaPath:Yt.nil,topSchemaRef:v,errSchemaPath:r},m);t.mergeEvaluated(p),t.ok(m)}}};function xf(t,e){const{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Yt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Bn.getValidate=xf;function Zo(t,e,r,a){const{gen:n,it:s}=t,{allErrors:o,schemaEnv:i,opts:l}=s,c=l.passContext?Sa.default.this:Yt.nil;a?u():f();function u(){if(!i.$async)throw new Error("async schema referenced by sync schema");const h=n.let("valid");n.try(()=>{n.code((0,Yt._)`await ${(0,kf.callValidateCode)(t,e,c)}`),d(e),o||n.assign(h,!0)},v=>{n.if((0,Yt._)`!(${v} instanceof ${s.ValidationError})`,()=>n.throw(v)),g(v),o||n.assign(h,!1)}),t.ok(h)}function f(){t.result((0,kf.callValidateCode)(t,e,c),()=>d(e),()=>g(e))}function g(h){const v=(0,Yt._)`${h}.errors`;n.assign(Sa.default.vErrors,(0,Yt._)`${Sa.default.vErrors} === null ? ${v} : ${Sa.default.vErrors}.concat(${v})`),n.assign(Sa.default.errors,(0,Yt._)`${Sa.default.vErrors}.length`)}function d(h){var v;if(!s.opts.unevaluated)return;const m=(v=r==null?void 0:r.validate)===null||v===void 0?void 0:v.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=Fo.mergeEvaluated.props(n,m.props,s.props));else{const p=n.var("props",(0,Yt._)`${h}.evaluated.props`);s.props=Fo.mergeEvaluated.props(n,p,s.props,Yt.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=Fo.mergeEvaluated.items(n,m.items,s.items));else{const p=n.var("items",(0,Yt._)`${h}.evaluated.items`);s.items=Fo.mergeEvaluated.items(n,p,s.items,Yt.Name)}}}Bn.callRef=Zo,Bn.default=N1,Object.defineProperty(rc,"__esModule",{value:!0});const A1=nc,M1=Bn,j1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",A1.default,M1.default];rc.default=j1;var ac={},sc={};Object.defineProperty(sc,"__esModule",{value:!0});const Vo=Me,kn=Vo.operators,Ho={maximum:{okStr:"<=",ok:kn.LTE,fail:kn.GT},minimum:{okStr:">=",ok:kn.GTE,fail:kn.LT},exclusiveMaximum:{okStr:"<",ok:kn.LT,fail:kn.GTE},exclusiveMinimum:{okStr:">",ok:kn.GT,fail:kn.LTE}},D1={message:({keyword:t,schemaCode:e})=>(0,Vo.str)`must be ${Ho[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Vo._)`{comparison: ${Ho[t].okStr}, limit: ${e}}`},L1={keyword:Object.keys(Ho),type:"number",schemaType:"number",$data:!0,error:D1,code(t){const{keyword:e,data:r,schemaCode:a}=t;t.fail$data((0,Vo._)`${r} ${Ho[e].fail} ${a} || isNaN(${r})`)}};sc.default=L1;var oc={};Object.defineProperty(oc,"__esModule",{value:!0});const hs=Me,z1={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>(0,hs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,hs._)`{multipleOf: ${t}}`},code(t){const{gen:e,data:r,schemaCode:a,it:n}=t,s=n.opts.multipleOfPrecision,o=e.let("res"),i=s?(0,hs._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,hs._)`${o} !== parseInt(${o})`;t.fail$data((0,hs._)`(${a} === 0 || (${o} = ${r}/${a}, ${i}))`)}};oc.default=z1;var ic={},lc={};Object.defineProperty(lc,"__esModule",{value:!0});function Tf(t){const e=t.length;let r=0,a=0,n;for(;a<e;)r++,n=t.charCodeAt(a++),n>=55296&&n<=56319&&a<e&&(n=t.charCodeAt(a),(n&64512)===56320&&a++);return r}lc.default=Tf,Tf.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(ic,"__esModule",{value:!0});const Jn=Me,U1=ie,q1=lc,F1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:t,schemaCode:e}){const r=t==="maxLength"?"more":"fewer";return(0,Jn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Jn._)`{limit: ${t}}`},code(t){const{keyword:e,data:r,schemaCode:a,it:n}=t,s=e==="maxLength"?Jn.operators.GT:Jn.operators.LT,o=n.opts.unicode===!1?(0,Jn._)`${r}.length`:(0,Jn._)`${(0,U1.useFunc)(t.gen,q1.default)}(${r})`;t.fail$data((0,Jn._)`${o} ${s} ${a}`)}};ic.default=F1;var cc={};Object.defineProperty(cc,"__esModule",{value:!0});const Z1=je,Bo=Me,V1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>(0,Bo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Bo._)`{pattern: ${t}}`},code(t){const{data:e,$data:r,schema:a,schemaCode:n,it:s}=t,o=s.opts.unicodeRegExp?"u":"",i=r?(0,Bo._)`(new RegExp(${n}, ${o}))`:(0,Z1.usePattern)(t,a);t.fail$data((0,Bo._)`!${i}.test(${e})`)}};cc.default=V1;var uc={};Object.defineProperty(uc,"__esModule",{value:!0});const ms=Me,H1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:t,schemaCode:e}){const r=t==="maxProperties"?"more":"fewer";return(0,ms.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ms._)`{limit: ${t}}`},code(t){const{keyword:e,data:r,schemaCode:a}=t,n=e==="maxProperties"?ms.operators.GT:ms.operators.LT;t.fail$data((0,ms._)`Object.keys(${r}).length ${n} ${a}`)}};uc.default=H1;var dc={};Object.defineProperty(dc,"__esModule",{value:!0});const vs=je,gs=Me,B1=ie,J1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:t}})=>(0,gs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,gs._)`{missingProperty: ${t}}`},code(t){const{gen:e,schema:r,schemaCode:a,data:n,$data:s,it:o}=t,{opts:i}=o;if(!s&&r.length===0)return;const l=r.length>=i.loopRequired;if(o.allErrors?c():u(),i.strictRequired){const d=t.parentSchema.properties,{definedProperties:h}=t.it;for(const v of r)if((d==null?void 0:d[v])===void 0&&!h.has(v)){const m=o.schemaEnv.baseId+o.errSchemaPath,p=`required property "${v}" is not defined at "${m}" (strictRequired)`;(0,B1.checkStrictMode)(o,p,o.opts.strictRequired)}}function c(){if(l||s)t.block$data(gs.nil,f);else for(const d of r)(0,vs.checkReportMissingProp)(t,d)}function u(){const d=e.let("missing");if(l||s){const h=e.let("valid",!0);t.block$data(h,()=>g(d,h)),t.ok(h)}else e.if((0,vs.checkMissingProp)(t,r,d)),(0,vs.reportMissingProp)(t,d),e.else()}function f(){e.forOf("prop",a,d=>{t.setParams({missingProperty:d}),e.if((0,vs.noPropertyInData)(e,n,d,i.ownProperties),()=>t.error())})}function g(d,h){t.setParams({missingProperty:d}),e.forOf(d,a,()=>{e.assign(h,(0,vs.propertyInData)(e,n,d,i.ownProperties)),e.if((0,gs.not)(h),()=>{t.error(),e.break()})},gs.nil)}}};dc.default=J1;var pc={};Object.defineProperty(pc,"__esModule",{value:!0});const ys=Me,G1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:t,schemaCode:e}){const r=t==="maxItems"?"more":"fewer";return(0,ys.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ys._)`{limit: ${t}}`},code(t){const{keyword:e,data:r,schemaCode:a}=t,n=e==="maxItems"?ys.operators.GT:ys.operators.LT;t.fail$data((0,ys._)`${r}.length ${n} ${a}`)}};pc.default=G1;var fc={},_s={};Object.defineProperty(_s,"__esModule",{value:!0});const Cf=cs;Cf.code='require("ajv/dist/runtime/equal").default',_s.default=Cf,Object.defineProperty(fc,"__esModule",{value:!0});const hc=Tt,zt=Me,K1=ie,W1=_s,Q1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:t,j:e}})=>(0,zt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,zt._)`{i: ${t}, j: ${e}}`},code(t){const{gen:e,data:r,$data:a,schema:n,parentSchema:s,schemaCode:o,it:i}=t;if(!a&&!n)return;const l=e.let("valid"),c=s.items?(0,hc.getSchemaTypes)(s.items):[];t.block$data(l,u,(0,zt._)`${o} === false`),t.ok(l);function u(){const h=e.let("i",(0,zt._)`${r}.length`),v=e.let("j");t.setParams({i:h,j:v}),e.assign(l,!0),e.if((0,zt._)`${h} > 1`,()=>(f()?g:d)(h,v))}function f(){return c.length>0&&!c.some(h=>h==="object"||h==="array")}function g(h,v){const m=e.name("item"),p=(0,hc.checkDataTypes)(c,m,i.opts.strictNumbers,hc.DataType.Wrong),_=e.const("indices",(0,zt._)`{}`);e.for((0,zt._)`;${h}--;`,()=>{e.let(m,(0,zt._)`${r}[${h}]`),e.if(p,(0,zt._)`continue`),c.length>1&&e.if((0,zt._)`typeof ${m} == "string"`,(0,zt._)`${m} += "_"`),e.if((0,zt._)`typeof ${_}[${m}] == "number"`,()=>{e.assign(v,(0,zt._)`${_}[${m}]`),t.error(),e.assign(l,!1).break()}).code((0,zt._)`${_}[${m}] = ${h}`)})}function d(h,v){const m=(0,K1.useFunc)(e,W1.default),p=e.name("outer");e.label(p).for((0,zt._)`;${h}--;`,()=>e.for((0,zt._)`${v} = ${h}; ${v}--;`,()=>e.if((0,zt._)`${m}(${r}[${h}], ${r}[${v}])`,()=>{t.error(),e.assign(l,!1).break(p)})))}}};fc.default=Q1;var mc={};Object.defineProperty(mc,"__esModule",{value:!0});const vc=Me,Y1=ie,X1=_s,eE={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>(0,vc._)`{allowedValue: ${t}}`},code(t){const{gen:e,data:r,$data:a,schemaCode:n,schema:s}=t;a||s&&typeof s=="object"?t.fail$data((0,vc._)`!${(0,Y1.useFunc)(e,X1.default)}(${r}, ${n})`):t.fail((0,vc._)`${s} !== ${r}`)}};mc.default=eE;var gc={};Object.defineProperty(gc,"__esModule",{value:!0});const ws=Me,tE=ie,rE=_s,nE={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ws._)`{allowedValues: ${t}}`},code(t){const{gen:e,data:r,$data:a,schema:n,schemaCode:s,it:o}=t;if(!a&&n.length===0)throw new Error("enum must have non-empty array");const i=n.length>=o.opts.loopEnum;let l;const c=()=>l??(l=(0,tE.useFunc)(e,rE.default));let u;if(i||a)u=e.let("valid"),t.block$data(u,f);else{if(!Array.isArray(n))throw new Error("ajv implementation error");const d=e.const("vSchema",s);u=(0,ws.or)(...n.map((h,v)=>g(d,v)))}t.pass(u);function f(){e.assign(u,!1),e.forOf("v",s,d=>e.if((0,ws._)`${c()}(${r}, ${d})`,()=>e.assign(u,!0).break()))}function g(d,h){const v=n[h];return typeof v=="object"&&v!==null?(0,ws._)`${c()}(${r}, ${d}[${h}])`:(0,ws._)`${r} === ${v}`}}};gc.default=nE,Object.defineProperty(ac,"__esModule",{value:!0});const aE=sc,sE=oc,oE=ic,iE=cc,lE=uc,cE=dc,uE=pc,dE=fc,pE=mc,fE=gc,hE=[aE.default,sE.default,oE.default,iE.default,lE.default,cE.default,uE.default,dE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},pE.default,fE.default];ac.default=hE;var yc={},$a={};Object.defineProperty($a,"__esModule",{value:!0}),$a.validateAdditionalItems=void 0;const Gn=Me,_c=ie,mE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>(0,Gn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Gn._)`{limit: ${t}}`},code(t){const{parentSchema:e,it:r}=t,{items:a}=e;if(!Array.isArray(a)){(0,_c.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Rf(t,a)}};function Rf(t,e){const{gen:r,schema:a,data:n,keyword:s,it:o}=t;o.items=!0;const i=r.const("len",(0,Gn._)`${n}.length`);if(a===!1)t.setParams({len:e.length}),t.pass((0,Gn._)`${i} <= ${e.length}`);else if(typeof a=="object"&&!(0,_c.alwaysValidSchema)(o,a)){const c=r.var("valid",(0,Gn._)`${i} <= ${e.length}`);r.if((0,Gn.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,i,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:_c.Type.Num},c),o.allErrors||r.if((0,Gn.not)(c),()=>r.break())})}}$a.validateAdditionalItems=Rf,$a.default=mE;var wc={},Pa={};Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.validateTuple=void 0;const Of=Me,Jo=ie,vE=je,gE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){const{schema:e,it:r}=t;if(Array.isArray(e))return Nf(t,"additionalItems",e);r.items=!0,!(0,Jo.alwaysValidSchema)(r,e)&&t.ok((0,vE.validateArray)(t))}};function Nf(t,e,r=t.schema){const{gen:a,parentSchema:n,data:s,keyword:o,it:i}=t;u(n),i.opts.unevaluated&&r.length&&i.items!==!0&&(i.items=Jo.mergeEvaluated.items(a,r.length,i.items));const l=a.name("valid"),c=a.const("len",(0,Of._)`${s}.length`);r.forEach((f,g)=>{(0,Jo.alwaysValidSchema)(i,f)||(a.if((0,Of._)`${c} > ${g}`,()=>t.subschema({keyword:o,schemaProp:g,dataProp:g},l)),t.ok(l))});function u(f){const{opts:g,errSchemaPath:d}=i,h=r.length,v=h===f.minItems&&(h===f.maxItems||f[e]===!1);if(g.strictTuples&&!v){const m=`"${o}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${d}"`;(0,Jo.checkStrictMode)(i,m,g.strictTuples)}}}Pa.validateTuple=Nf,Pa.default=gE,Object.defineProperty(wc,"__esModule",{value:!0});const yE=Pa,_E={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,yE.validateTuple)(t,"items")};wc.default=_E;var bc={};Object.defineProperty(bc,"__esModule",{value:!0});const Af=Me,wE=ie,bE=je,EE=$a,SE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>(0,Af.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Af._)`{limit: ${t}}`},code(t){const{schema:e,parentSchema:r,it:a}=t,{prefixItems:n}=r;a.items=!0,!(0,wE.alwaysValidSchema)(a,e)&&(n?(0,EE.validateAdditionalItems)(t,n):t.ok((0,bE.validateArray)(t)))}};bc.default=SE;var Ec={};Object.defineProperty(Ec,"__esModule",{value:!0});const vr=Me,Go=ie,$E={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:e}})=>e===void 0?(0,vr.str)`must contain at least ${t} valid item(s)`:(0,vr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,vr._)`{minContains: ${t}}`:(0,vr._)`{minContains: ${t}, maxContains: ${e}}`},code(t){const{gen:e,schema:r,parentSchema:a,data:n,it:s}=t;let o,i;const{minContains:l,maxContains:c}=a;s.opts.next?(o=l===void 0?1:l,i=c):o=1;const u=e.const("len",(0,vr._)`${n}.length`);if(t.setParams({min:o,max:i}),i===void 0&&o===0){(0,Go.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(i!==void 0&&o>i){(0,Go.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Go.alwaysValidSchema)(s,r)){let v=(0,vr._)`${u} >= ${o}`;i!==void 0&&(v=(0,vr._)`${v} && ${u} <= ${i}`),t.pass(v);return}s.items=!0;const f=e.name("valid");i===void 0&&o===1?d(f,()=>e.if(f,()=>e.break())):o===0?(e.let(f,!0),i!==void 0&&e.if((0,vr._)`${n}.length > 0`,g)):(e.let(f,!1),g()),t.result(f,()=>t.reset());function g(){const v=e.name("_valid"),m=e.let("count",0);d(v,()=>e.if(v,()=>h(m)))}function d(v,m){e.forRange("i",0,u,p=>{t.subschema({keyword:"contains",dataProp:p,dataPropType:Go.Type.Num,compositeRule:!0},v),m()})}function h(v){e.code((0,vr._)`${v}++`),i===void 0?e.if((0,vr._)`${v} >= ${o}`,()=>e.assign(f,!0).break()):(e.if((0,vr._)`${v} > ${i}`,()=>e.assign(f,!1).break()),o===1?e.assign(f,!0):e.if((0,vr._)`${v} >= ${o}`,()=>e.assign(f,!0)))}}};Ec.default=$E;var Mf={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=Me,r=ie,a=je;t.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const f=c===1?"property":"properties";return(0,e.str)`must have ${f} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:f}})=>(0,e._)`{property: ${l},
6
- missingProperty: ${f},
5
+ || ${o} === "boolean" || ${n} === null`).assign(i,(0,Re._)`[${n}]`)}}}function Jw({gen:t,parentData:e,parentDataProperty:r},a){t.if((0,Re._)`${e} !== undefined`,()=>t.assign((0,Re._)`${e}[${r}]`,a))}function Il(t,e,r,a=pa.Correct){const n=a===pa.Correct?Re.operators.EQ:Re.operators.NEQ;let s;switch(t){case"null":return(0,Re._)`${e} ${n} null`;case"array":s=(0,Re._)`Array.isArray(${e})`;break;case"object":s=(0,Re._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,Re._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,Re._)`typeof ${e} ${n} ${t}`}return a===pa.Correct?s:(0,Re.not)(s);function o(i=Re.nil){return(0,Re.and)((0,Re._)`typeof ${e} == "number"`,i,r?(0,Re._)`isFinite(${e})`:Re.nil)}}Tt.checkDataType=Il;function Cl(t,e,r,a){if(t.length===1)return Il(t[0],e,r,a);let n;const s=(0,Lf.toHash)(t);if(s.array&&s.object){const o=(0,Re._)`typeof ${e} != "object"`;n=s.null?o:(0,Re._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else n=Re.nil;s.number&&delete s.integer;for(const o in s)n=(0,Re.and)(n,Il(o,e,r,a));return n}Tt.checkDataTypes=Cl;const Gw={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Re._)`{type: ${t}}`:(0,Re._)`{type: ${e}}`};function Rl(t){const e=Kw(t);(0,Fw.reportError)(e,Gw)}Tt.reportTypeError=Rl;function Kw(t){const{gen:e,data:r,schema:a}=t,n=(0,Lf.schemaRefOrVal)(t,a,"type");return{gen:e,keyword:"type",data:r,schema:a.type,schemaCode:n,schemaValue:n,parentSchema:a,params:{},it:t}}var ko={};Object.defineProperty(ko,"__esModule",{value:!0}),ko.assignDefaults=void 0;const ha=Me,Ww=se;function Qw(t,e){const{properties:r,items:a}=t.schema;if(e==="object"&&r)for(const n in r)qf(t,n,r[n].default);else e==="array"&&Array.isArray(a)&&a.forEach((n,s)=>qf(t,s,n.default))}ko.assignDefaults=Qw;function qf(t,e,r){const{gen:a,compositeRule:n,data:s,opts:o}=t;if(r===void 0)return;const i=(0,ha._)`${s}${(0,ha.getProperty)(e)}`;if(n){(0,Ww.checkStrictMode)(t,`default is ignored for: ${i}`);return}let l=(0,ha._)`${i} === undefined`;o.useDefaults==="empty"&&(l=(0,ha._)`${l} || ${i} === null || ${i} === ""`),a.if(l,(0,ha._)`${i} = ${(0,ha.stringify)(r)}`)}var Mr={},je={};Object.defineProperty(je,"__esModule",{value:!0}),je.validateUnion=je.validateArray=je.usePattern=je.callValidateCode=je.schemaProperties=je.allSchemaProperties=je.noPropertyInData=je.propertyInData=je.isOwnProperty=je.hasPropFunc=je.reportMissingProp=je.checkMissingProp=je.checkReportMissingProp=void 0;const at=Me,Ol=se,pn=Nr,Yw=se;function Xw(t,e){const{gen:r,data:a,it:n}=t;r.if(Nl(r,a,e,n.opts.ownProperties),()=>{t.setParams({missingProperty:(0,at._)`${e}`},!0),t.error()})}je.checkReportMissingProp=Xw;function eb({gen:t,data:e,it:{opts:r}},a,n){return(0,at.or)(...a.map(s=>(0,at.and)(Nl(t,e,s,r.ownProperties),(0,at._)`${n} = ${s}`)))}je.checkMissingProp=eb;function tb(t,e){t.setParams({missingProperty:e},!0),t.error()}je.reportMissingProp=tb;function Ff(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,at._)`Object.prototype.hasOwnProperty`})}je.hasPropFunc=Ff;function Al(t,e,r){return(0,at._)`${Ff(t)}.call(${e}, ${r})`}je.isOwnProperty=Al;function rb(t,e,r,a){const n=(0,at._)`${e}${(0,at.getProperty)(r)} !== undefined`;return a?(0,at._)`${n} && ${Al(t,e,r)}`:n}je.propertyInData=rb;function Nl(t,e,r,a){const n=(0,at._)`${e}${(0,at.getProperty)(r)} === undefined`;return a?(0,at.or)(n,(0,at.not)(Al(t,e,r))):n}je.noPropertyInData=Nl;function Zf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}je.allSchemaProperties=Zf;function nb(t,e){return Zf(e).filter(r=>!(0,Ol.alwaysValidSchema)(t,e[r]))}je.schemaProperties=nb;function ab({schemaCode:t,data:e,it:{gen:r,topSchemaRef:a,schemaPath:n,errorPath:s},it:o},i,l,c){const u=c?(0,at._)`${t}, ${e}, ${a}${n}`:e,h=[[pn.default.instancePath,(0,at.strConcat)(pn.default.instancePath,s)],[pn.default.parentData,o.parentData],[pn.default.parentDataProperty,o.parentDataProperty],[pn.default.rootData,pn.default.rootData]];o.opts.dynamicRef&&h.push([pn.default.dynamicAnchors,pn.default.dynamicAnchors]);const g=(0,at._)`${u}, ${r.object(...h)}`;return l!==at.nil?(0,at._)`${i}.call(${l}, ${g})`:(0,at._)`${i}(${g})`}je.callValidateCode=ab;const sb=(0,at._)`new RegExp`;function ob({gen:t,it:{opts:e}},r){const a=e.unicodeRegExp?"u":"",{regExp:n}=e.code,s=n(r,a);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,at._)`${n.code==="new RegExp"?sb:(0,Yw.useFunc)(t,n)}(${r}, ${a})`})}je.usePattern=ob;function ib(t){const{gen:e,data:r,keyword:a,it:n}=t,s=e.name("valid");if(n.allErrors){const i=e.let("valid",!0);return o(()=>e.assign(i,!1)),i}return e.var(s,!0),o(()=>e.break()),s;function o(i){const l=e.const("len",(0,at._)`${r}.length`);e.forRange("i",0,l,c=>{t.subschema({keyword:a,dataProp:c,dataPropType:Ol.Type.Num},s),e.if((0,at.not)(s),i)})}}je.validateArray=ib;function lb(t){const{gen:e,schema:r,keyword:a,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Ol.alwaysValidSchema)(n,l))&&!n.opts.unevaluated)return;const o=e.let("valid",!1),i=e.name("_valid");e.block(()=>r.forEach((l,c)=>{const u=t.subschema({keyword:a,schemaProp:c,compositeRule:!0},i);e.assign(o,(0,at._)`${o} || ${i}`),t.mergeValidEvaluated(u,i)||e.if((0,at.not)(o))})),t.result(o,()=>t.reset(),()=>t.error(!0))}je.validateUnion=lb,Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.validateKeywordUsage=Mr.validSchemaType=Mr.funcKeywordCode=Mr.macroKeywordCode=void 0;const Ut=Me,Dn=Nr,cb=je,ub=ts;function db(t,e){const{gen:r,keyword:a,schema:n,parentSchema:s,it:o}=t,i=e.macro.call(o.self,n,s,o),l=Hf(r,a,i);o.opts.validateSchema!==!1&&o.self.validateSchema(i,!0);const c=r.name("valid");t.subschema({schema:i,schemaPath:Ut.nil,errSchemaPath:`${o.errSchemaPath}/${a}`,topSchemaRef:l,compositeRule:!0},c),t.pass(c,()=>t.error(!0))}Mr.macroKeywordCode=db;function fb(t,e){var r;const{gen:a,keyword:n,schema:s,parentSchema:o,$data:i,it:l}=t;hb(l,e);const c=!i&&e.compile?e.compile.call(l.self,s,o,l):e.validate,u=Hf(a,n,c),h=a.let("valid");t.block$data(h,g),t.ok((r=e.valid)!==null&&r!==void 0?r:h);function g(){if(e.errors===!1)v(),e.modifying&&Vf(t),m(()=>t.error());else{const p=e.async?d():f();e.modifying&&Vf(t),m(()=>pb(t,p))}}function d(){const p=a.let("ruleErrs",null);return a.try(()=>v((0,Ut._)`await `),y=>a.assign(h,!1).if((0,Ut._)`${y} instanceof ${l.ValidationError}`,()=>a.assign(p,(0,Ut._)`${y}.errors`),()=>a.throw(y))),p}function f(){const p=(0,Ut._)`${u}.errors`;return a.assign(p,null),v(Ut.nil),p}function v(p=e.async?(0,Ut._)`await `:Ut.nil){const y=l.opts.passContext?Dn.default.this:Dn.default.self,_=!("compile"in e&&!i||e.schema===!1);a.assign(h,(0,Ut._)`${p}${(0,cb.callValidateCode)(t,u,y,_)}`,e.modifying)}function m(p){var y;a.if((0,Ut.not)((y=e.valid)!==null&&y!==void 0?y:h),p)}}Mr.funcKeywordCode=fb;function Vf(t){const{gen:e,data:r,it:a}=t;e.if(a.parentData,()=>e.assign(r,(0,Ut._)`${a.parentData}[${a.parentDataProperty}]`))}function pb(t,e){const{gen:r}=t;r.if((0,Ut._)`Array.isArray(${e})`,()=>{r.assign(Dn.default.vErrors,(0,Ut._)`${Dn.default.vErrors} === null ? ${e} : ${Dn.default.vErrors}.concat(${e})`).assign(Dn.default.errors,(0,Ut._)`${Dn.default.vErrors}.length`),(0,ub.extendErrors)(t)},()=>t.error())}function hb({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Hf(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ut.stringify)(r)})}function mb(t,e,r=!1){return!e.length||e.some(a=>a==="array"?Array.isArray(t):a==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==a||r&&typeof t>"u")}Mr.validSchemaType=mb;function vb({schema:t,opts:e,self:r,errSchemaPath:a},n,s){if(Array.isArray(n.keyword)?!n.keyword.includes(s):n.keyword!==s)throw new Error("ajv implementation error");const o=n.dependencies;if(o!=null&&o.some(i=>!Object.prototype.hasOwnProperty.call(t,i)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(n.validateSchema&&!n.validateSchema(t[s])){const l=`keyword "${s}" value is invalid at path "${a}": `+r.errorsText(n.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Mr.validateKeywordUsage=vb;var hn={};Object.defineProperty(hn,"__esModule",{value:!0}),hn.extendSubschemaMode=hn.extendSubschemaData=hn.getSubschema=void 0;const jr=Me,Bf=se;function gb(t,{keyword:e,schemaProp:r,schema:a,schemaPath:n,errSchemaPath:s,topSchemaRef:o}){if(e!==void 0&&a!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const i=t.schema[e];return r===void 0?{schema:i,schemaPath:(0,jr._)`${t.schemaPath}${(0,jr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:i[r],schemaPath:(0,jr._)`${t.schemaPath}${(0,jr.getProperty)(e)}${(0,jr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Bf.escapeFragment)(r)}`}}if(a!==void 0){if(n===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:n,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}hn.getSubschema=gb;function yb(t,e,{dataProp:r,dataPropType:a,data:n,dataTypes:s,propertyName:o}){if(n!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:i}=e;if(r!==void 0){const{errorPath:c,dataPathArr:u,opts:h}=e,g=i.let("data",(0,jr._)`${e.data}${(0,jr.getProperty)(r)}`,!0);l(g),t.errorPath=(0,jr.str)`${c}${(0,Bf.getErrorPath)(r,a,h.jsPropertySyntax)}`,t.parentDataProperty=(0,jr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(n!==void 0){const c=n instanceof jr.Name?n:i.let("data",n,!0);l(c),o!==void 0&&(t.propertyName=o)}s&&(t.dataTypes=s);function l(c){t.data=c,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,c]}}hn.extendSubschemaData=yb;function _b(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:a,createErrors:n,allErrors:s}){a!==void 0&&(t.compositeRule=a),n!==void 0&&(t.createErrors=n),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}hn.extendSubschemaMode=_b;var At={},ns=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var a,n,s;if(Array.isArray(e)){if(a=e.length,a!=r.length)return!1;for(n=a;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),a=s.length,a!==Object.keys(r).length)return!1;for(n=a;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=a;n--!==0;){var o=s[n];if(!t(e[o],r[o]))return!1}return!0}return e!==e&&r!==r},Jf={exports:{}},mn=Jf.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};Io(e,a,n,t,"",t)};mn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},mn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},mn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},mn.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 Io(t,e,r,a,n,s,o,i,l,c){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,n,s,o,i,l,c);for(var u in a){var h=a[u];if(Array.isArray(h)){if(u in mn.arrayKeywords)for(var g=0;g<h.length;g++)Io(t,e,r,h[g],n+"/"+u+"/"+g,s,n,u,a,g)}else if(u in mn.propsKeywords){if(h&&typeof h=="object")for(var d in h)Io(t,e,r,h[d],n+"/"+u+"/"+wb(d),s,n,u,a,d)}else(u in mn.keywords||t.allKeys&&!(u in mn.skipKeywords))&&Io(t,e,r,h,n+"/"+u,s,n,u,a)}r(a,n,s,o,i,l,c)}}function wb(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var bb=Jf.exports;Object.defineProperty(At,"__esModule",{value:!0}),At.getSchemaRefs=At.resolveUrl=At.normalizeId=At._getFullPath=At.getFullPath=At.inlineRef=void 0;const Eb=se,$b=ns,Sb=bb,Pb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Tb(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ml(t):e?Gf(t)<=e:!1}At.inlineRef=Tb;const xb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ml(t){for(const e in t){if(xb.has(e))return!0;const r=t[e];if(Array.isArray(r)&&r.some(Ml)||typeof r=="object"&&Ml(r))return!0}return!1}function Gf(t){let e=0;for(const r in t){if(r==="$ref")return 1/0;if(e++,!Pb.has(r)&&(typeof t[r]=="object"&&(0,Eb.eachItem)(t[r],a=>e+=Gf(a)),e===1/0))return 1/0}return e}function Kf(t,e="",r){r!==!1&&(e=ma(e));const a=t.parse(e);return Wf(t,a)}At.getFullPath=Kf;function Wf(t,e){return t.serialize(e).split("#")[0]+"#"}At._getFullPath=Wf;const kb=/#\/?$/;function ma(t){return t?t.replace(kb,""):""}At.normalizeId=ma;function Ib(t,e,r){return r=ma(r),t.resolve(e,r)}At.resolveUrl=Ib;const Cb=/^[a-z_][-a-z0-9._]*$/i;function Rb(t,e){if(typeof t=="boolean")return{};const{schemaId:r,uriResolver:a}=this.opts,n=ma(t[r]||e),s={"":n},o=Kf(a,n,!1),i={},l=new Set;return Sb(t,{allKeys:!0},(h,g,d,f)=>{if(f===void 0)return;const v=o+g;let m=s[f];typeof h[r]=="string"&&(m=p.call(this,h[r])),y.call(this,h.$anchor),y.call(this,h.$dynamicAnchor),s[g]=m;function p(_){const w=this.opts.uriResolver.resolve;if(_=ma(m?w(m,_):_),l.has(_))throw u(_);l.add(_);let E=this.refs[_];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?c(h,E.schema,_):_!==ma(v)&&(_[0]==="#"?(c(h,i[_],_),i[_]=h):this.refs[_]=v),_}function y(_){if(typeof _=="string"){if(!Cb.test(_))throw new Error(`invalid anchor "${_}"`);p.call(this,`#${_}`)}}}),i;function c(h,g,d){if(g!==void 0&&!$b(h,g))throw u(d)}function u(h){return new Error(`reference "${h}" resolves to more than one schema`)}}At.getSchemaRefs=Rb,Object.defineProperty(wr,"__esModule",{value:!0}),wr.getData=wr.KeywordCxt=wr.validateFunctionCode=void 0;const Qf=fa,Yf=Tt,jl=tn,Co=Tt,Ob=ko,as=Mr,Dl=hn,me=Me,Se=Nr,Ab=At,rn=se,ss=ts;function Nb(t){if(rp(t)&&(np(t),tp(t))){Db(t);return}Xf(t,()=>(0,Qf.topBoolOrEmptySchema)(t))}wr.validateFunctionCode=Nb;function Xf({gen:t,validateName:e,schema:r,schemaEnv:a,opts:n},s){n.code.es5?t.func(e,(0,me._)`${Se.default.data}, ${Se.default.valCxt}`,a.$async,()=>{t.code((0,me._)`"use strict"; ${ep(r,n)}`),jb(t,n),t.code(s)}):t.func(e,(0,me._)`${Se.default.data}, ${Mb(n)}`,a.$async,()=>t.code(ep(r,n)).code(s))}function Mb(t){return(0,me._)`{${Se.default.instancePath}="", ${Se.default.parentData}, ${Se.default.parentDataProperty}, ${Se.default.rootData}=${Se.default.data}${t.dynamicRef?(0,me._)`, ${Se.default.dynamicAnchors}={}`:me.nil}}={}`}function jb(t,e){t.if(Se.default.valCxt,()=>{t.var(Se.default.instancePath,(0,me._)`${Se.default.valCxt}.${Se.default.instancePath}`),t.var(Se.default.parentData,(0,me._)`${Se.default.valCxt}.${Se.default.parentData}`),t.var(Se.default.parentDataProperty,(0,me._)`${Se.default.valCxt}.${Se.default.parentDataProperty}`),t.var(Se.default.rootData,(0,me._)`${Se.default.valCxt}.${Se.default.rootData}`),e.dynamicRef&&t.var(Se.default.dynamicAnchors,(0,me._)`${Se.default.valCxt}.${Se.default.dynamicAnchors}`)},()=>{t.var(Se.default.instancePath,(0,me._)`""`),t.var(Se.default.parentData,(0,me._)`undefined`),t.var(Se.default.parentDataProperty,(0,me._)`undefined`),t.var(Se.default.rootData,Se.default.data),e.dynamicRef&&t.var(Se.default.dynamicAnchors,(0,me._)`{}`)})}function Db(t){const{schema:e,opts:r,gen:a}=t;Xf(t,()=>{r.$comment&&e.$comment&&sp(t),Fb(t),a.let(Se.default.vErrors,null),a.let(Se.default.errors,0),r.unevaluated&&Lb(t),ap(t),Hb(t)})}function Lb(t){const{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,me._)`${r}.evaluated`),e.if((0,me._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,me._)`${t.evaluated}.props`,(0,me._)`undefined`)),e.if((0,me._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,me._)`${t.evaluated}.items`,(0,me._)`undefined`))}function ep(t,e){const r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,me._)`/*# sourceURL=${r} */`:me.nil}function zb(t,e){if(rp(t)&&(np(t),tp(t))){Ub(t,e);return}(0,Qf.boolOrEmptySchema)(t,e)}function tp({schema:t,self:e}){if(typeof t=="boolean")return!t;for(const r in t)if(e.RULES.all[r])return!0;return!1}function rp(t){return typeof t.schema!="boolean"}function Ub(t,e){const{schema:r,gen:a,opts:n}=t;n.$comment&&r.$comment&&sp(t),Zb(t),Vb(t);const s=a.const("_errs",Se.default.errors);ap(t,s),a.var(e,(0,me._)`${s} === ${Se.default.errors}`)}function np(t){(0,rn.checkUnknownRules)(t),qb(t)}function ap(t,e){if(t.opts.jtd)return op(t,[],!1,e);const r=(0,Yf.getSchemaTypes)(t.schema),a=(0,Yf.coerceAndCheckDataType)(t,r);op(t,r,!a,e)}function qb(t){const{schema:e,errSchemaPath:r,opts:a,self:n}=t;e.$ref&&a.ignoreKeywordsWithRef&&(0,rn.schemaHasRulesButRef)(e,n.RULES)&&n.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function Fb(t){const{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,rn.checkStrictMode)(t,"default is ignored in the schema root")}function Zb(t){const e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Ab.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Vb(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function sp({gen:t,schemaEnv:e,schema:r,errSchemaPath:a,opts:n}){const s=r.$comment;if(n.$comment===!0)t.code((0,me._)`${Se.default.self}.logger.log(${s})`);else if(typeof n.$comment=="function"){const o=(0,me.str)`${a}/$comment`,i=t.scopeValue("root",{ref:e.root});t.code((0,me._)`${Se.default.self}.opts.$comment(${s}, ${o}, ${i}.schema)`)}}function Hb(t){const{gen:e,schemaEnv:r,validateName:a,ValidationError:n,opts:s}=t;r.$async?e.if((0,me._)`${Se.default.errors} === 0`,()=>e.return(Se.default.data),()=>e.throw((0,me._)`new ${n}(${Se.default.vErrors})`)):(e.assign((0,me._)`${a}.errors`,Se.default.vErrors),s.unevaluated&&Bb(t),e.return((0,me._)`${Se.default.errors} === 0`))}function Bb({gen:t,evaluated:e,props:r,items:a}){r instanceof me.Name&&t.assign((0,me._)`${e}.props`,r),a instanceof me.Name&&t.assign((0,me._)`${e}.items`,a)}function op(t,e,r,a){const{gen:n,schema:s,data:o,allErrors:i,opts:l,self:c}=t,{RULES:u}=c;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,rn.schemaHasRulesButRef)(s,u))){n.block(()=>up(t,"$ref",u.all.$ref.definition));return}l.jtd||Jb(t,e),n.block(()=>{for(const g of u.rules)h(g);h(u.post)});function h(g){(0,jl.shouldUseGroup)(s,g)&&(g.type?(n.if((0,Co.checkDataType)(g.type,o,l.strictNumbers)),ip(t,g),e.length===1&&e[0]===g.type&&r&&(n.else(),(0,Co.reportTypeError)(t)),n.endIf()):ip(t,g),i||n.if((0,me._)`${Se.default.errors} === ${a||0}`))}}function ip(t,e){const{gen:r,schema:a,opts:{useDefaults:n}}=t;n&&(0,Ob.assignDefaults)(t,e.type),r.block(()=>{for(const s of e.rules)(0,jl.shouldUseRule)(a,s)&&up(t,s.keyword,s.definition,e.type)})}function Jb(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Gb(t,e),t.opts.allowUnionTypes||Kb(t,e),Wb(t,t.dataTypes))}function Gb(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{lp(t.dataTypes,r)||Ll(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),Yb(t,e)}}function Kb(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ll(t,"use allowUnionTypes to allow union type keyword")}function Wb(t,e){const r=t.self.RULES.all;for(const a in r){const n=r[a];if(typeof n=="object"&&(0,jl.shouldUseRule)(t.schema,n)){const{type:s}=n.definition;s.length&&!s.some(o=>Qb(e,o))&&Ll(t,`missing type "${s.join(",")}" for keyword "${a}"`)}}}function Qb(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function lp(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function Yb(t,e){const r=[];for(const a of t.dataTypes)lp(e,a)?r.push(a):e.includes("integer")&&a==="number"&&r.push("integer");t.dataTypes=r}function Ll(t,e){const r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,rn.checkStrictMode)(t,e,t.opts.strictTypes)}class cp{constructor(e,r,a){if((0,as.validateKeywordUsage)(e,r,a),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=a,this.data=e.data,this.schema=e.schema[a],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,rn.schemaRefOrVal)(e,this.schema,a,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",dp(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,as.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${a} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Se.default.errors))}result(e,r,a){this.failResult((0,me.not)(e),r,a)}failResult(e,r,a){this.gen.if(e),a?a():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,me.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:r}=this;this.fail((0,me._)`${r} !== undefined && (${(0,me.or)(this.invalid$data(),e)})`)}error(e,r,a){if(r){this.setParams(r),this._error(e,a),this.setParams({});return}this._error(e,a)}_error(e,r){(e?ss.reportExtraError:ss.reportError)(this,this.def.error,r)}$dataError(){(0,ss.reportError)(this,this.def.$dataError||ss.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ss.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,a=me.nil){this.gen.block(()=>{this.check$data(e,a),r()})}check$data(e=me.nil,r=me.nil){if(!this.$data)return;const{gen:a,schemaCode:n,schemaType:s,def:o}=this;a.if((0,me.or)((0,me._)`${n} === undefined`,r)),e!==me.nil&&a.assign(e,!0),(s.length||o.validateSchema)&&(a.elseIf(this.invalid$data()),this.$dataError(),e!==me.nil&&a.assign(e,!1)),a.else()}invalid$data(){const{gen:e,schemaCode:r,schemaType:a,def:n,it:s}=this;return(0,me.or)(o(),i());function o(){if(a.length){if(!(r instanceof me.Name))throw new Error("ajv implementation error");const l=Array.isArray(a)?a:[a];return(0,me._)`${(0,Co.checkDataTypes)(l,r,s.opts.strictNumbers,Co.DataType.Wrong)}`}return me.nil}function i(){if(n.validateSchema){const l=e.scopeValue("validate$data",{ref:n.validateSchema});return(0,me._)`!${l}(${r})`}return me.nil}}subschema(e,r){const a=(0,Dl.getSubschema)(this.it,e);(0,Dl.extendSubschemaData)(a,this.it,e),(0,Dl.extendSubschemaMode)(a,e);const n={...this.it,...a,items:void 0,props:void 0};return zb(n,r),n}mergeEvaluated(e,r){const{it:a,gen:n}=this;a.opts.unevaluated&&(a.props!==!0&&e.props!==void 0&&(a.props=rn.mergeEvaluated.props(n,e.props,a.props,r)),a.items!==!0&&e.items!==void 0&&(a.items=rn.mergeEvaluated.items(n,e.items,a.items,r)))}mergeValidEvaluated(e,r){const{it:a,gen:n}=this;if(a.opts.unevaluated&&(a.props!==!0||a.items!==!0))return n.if(r,()=>this.mergeEvaluated(e,me.Name)),!0}}wr.KeywordCxt=cp;function up(t,e,r,a){const n=new cp(t,r,e);"code"in r?r.code(n,a):n.$data&&r.validate?(0,as.funcKeywordCode)(n,r):"macro"in r?(0,as.macroKeywordCode)(n,r):(r.compile||r.validate)&&(0,as.funcKeywordCode)(n,r)}const Xb=/^\/(?:[^~]|~0|~1)*$/,e1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function dp(t,{dataLevel:e,dataNames:r,dataPathArr:a}){let n,s;if(t==="")return Se.default.rootData;if(t[0]==="/"){if(!Xb.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);n=t,s=Se.default.rootData}else{const c=e1.exec(t);if(!c)throw new Error(`Invalid JSON-pointer: ${t}`);const u=+c[1];if(n=c[2],n==="#"){if(u>=e)throw new Error(l("property/index",u));return a[e-u]}if(u>e)throw new Error(l("data",u));if(s=r[e-u],!n)return s}let o=s;const i=n.split("/");for(const c of i)c&&(s=(0,me._)`${s}${(0,me.getProperty)((0,rn.unescapeJsonPointer)(c))}`,o=(0,me._)`${o} && ${s}`);return o;function l(c,u){return`Cannot access ${c} ${u} levels up, current level is ${e}`}}wr.getData=dp;var os={};Object.defineProperty(os,"__esModule",{value:!0});let t1=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};os.default=t1;var va={};Object.defineProperty(va,"__esModule",{value:!0});const zl=At;let r1=class extends Error{constructor(e,r,a,n){super(n||`can't resolve reference ${a} from id ${r}`),this.missingRef=(0,zl.resolveUrl)(e,r,a),this.missingSchema=(0,zl.normalizeId)((0,zl.getFullPath)(e,this.missingRef))}};va.default=r1;var Vt={};Object.defineProperty(Vt,"__esModule",{value:!0}),Vt.resolveSchema=Vt.getCompilingSchema=Vt.resolveRef=Vt.compileSchema=Vt.SchemaEnv=void 0;const br=Me,n1=os,Ln=Nr,Er=At,fp=se,a1=wr;class Ro{constructor(e){var r;this.refs={},this.dynamicAnchors={};let a;typeof e.schema=="object"&&(a=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Er.normalizeId)(a==null?void 0:a[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=a==null?void 0:a.$async,this.refs={}}}Vt.SchemaEnv=Ro;function Ul(t){const e=pp.call(this,t);if(e)return e;const r=(0,Er.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:a,lines:n}=this.opts.code,{ownProperties:s}=this.opts,o=new br.CodeGen(this.scope,{es5:a,lines:n,ownProperties:s});let i;t.$async&&(i=o.scopeValue("Error",{ref:n1.default,code:(0,br._)`require("ajv/dist/runtime/validation_error").default`}));const l=o.scopeName("validate");t.validateName=l;const c={gen:o,allErrors:this.opts.allErrors,data:Ln.default.data,parentData:Ln.default.parentData,parentDataProperty:Ln.default.parentDataProperty,dataNames:[Ln.default.data],dataPathArr:[br.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,br.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:i,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:br.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,br._)`""`,opts:this.opts,self:this};let u;try{this._compilations.add(t),(0,a1.validateFunctionCode)(c),o.optimize(this.opts.code.optimize);const h=o.toString();u=`${o.scopeRefs(Ln.default.scope)}return ${h}`,this.opts.code.process&&(u=this.opts.code.process(u,t));const d=new Function(`${Ln.default.self}`,`${Ln.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:d}),d.errors=null,d.schema=t.schema,d.schemaEnv=t,t.$async&&(d.$async=!0),this.opts.code.source===!0&&(d.source={validateName:l,validateCode:h,scopeValues:o._values}),this.opts.unevaluated){const{props:f,items:v}=c;d.evaluated={props:f instanceof br.Name?void 0:f,items:v instanceof br.Name?void 0:v,dynamicProps:f instanceof br.Name,dynamicItems:v instanceof br.Name},d.source&&(d.source.evaluated=(0,br.stringify)(d.evaluated))}return t.validate=d,t}catch(h){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),h}finally{this._compilations.delete(t)}}Vt.compileSchema=Ul;function s1(t,e,r){var a;r=(0,Er.resolveUrl)(this.opts.uriResolver,e,r);const n=t.refs[r];if(n)return n;let s=l1.call(this,t,r);if(s===void 0){const o=(a=t.localRefs)===null||a===void 0?void 0:a[r],{schemaId:i}=this.opts;o&&(s=new Ro({schema:o,schemaId:i,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=o1.call(this,s)}Vt.resolveRef=s1;function o1(t){return(0,Er.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ul.call(this,t)}function pp(t){for(const e of this._compilations)if(i1(e,t))return e}Vt.getCompilingSchema=pp;function i1(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function l1(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Oo.call(this,t,e)}function Oo(t,e){const r=this.opts.uriResolver.parse(e),a=(0,Er._getFullPath)(this.opts.uriResolver,r);let n=(0,Er.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&a===n)return ql.call(this,r,t);const s=(0,Er.normalizeId)(a),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){const i=Oo.call(this,t,o);return typeof(i==null?void 0:i.schema)!="object"?void 0:ql.call(this,r,i)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Ul.call(this,o),s===(0,Er.normalizeId)(e)){const{schema:i}=o,{schemaId:l}=this.opts,c=i[l];return c&&(n=(0,Er.resolveUrl)(this.opts.uriResolver,n,c)),new Ro({schema:i,schemaId:l,root:t,baseId:n})}return ql.call(this,r,o)}}Vt.resolveSchema=Oo;const c1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ql(t,{baseId:e,schema:r,root:a}){var n;if(((n=t.fragment)===null||n===void 0?void 0:n[0])!=="/")return;for(const i of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;const l=r[(0,fp.unescapeFragment)(i)];if(l===void 0)return;r=l;const c=typeof r=="object"&&r[this.opts.schemaId];!c1.has(i)&&c&&(e=(0,Er.resolveUrl)(this.opts.uriResolver,e,c))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,fp.schemaHasRulesButRef)(r,this.RULES)){const i=(0,Er.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Oo.call(this,a,i)}const{schemaId:o}=this.opts;if(s=s||new Ro({schema:r,schemaId:o,root:a,baseId:e}),s.schema!==s.root.schema)return s}const u1={$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 Fl={},Ao={exports:{}},d1={HEX:{0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15}};const{HEX:f1}=d1,p1=/^(?:(?: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 hp(t){if(gp(t,".")<3)return{host:t,isIPV4:!1};const e=t.match(p1)||[],[r]=e;return r?{host:m1(r,"."),isIPV4:!0}:{host:t,isIPV4:!1}}function mp(t,e=!1){let r="",a=!0;for(const n of t){if(f1[n]===void 0)return;n!=="0"&&a===!0&&(a=!1),a||(r+=n)}return e&&r.length===0&&(r="0"),r}function h1(t){let e=0;const r={error:!1,address:"",zone:""},a=[],n=[];let s=!1,o=!1,i=!1;function l(){if(n.length){if(s===!1){const c=mp(n);if(c!==void 0)a.push(c);else return r.error=!0,!1}n.length=0}return!0}for(let c=0;c<t.length;c++){const u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!l())break;if(e++,a.push(":"),e>7){r.error=!0;break}c-1>=0&&t[c-1]===":"&&(o=!0);continue}else if(u==="%"){if(!l())break;s=!0}else{n.push(u);continue}}return n.length&&(s?r.zone=n.join(""):i?a.push(n.join("")):a.push(mp(n))),r.address=a.join(""),r}function vp(t){if(gp(t,":")<2)return{host:t,isIPV6:!1};const e=h1(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,a=e.address;return e.zone&&(r+="%"+e.zone,a+="%25"+e.zone),{host:r,escapedHost:a,isIPV6:!0}}}function m1(t,e){let r="",a=!0;const n=t.length;for(let s=0;s<n;s++){const o=t[s];o==="0"&&a?(s+1<=n&&t[s+1]===e||s+1===n)&&(r+=o,a=!1):(o===e?a=!0:a=!1,r+=o)}return r}function gp(t,e){let r=0;for(let a=0;a<t.length;a++)t[a]===e&&r++;return r}const yp=/^\.\.?\//u,_p=/^\/\.(?:\/|$)/u,wp=/^\/\.\.(?:\/|$)/u,v1=/^\/?(?:.|\n)*?(?=\/|$)/u;function g1(t){const e=[];for(;t.length;)if(t.match(yp))t=t.replace(yp,"");else if(t.match(_p))t=t.replace(_p,"/");else if(t.match(wp))t=t.replace(wp,"/"),e.pop();else if(t==="."||t==="..")t="";else{const r=t.match(v1);if(r){const a=r[0];t=t.slice(a.length),e.push(a)}else throw new Error("Unexpected dot segment condition")}return e.join("")}function y1(t,e){const r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function _1(t){const e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);const a=hp(r);if(a.isIPV4)r=a.host;else{const n=vp(a.host);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}var w1={recomposeAuthority:_1,normalizeComponentEncoding:y1,removeDotSegments:g1,normalizeIPv4:hp,normalizeIPv6:vp};const b1=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,E1=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function bp(t){return typeof t.secure=="boolean"?t.secure:String(t.scheme).toLowerCase()==="wss"}function Ep(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function $p(t){const e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function $1(t){return t.secure=bp(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function S1(t){if((t.port===(bp(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){const[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function P1(t,e){if(!t.path)return t.error="URN can not be parsed",t;const r=t.path.match(E1);if(r){const a=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];const n=`${a}:${e.nid||t.nid}`,s=Zl[n];t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function T1(t,e){const r=e.scheme||t.scheme||"urn",a=t.nid.toLowerCase(),n=`${r}:${e.nid||a}`,s=Zl[n];s&&(t=s.serialize(t,e));const o=t,i=t.nss;return o.path=`${a||e.nid}:${i}`,e.skipEscape=!0,o}function x1(t,e){const r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!b1.test(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function k1(t){const e=t;return e.nss=(t.uuid||"").toLowerCase(),e}const Sp={scheme:"http",domainHost:!0,parse:Ep,serialize:$p},I1={scheme:"https",domainHost:Sp.domainHost,parse:Ep,serialize:$p},No={scheme:"ws",domainHost:!0,parse:$1,serialize:S1},C1={scheme:"wss",domainHost:No.domainHost,parse:No.parse,serialize:No.serialize},Zl={http:Sp,https:I1,ws:No,wss:C1,urn:{scheme:"urn",parse:P1,serialize:T1,skipNormalize:!0},"urn:uuid":{scheme:"urn:uuid",parse:x1,serialize:k1,skipNormalize:!0}};var R1=Zl;const{normalizeIPv6:O1,normalizeIPv4:A1,removeDotSegments:is,recomposeAuthority:N1,normalizeComponentEncoding:Mo}=w1,Vl=R1;function M1(t,e){return typeof t=="string"?t=Dr(nn(t,e),e):typeof t=="object"&&(t=nn(Dr(t,e),e)),t}function j1(t,e,r){const a=Object.assign({scheme:"null"},r),n=Pp(nn(t,a),nn(e,a),a,!0);return Dr(n,{...a,skipEscape:!0})}function Pp(t,e,r,a){const n={};return a||(t=nn(Dr(t,r),r),e=nn(Dr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(n.scheme=e.scheme,n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=is(e.path||""),n.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(n.userinfo=e.userinfo,n.host=e.host,n.port=e.port,n.path=is(e.path||""),n.query=e.query):(e.path?(e.path.charAt(0)==="/"?n.path=is(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?n.path="/"+e.path:t.path?n.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:n.path=e.path,n.path=is(n.path)),n.query=e.query):(n.path=t.path,e.query!==void 0?n.query=e.query:n.query=t.query),n.userinfo=t.userinfo,n.host=t.host,n.port=t.port),n.scheme=t.scheme),n.fragment=e.fragment,n}function D1(t,e,r){return typeof t=="string"?(t=unescape(t),t=Dr(Mo(nn(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Dr(Mo(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Dr(Mo(nn(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Dr(Mo(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Dr(t,e){const r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},a=Object.assign({},e),n=[],s=Vl[(a.scheme||r.scheme||"").toLowerCase()];s&&s.serialize&&s.serialize(r,a),r.path!==void 0&&(a.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),a.reference!=="suffix"&&r.scheme&&n.push(r.scheme,":");const o=N1(r);if(o!==void 0&&(a.reference!=="suffix"&&n.push("//"),n.push(o),r.path&&r.path.charAt(0)!=="/"&&n.push("/")),r.path!==void 0){let i=r.path;!a.absolutePath&&(!s||!s.absolutePath)&&(i=is(i)),o===void 0&&(i=i.replace(/^\/\//u,"/%2F")),n.push(i)}return r.query!==void 0&&n.push("?",r.query),r.fragment!==void 0&&n.push("#",r.fragment),n.join("")}const L1=Array.from({length:127},(t,e)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(e)));function z1(t){let e=0;for(let r=0,a=t.length;r<a;++r)if(e=t.charCodeAt(r),e>126||L1[e])return!0;return!1}const U1=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function nn(t,e){const r=Object.assign({},e),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},n=t.indexOf("%")!==-1;let s=!1;r.reference==="suffix"&&(t=(r.scheme?r.scheme+":":"")+"//"+t);const o=t.match(U1);if(o){if(a.scheme=o[1],a.userinfo=o[3],a.host=o[4],a.port=parseInt(o[5],10),a.path=o[6]||"",a.query=o[7],a.fragment=o[8],isNaN(a.port)&&(a.port=o[5]),a.host){const l=A1(a.host);if(l.isIPV4===!1){const c=O1(l.host);a.host=c.host.toLowerCase(),s=c.isIPV6}else a.host=l.host,s=!0}a.scheme===void 0&&a.userinfo===void 0&&a.host===void 0&&a.port===void 0&&a.query===void 0&&!a.path?a.reference="same-document":a.scheme===void 0?a.reference="relative":a.fragment===void 0?a.reference="absolute":a.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==a.reference&&(a.error=a.error||"URI is not a "+r.reference+" reference.");const i=Vl[(r.scheme||a.scheme||"").toLowerCase()];if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&a.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&z1(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(l){a.error=a.error||"Host's domain name can not be converted to ASCII: "+l}(!i||i&&!i.skipNormalize)&&(n&&a.scheme!==void 0&&(a.scheme=unescape(a.scheme)),n&&a.host!==void 0&&(a.host=unescape(a.host)),a.path&&(a.path=escape(unescape(a.path))),a.fragment&&(a.fragment=encodeURI(decodeURIComponent(a.fragment)))),i&&i.parse&&i.parse(a,r)}else a.error=a.error||"URI can not be parsed.";return a}const Hl={SCHEMES:Vl,normalize:M1,resolve:j1,resolveComponents:Pp,equal:D1,serialize:Dr,parse:nn};Ao.exports=Hl,Ao.exports.default=Hl,Ao.exports.fastUri=Hl;var q1=Ao.exports;Object.defineProperty(Fl,"__esModule",{value:!0});const Tp=q1;Tp.code='require("ajv/dist/runtime/uri").default',Fl.default=Tp,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=wr;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var r=Me;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return r.CodeGen}});const a=os,n=va,s=jn,o=Vt,i=Me,l=At,c=Tt,u=se,h=u1,g=Fl,d=(D,C)=>new RegExp(D,C);d.code="new RegExp";const f=["removeAdditional","useDefaults","coerceTypes"],v=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),m={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},p={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},y=200;function _(D){var C,z,A,b,x,L,W,X,$e,le,ge,mt,Ie,he,Ae,Ne,Te,tt,Ze,re,Le,He,Ee,We,Yt;const Ct=D.strict,yt=(C=D.code)===null||C===void 0?void 0:C.optimize,Xt=yt===!0||yt===void 0?1:yt||0,Rt=(A=(z=D.code)===null||z===void 0?void 0:z.regExp)!==null&&A!==void 0?A:d,er=(b=D.uriResolver)!==null&&b!==void 0?b:g.default;return{strictSchema:(L=(x=D.strictSchema)!==null&&x!==void 0?x:Ct)!==null&&L!==void 0?L:!0,strictNumbers:(X=(W=D.strictNumbers)!==null&&W!==void 0?W:Ct)!==null&&X!==void 0?X:!0,strictTypes:(le=($e=D.strictTypes)!==null&&$e!==void 0?$e:Ct)!==null&&le!==void 0?le:"log",strictTuples:(mt=(ge=D.strictTuples)!==null&&ge!==void 0?ge:Ct)!==null&&mt!==void 0?mt:"log",strictRequired:(he=(Ie=D.strictRequired)!==null&&Ie!==void 0?Ie:Ct)!==null&&he!==void 0?he:!1,code:D.code?{...D.code,optimize:Xt,regExp:Rt}:{optimize:Xt,regExp:Rt},loopRequired:(Ae=D.loopRequired)!==null&&Ae!==void 0?Ae:y,loopEnum:(Ne=D.loopEnum)!==null&&Ne!==void 0?Ne:y,meta:(Te=D.meta)!==null&&Te!==void 0?Te:!0,messages:(tt=D.messages)!==null&&tt!==void 0?tt:!0,inlineRefs:(Ze=D.inlineRefs)!==null&&Ze!==void 0?Ze:!0,schemaId:(re=D.schemaId)!==null&&re!==void 0?re:"$id",addUsedSchema:(Le=D.addUsedSchema)!==null&&Le!==void 0?Le:!0,validateSchema:(He=D.validateSchema)!==null&&He!==void 0?He:!0,validateFormats:(Ee=D.validateFormats)!==null&&Ee!==void 0?Ee:!0,unicodeRegExp:(We=D.unicodeRegExp)!==null&&We!==void 0?We:!0,int32range:(Yt=D.int32range)!==null&&Yt!==void 0?Yt:!0,uriResolver:er}}class w{constructor(C={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,C=this.opts={...C,..._(C)};const{es5:z,lines:A}=this.opts.code;this.scope=new i.ValueScope({scope:{},prefixes:v,es5:z,lines:A}),this.logger=G(C.logger);const b=C.validateFormats;C.validateFormats=!1,this.RULES=(0,s.getRules)(),E.call(this,m,C,"NOT SUPPORTED"),E.call(this,p,C,"DEPRECATED","warn"),this._metaOpts=J.call(this),C.formats&&O.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),C.keywords&&M.call(this,C.keywords),typeof C.meta=="object"&&this.addMetaSchema(C.meta),T.call(this),C.validateFormats=b}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:C,meta:z,schemaId:A}=this.opts;let b=h;A==="id"&&(b={...h},b.id=b.$id,delete b.$id),z&&C&&this.addMetaSchema(b,b[A],!1)}defaultMeta(){const{meta:C,schemaId:z}=this.opts;return this.opts.defaultMeta=typeof C=="object"?C[z]||C:void 0}validate(C,z){let A;if(typeof C=="string"){if(A=this.getSchema(C),!A)throw new Error(`no schema with key or ref "${C}"`)}else A=this.compile(C);const b=A(z);return"$async"in A||(this.errors=A.errors),b}compile(C,z){const A=this._addSchema(C,z);return A.validate||this._compileSchemaEnv(A)}compileAsync(C,z){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:A}=this.opts;return b.call(this,C,z);async function b(le,ge){await x.call(this,le.$schema);const mt=this._addSchema(le,ge);return mt.validate||L.call(this,mt)}async function x(le){le&&!this.getSchema(le)&&await b.call(this,{$ref:le},!0)}async function L(le){try{return this._compileSchemaEnv(le)}catch(ge){if(!(ge instanceof n.default))throw ge;return W.call(this,ge),await X.call(this,ge.missingSchema),L.call(this,le)}}function W({missingSchema:le,missingRef:ge}){if(this.refs[le])throw new Error(`AnySchema ${le} is loaded but ${ge} cannot be resolved`)}async function X(le){const ge=await $e.call(this,le);this.refs[le]||await x.call(this,ge.$schema),this.refs[le]||this.addSchema(ge,le,z)}async function $e(le){const ge=this._loading[le];if(ge)return ge;try{return await(this._loading[le]=A(le))}finally{delete this._loading[le]}}}addSchema(C,z,A,b=this.opts.validateSchema){if(Array.isArray(C)){for(const L of C)this.addSchema(L,void 0,A,b);return this}let x;if(typeof C=="object"){const{schemaId:L}=this.opts;if(x=C[L],x!==void 0&&typeof x!="string")throw new Error(`schema ${L} must be string`)}return z=(0,l.normalizeId)(z||x),this._checkUnique(z),this.schemas[z]=this._addSchema(C,A,z,b,!0),this}addMetaSchema(C,z,A=this.opts.validateSchema){return this.addSchema(C,z,!0,A),this}validateSchema(C,z){if(typeof C=="boolean")return!0;let A;if(A=C.$schema,A!==void 0&&typeof A!="string")throw new Error("$schema must be a string");if(A=A||this.opts.defaultMeta||this.defaultMeta(),!A)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const b=this.validate(A,C);if(!b&&z){const x="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(x);else throw new Error(x)}return b}getSchema(C){let z;for(;typeof(z=P.call(this,C))=="string";)C=z;if(z===void 0){const{schemaId:A}=this.opts,b=new o.SchemaEnv({schema:{},schemaId:A});if(z=o.resolveSchema.call(this,b,C),!z)return;this.refs[C]=z}return z.validate||this._compileSchemaEnv(z)}removeSchema(C){if(C instanceof RegExp)return this._removeAllSchemas(this.schemas,C),this._removeAllSchemas(this.refs,C),this;switch(typeof C){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const z=P.call(this,C);return typeof z=="object"&&this._cache.delete(z.schema),delete this.schemas[C],delete this.refs[C],this}case"object":{const z=C;this._cache.delete(z);let A=C[this.opts.schemaId];return A&&(A=(0,l.normalizeId)(A),delete this.schemas[A],delete this.refs[A]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(C){for(const z of C)this.addKeyword(z);return this}addKeyword(C,z){let A;if(typeof C=="string")A=C,typeof z=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),z.keyword=A);else if(typeof C=="object"&&z===void 0){if(z=C,A=z.keyword,Array.isArray(A)&&!A.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Z.call(this,A,z),!z)return(0,u.eachItem)(A,x=>te.call(this,x)),this;ve.call(this,z);const b={...z,type:(0,c.getJSONTypes)(z.type),schemaType:(0,c.getJSONTypes)(z.schemaType)};return(0,u.eachItem)(A,b.type.length===0?x=>te.call(this,x,b):x=>b.type.forEach(L=>te.call(this,x,b,L))),this}getKeyword(C){const z=this.RULES.all[C];return typeof z=="object"?z.definition:!!z}removeKeyword(C){const{RULES:z}=this;delete z.keywords[C],delete z.all[C];for(const A of z.rules){const b=A.rules.findIndex(x=>x.keyword===C);b>=0&&A.rules.splice(b,1)}return this}addFormat(C,z){return typeof z=="string"&&(z=new RegExp(z)),this.formats[C]=z,this}errorsText(C=this.errors,{separator:z=", ",dataVar:A="data"}={}){return!C||C.length===0?"No errors":C.map(b=>`${A}${b.instancePath} ${b.message}`).reduce((b,x)=>b+z+x)}$dataMetaSchema(C,z){const A=this.RULES.all;C=JSON.parse(JSON.stringify(C));for(const b of z){const x=b.split("/").slice(1);let L=C;for(const W of x)L=L[W];for(const W in A){const X=A[W];if(typeof X!="object")continue;const{$data:$e}=X.definition,le=L[W];$e&&le&&(L[W]=ie(le))}}return C}_removeAllSchemas(C,z){for(const A in C){const b=C[A];(!z||z.test(A))&&(typeof b=="string"?delete C[A]:b&&!b.meta&&(this._cache.delete(b.schema),delete C[A]))}}_addSchema(C,z,A,b=this.opts.validateSchema,x=this.opts.addUsedSchema){let L;const{schemaId:W}=this.opts;if(typeof C=="object")L=C[W];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof C!="boolean")throw new Error("schema must be object or boolean")}let X=this._cache.get(C);if(X!==void 0)return X;A=(0,l.normalizeId)(L||A);const $e=l.getSchemaRefs.call(this,C,A);return X=new o.SchemaEnv({schema:C,schemaId:W,meta:z,baseId:A,localRefs:$e}),this._cache.set(X.schema,X),x&&!A.startsWith("#")&&(A&&this._checkUnique(A),this.refs[A]=X),b&&this.validateSchema(C,!0),X}_checkUnique(C){if(this.schemas[C]||this.refs[C])throw new Error(`schema with key or id "${C}" already exists`)}_compileSchemaEnv(C){if(C.meta?this._compileMetaSchema(C):o.compileSchema.call(this,C),!C.validate)throw new Error("ajv implementation error");return C.validate}_compileMetaSchema(C){const z=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,C)}finally{this.opts=z}}}w.ValidationError=a.default,w.MissingRefError=n.default,t.default=w;function E(D,C,z,A="error"){for(const b in D){const x=b;x in C&&this.logger[A](`${z}: option ${b}. ${D[x]}`)}}function P(D){return D=(0,l.normalizeId)(D),this.schemas[D]||this.refs[D]}function T(){const D=this.opts.schemas;if(D)if(Array.isArray(D))this.addSchema(D);else for(const C in D)this.addSchema(D[C],C)}function O(){for(const D in this.opts.formats){const C=this.opts.formats[D];C&&this.addFormat(D,C)}}function M(D){if(Array.isArray(D)){this.addVocabulary(D);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const C in D){const z=D[C];z.keyword||(z.keyword=C),this.addKeyword(z)}}function J(){const D={...this.opts};for(const C of f)delete D[C];return D}const H={log(){},warn(){},error(){}};function G(D){if(D===!1)return H;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 F=/^[a-z_$][a-z0-9_$:-]*$/i;function Z(D,C){const{RULES:z}=this;if((0,u.eachItem)(D,A=>{if(z.keywords[A])throw new Error(`Keyword ${A} is already defined`);if(!F.test(A))throw new Error(`Keyword ${A} has invalid name`)}),!!C&&C.$data&&!("code"in C||"validate"in C))throw new Error('$data keyword must have "code" or "validate" function')}function te(D,C,z){var A;const b=C==null?void 0:C.post;if(z&&b)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:x}=this;let L=b?x.post:x.rules.find(({type:X})=>X===z);if(L||(L={type:z,rules:[]},x.rules.push(L)),x.keywords[D]=!0,!C)return;const W={keyword:D,definition:{...C,type:(0,c.getJSONTypes)(C.type),schemaType:(0,c.getJSONTypes)(C.schemaType)}};C.before?pe.call(this,L,W,C.before):L.rules.push(W),x.all[D]=W,(A=C.implements)===null||A===void 0||A.forEach(X=>this.addKeyword(X))}function pe(D,C,z){const A=D.rules.findIndex(b=>b.keyword===z);A>=0?D.rules.splice(A,0,C):(D.rules.push(C),this.logger.warn(`rule ${z} is not defined`))}function ve(D){let{metaSchema:C}=D;C!==void 0&&(D.$data&&this.opts.$data&&(C=ie(C)),D.validateSchema=this.compile(C,!0))}const N={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ie(D){return{anyOf:[D,N]}}}(xf);var Bl={},Jl={},Gl={};Object.defineProperty(Gl,"__esModule",{value:!0});const F1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Gl.default=F1;var zn={};Object.defineProperty(zn,"__esModule",{value:!0}),zn.callRef=zn.getValidate=void 0;const Z1=va,xp=je,Ht=Me,ga=Nr,kp=Vt,jo=se,V1={keyword:"$ref",schemaType:"string",code(t){const{gen:e,schema:r,it:a}=t,{baseId:n,schemaEnv:s,validateName:o,opts:i,self:l}=a,{root:c}=s;if((r==="#"||r==="#/")&&n===c.baseId)return h();const u=kp.resolveRef.call(l,c,n,r);if(u===void 0)throw new Z1.default(a.opts.uriResolver,n,r);if(u instanceof kp.SchemaEnv)return g(u);return d(u);function h(){if(s===c)return Do(t,o,s,s.$async);const f=e.scopeValue("root",{ref:c});return Do(t,(0,Ht._)`${f}.validate`,c,c.$async)}function g(f){const v=Ip(t,f);Do(t,v,f,f.$async)}function d(f){const v=e.scopeValue("schema",i.code.source===!0?{ref:f,code:(0,Ht.stringify)(f)}:{ref:f}),m=e.name("valid"),p=t.subschema({schema:f,dataTypes:[],schemaPath:Ht.nil,topSchemaRef:v,errSchemaPath:r},m);t.mergeEvaluated(p),t.ok(m)}}};function Ip(t,e){const{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Ht._)`${r.scopeValue("wrapper",{ref:e})}.validate`}zn.getValidate=Ip;function Do(t,e,r,a){const{gen:n,it:s}=t,{allErrors:o,schemaEnv:i,opts:l}=s,c=l.passContext?ga.default.this:Ht.nil;a?u():h();function u(){if(!i.$async)throw new Error("async schema referenced by sync schema");const f=n.let("valid");n.try(()=>{n.code((0,Ht._)`await ${(0,xp.callValidateCode)(t,e,c)}`),d(e),o||n.assign(f,!0)},v=>{n.if((0,Ht._)`!(${v} instanceof ${s.ValidationError})`,()=>n.throw(v)),g(v),o||n.assign(f,!1)}),t.ok(f)}function h(){t.result((0,xp.callValidateCode)(t,e,c),()=>d(e),()=>g(e))}function g(f){const v=(0,Ht._)`${f}.errors`;n.assign(ga.default.vErrors,(0,Ht._)`${ga.default.vErrors} === null ? ${v} : ${ga.default.vErrors}.concat(${v})`),n.assign(ga.default.errors,(0,Ht._)`${ga.default.vErrors}.length`)}function d(f){var v;if(!s.opts.unevaluated)return;const m=(v=r==null?void 0:r.validate)===null||v===void 0?void 0:v.evaluated;if(s.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(s.props=jo.mergeEvaluated.props(n,m.props,s.props));else{const p=n.var("props",(0,Ht._)`${f}.evaluated.props`);s.props=jo.mergeEvaluated.props(n,p,s.props,Ht.Name)}if(s.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(s.items=jo.mergeEvaluated.items(n,m.items,s.items));else{const p=n.var("items",(0,Ht._)`${f}.evaluated.items`);s.items=jo.mergeEvaluated.items(n,p,s.items,Ht.Name)}}}zn.callRef=Do,zn.default=V1,Object.defineProperty(Jl,"__esModule",{value:!0});const H1=Gl,B1=zn,J1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",H1.default,B1.default];Jl.default=J1;var Kl={},Wl={};Object.defineProperty(Wl,"__esModule",{value:!0});const Lo=Me,vn=Lo.operators,zo={maximum:{okStr:"<=",ok:vn.LTE,fail:vn.GT},minimum:{okStr:">=",ok:vn.GTE,fail:vn.LT},exclusiveMaximum:{okStr:"<",ok:vn.LT,fail:vn.GTE},exclusiveMinimum:{okStr:">",ok:vn.GT,fail:vn.LTE}},G1={message:({keyword:t,schemaCode:e})=>(0,Lo.str)`must be ${zo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Lo._)`{comparison: ${zo[t].okStr}, limit: ${e}}`},K1={keyword:Object.keys(zo),type:"number",schemaType:"number",$data:!0,error:G1,code(t){const{keyword:e,data:r,schemaCode:a}=t;t.fail$data((0,Lo._)`${r} ${zo[e].fail} ${a} || isNaN(${r})`)}};Wl.default=K1;var Ql={};Object.defineProperty(Ql,"__esModule",{value:!0});const ls=Me,W1={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:{message:({schemaCode:t})=>(0,ls.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ls._)`{multipleOf: ${t}}`},code(t){const{gen:e,data:r,schemaCode:a,it:n}=t,s=n.opts.multipleOfPrecision,o=e.let("res"),i=s?(0,ls._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,ls._)`${o} !== parseInt(${o})`;t.fail$data((0,ls._)`(${a} === 0 || (${o} = ${r}/${a}, ${i}))`)}};Ql.default=W1;var Yl={},Xl={};Object.defineProperty(Xl,"__esModule",{value:!0});function Cp(t){const e=t.length;let r=0,a=0,n;for(;a<e;)r++,n=t.charCodeAt(a++),n>=55296&&n<=56319&&a<e&&(n=t.charCodeAt(a),(n&64512)===56320&&a++);return r}Xl.default=Cp,Cp.code='require("ajv/dist/runtime/ucs2length").default',Object.defineProperty(Yl,"__esModule",{value:!0});const Un=Me,Q1=se,Y1=Xl,X1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:{message({keyword:t,schemaCode:e}){const r=t==="maxLength"?"more":"fewer";return(0,Un.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Un._)`{limit: ${t}}`},code(t){const{keyword:e,data:r,schemaCode:a,it:n}=t,s=e==="maxLength"?Un.operators.GT:Un.operators.LT,o=n.opts.unicode===!1?(0,Un._)`${r}.length`:(0,Un._)`${(0,Q1.useFunc)(t.gen,Y1.default)}(${r})`;t.fail$data((0,Un._)`${o} ${s} ${a}`)}};Yl.default=X1;var ec={};Object.defineProperty(ec,"__esModule",{value:!0});const eE=je,Uo=Me,tE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>(0,Uo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Uo._)`{pattern: ${t}}`},code(t){const{data:e,$data:r,schema:a,schemaCode:n,it:s}=t,o=s.opts.unicodeRegExp?"u":"",i=r?(0,Uo._)`(new RegExp(${n}, ${o}))`:(0,eE.usePattern)(t,a);t.fail$data((0,Uo._)`!${i}.test(${e})`)}};ec.default=tE;var tc={};Object.defineProperty(tc,"__esModule",{value:!0});const cs=Me,rE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:{message({keyword:t,schemaCode:e}){const r=t==="maxProperties"?"more":"fewer";return(0,cs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,cs._)`{limit: ${t}}`},code(t){const{keyword:e,data:r,schemaCode:a}=t,n=e==="maxProperties"?cs.operators.GT:cs.operators.LT;t.fail$data((0,cs._)`Object.keys(${r}).length ${n} ${a}`)}};tc.default=rE;var rc={};Object.defineProperty(rc,"__esModule",{value:!0});const us=je,ds=Me,nE=se,aE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:{message:({params:{missingProperty:t}})=>(0,ds.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ds._)`{missingProperty: ${t}}`},code(t){const{gen:e,schema:r,schemaCode:a,data:n,$data:s,it:o}=t,{opts:i}=o;if(!s&&r.length===0)return;const l=r.length>=i.loopRequired;if(o.allErrors?c():u(),i.strictRequired){const d=t.parentSchema.properties,{definedProperties:f}=t.it;for(const v of r)if((d==null?void 0:d[v])===void 0&&!f.has(v)){const m=o.schemaEnv.baseId+o.errSchemaPath,p=`required property "${v}" is not defined at "${m}" (strictRequired)`;(0,nE.checkStrictMode)(o,p,o.opts.strictRequired)}}function c(){if(l||s)t.block$data(ds.nil,h);else for(const d of r)(0,us.checkReportMissingProp)(t,d)}function u(){const d=e.let("missing");if(l||s){const f=e.let("valid",!0);t.block$data(f,()=>g(d,f)),t.ok(f)}else e.if((0,us.checkMissingProp)(t,r,d)),(0,us.reportMissingProp)(t,d),e.else()}function h(){e.forOf("prop",a,d=>{t.setParams({missingProperty:d}),e.if((0,us.noPropertyInData)(e,n,d,i.ownProperties),()=>t.error())})}function g(d,f){t.setParams({missingProperty:d}),e.forOf(d,a,()=>{e.assign(f,(0,us.propertyInData)(e,n,d,i.ownProperties)),e.if((0,ds.not)(f),()=>{t.error(),e.break()})},ds.nil)}}};rc.default=aE;var nc={};Object.defineProperty(nc,"__esModule",{value:!0});const fs=Me,sE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:{message({keyword:t,schemaCode:e}){const r=t==="maxItems"?"more":"fewer";return(0,fs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,fs._)`{limit: ${t}}`},code(t){const{keyword:e,data:r,schemaCode:a}=t,n=e==="maxItems"?fs.operators.GT:fs.operators.LT;t.fail$data((0,fs._)`${r}.length ${n} ${a}`)}};nc.default=sE;var ac={},ps={};Object.defineProperty(ps,"__esModule",{value:!0});const Rp=ns;Rp.code='require("ajv/dist/runtime/equal").default',ps.default=Rp,Object.defineProperty(ac,"__esModule",{value:!0});const sc=Tt,Nt=Me,oE=se,iE=ps,lE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:{message:({params:{i:t,j:e}})=>(0,Nt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Nt._)`{i: ${t}, j: ${e}}`},code(t){const{gen:e,data:r,$data:a,schema:n,parentSchema:s,schemaCode:o,it:i}=t;if(!a&&!n)return;const l=e.let("valid"),c=s.items?(0,sc.getSchemaTypes)(s.items):[];t.block$data(l,u,(0,Nt._)`${o} === false`),t.ok(l);function u(){const f=e.let("i",(0,Nt._)`${r}.length`),v=e.let("j");t.setParams({i:f,j:v}),e.assign(l,!0),e.if((0,Nt._)`${f} > 1`,()=>(h()?g:d)(f,v))}function h(){return c.length>0&&!c.some(f=>f==="object"||f==="array")}function g(f,v){const m=e.name("item"),p=(0,sc.checkDataTypes)(c,m,i.opts.strictNumbers,sc.DataType.Wrong),y=e.const("indices",(0,Nt._)`{}`);e.for((0,Nt._)`;${f}--;`,()=>{e.let(m,(0,Nt._)`${r}[${f}]`),e.if(p,(0,Nt._)`continue`),c.length>1&&e.if((0,Nt._)`typeof ${m} == "string"`,(0,Nt._)`${m} += "_"`),e.if((0,Nt._)`typeof ${y}[${m}] == "number"`,()=>{e.assign(v,(0,Nt._)`${y}[${m}]`),t.error(),e.assign(l,!1).break()}).code((0,Nt._)`${y}[${m}] = ${f}`)})}function d(f,v){const m=(0,oE.useFunc)(e,iE.default),p=e.name("outer");e.label(p).for((0,Nt._)`;${f}--;`,()=>e.for((0,Nt._)`${v} = ${f}; ${v}--;`,()=>e.if((0,Nt._)`${m}(${r}[${f}], ${r}[${v}])`,()=>{t.error(),e.assign(l,!1).break(p)})))}}};ac.default=lE;var oc={};Object.defineProperty(oc,"__esModule",{value:!0});const ic=Me,cE=se,uE=ps,dE={keyword:"const",$data:!0,error:{message:"must be equal to constant",params:({schemaCode:t})=>(0,ic._)`{allowedValue: ${t}}`},code(t){const{gen:e,data:r,$data:a,schemaCode:n,schema:s}=t;a||s&&typeof s=="object"?t.fail$data((0,ic._)`!${(0,cE.useFunc)(e,uE.default)}(${r}, ${n})`):t.fail((0,ic._)`${s} !== ${r}`)}};oc.default=dE;var lc={};Object.defineProperty(lc,"__esModule",{value:!0});const hs=Me,fE=se,pE=ps,hE={keyword:"enum",schemaType:"array",$data:!0,error:{message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,hs._)`{allowedValues: ${t}}`},code(t){const{gen:e,data:r,$data:a,schema:n,schemaCode:s,it:o}=t;if(!a&&n.length===0)throw new Error("enum must have non-empty array");const i=n.length>=o.opts.loopEnum;let l;const c=()=>l??(l=(0,fE.useFunc)(e,pE.default));let u;if(i||a)u=e.let("valid"),t.block$data(u,h);else{if(!Array.isArray(n))throw new Error("ajv implementation error");const d=e.const("vSchema",s);u=(0,hs.or)(...n.map((f,v)=>g(d,v)))}t.pass(u);function h(){e.assign(u,!1),e.forOf("v",s,d=>e.if((0,hs._)`${c()}(${r}, ${d})`,()=>e.assign(u,!0).break()))}function g(d,f){const v=n[f];return typeof v=="object"&&v!==null?(0,hs._)`${c()}(${r}, ${d}[${f}])`:(0,hs._)`${r} === ${v}`}}};lc.default=hE,Object.defineProperty(Kl,"__esModule",{value:!0});const mE=Wl,vE=Ql,gE=Yl,yE=ec,_E=tc,wE=rc,bE=nc,EE=ac,$E=oc,SE=lc,PE=[mE.default,vE.default,gE.default,yE.default,_E.default,wE.default,bE.default,EE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},$E.default,SE.default];Kl.default=PE;var cc={},ya={};Object.defineProperty(ya,"__esModule",{value:!0}),ya.validateAdditionalItems=void 0;const qn=Me,uc=se,TE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:{message:({params:{len:t}})=>(0,qn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,qn._)`{limit: ${t}}`},code(t){const{parentSchema:e,it:r}=t,{items:a}=e;if(!Array.isArray(a)){(0,uc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Op(t,a)}};function Op(t,e){const{gen:r,schema:a,data:n,keyword:s,it:o}=t;o.items=!0;const i=r.const("len",(0,qn._)`${n}.length`);if(a===!1)t.setParams({len:e.length}),t.pass((0,qn._)`${i} <= ${e.length}`);else if(typeof a=="object"&&!(0,uc.alwaysValidSchema)(o,a)){const c=r.var("valid",(0,qn._)`${i} <= ${e.length}`);r.if((0,qn.not)(c),()=>l(c)),t.ok(c)}function l(c){r.forRange("i",e.length,i,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:uc.Type.Num},c),o.allErrors||r.if((0,qn.not)(c),()=>r.break())})}}ya.validateAdditionalItems=Op,ya.default=TE;var dc={},_a={};Object.defineProperty(_a,"__esModule",{value:!0}),_a.validateTuple=void 0;const Ap=Me,qo=se,xE=je,kE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){const{schema:e,it:r}=t;if(Array.isArray(e))return Np(t,"additionalItems",e);r.items=!0,!(0,qo.alwaysValidSchema)(r,e)&&t.ok((0,xE.validateArray)(t))}};function Np(t,e,r=t.schema){const{gen:a,parentSchema:n,data:s,keyword:o,it:i}=t;u(n),i.opts.unevaluated&&r.length&&i.items!==!0&&(i.items=qo.mergeEvaluated.items(a,r.length,i.items));const l=a.name("valid"),c=a.const("len",(0,Ap._)`${s}.length`);r.forEach((h,g)=>{(0,qo.alwaysValidSchema)(i,h)||(a.if((0,Ap._)`${c} > ${g}`,()=>t.subschema({keyword:o,schemaProp:g,dataProp:g},l)),t.ok(l))});function u(h){const{opts:g,errSchemaPath:d}=i,f=r.length,v=f===h.minItems&&(f===h.maxItems||h[e]===!1);if(g.strictTuples&&!v){const m=`"${o}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${d}"`;(0,qo.checkStrictMode)(i,m,g.strictTuples)}}}_a.validateTuple=Np,_a.default=kE,Object.defineProperty(dc,"__esModule",{value:!0});const IE=_a,CE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,IE.validateTuple)(t,"items")};dc.default=CE;var fc={};Object.defineProperty(fc,"__esModule",{value:!0});const Mp=Me,RE=se,OE=je,AE=ya,NE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:{message:({params:{len:t}})=>(0,Mp.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Mp._)`{limit: ${t}}`},code(t){const{schema:e,parentSchema:r,it:a}=t,{prefixItems:n}=r;a.items=!0,!(0,RE.alwaysValidSchema)(a,e)&&(n?(0,AE.validateAdditionalItems)(t,n):t.ok((0,OE.validateArray)(t)))}};fc.default=NE;var pc={};Object.defineProperty(pc,"__esModule",{value:!0});const lr=Me,Fo=se,ME={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:{message:({params:{min:t,max:e}})=>e===void 0?(0,lr.str)`must contain at least ${t} valid item(s)`:(0,lr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,lr._)`{minContains: ${t}}`:(0,lr._)`{minContains: ${t}, maxContains: ${e}}`},code(t){const{gen:e,schema:r,parentSchema:a,data:n,it:s}=t;let o,i;const{minContains:l,maxContains:c}=a;s.opts.next?(o=l===void 0?1:l,i=c):o=1;const u=e.const("len",(0,lr._)`${n}.length`);if(t.setParams({min:o,max:i}),i===void 0&&o===0){(0,Fo.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(i!==void 0&&o>i){(0,Fo.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Fo.alwaysValidSchema)(s,r)){let v=(0,lr._)`${u} >= ${o}`;i!==void 0&&(v=(0,lr._)`${v} && ${u} <= ${i}`),t.pass(v);return}s.items=!0;const h=e.name("valid");i===void 0&&o===1?d(h,()=>e.if(h,()=>e.break())):o===0?(e.let(h,!0),i!==void 0&&e.if((0,lr._)`${n}.length > 0`,g)):(e.let(h,!1),g()),t.result(h,()=>t.reset());function g(){const v=e.name("_valid"),m=e.let("count",0);d(v,()=>e.if(v,()=>f(m)))}function d(v,m){e.forRange("i",0,u,p=>{t.subschema({keyword:"contains",dataProp:p,dataPropType:Fo.Type.Num,compositeRule:!0},v),m()})}function f(v){e.code((0,lr._)`${v}++`),i===void 0?e.if((0,lr._)`${v} >= ${o}`,()=>e.assign(h,!0).break()):(e.if((0,lr._)`${v} > ${i}`,()=>e.assign(h,!1).break()),o===1?e.assign(h,!0):e.if((0,lr._)`${v} >= ${o}`,()=>e.assign(h,!0)))}}};pc.default=ME;var jp={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=Me,r=se,a=je;t.error={message:({params:{property:l,depsCount:c,deps:u}})=>{const h=c===1?"property":"properties";return(0,e.str)`must have ${h} ${u} when property ${l} is present`},params:({params:{property:l,depsCount:c,deps:u,missingProperty:h}})=>(0,e._)`{property: ${l},
6
+ missingProperty: ${h},
7
7
  depsCount: ${c},
8
- deps: ${u}}`};const n={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(l){const[c,u]=s(l);o(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const f in l){if(f==="__proto__")continue;const g=Array.isArray(l[f])?c:u;g[f]=l[f]}return[c,u]}function o(l,c=l.schema){const{gen:u,data:f,it:g}=l;if(Object.keys(c).length===0)return;const d=u.let("missing");for(const h in c){const v=c[h];if(v.length===0)continue;const m=(0,a.propertyInData)(u,f,h,g.opts.ownProperties);l.setParams({property:h,depsCount:v.length,deps:v.join(", ")}),g.allErrors?u.if(m,()=>{for(const p of v)(0,a.checkReportMissingProp)(l,p)}):(u.if((0,e._)`${m} && (${(0,a.checkMissingProp)(l,v,d)})`),(0,a.reportMissingProp)(l,d),u.else())}}t.validatePropertyDeps=o;function i(l,c=l.schema){const{gen:u,data:f,keyword:g,it:d}=l,h=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(d,c[v])||(u.if((0,a.propertyInData)(u,f,v,d.opts.ownProperties),()=>{const m=l.subschema({keyword:g,schemaProp:v},h);l.mergeValidEvaluated(m,h)},()=>u.var(h,!0)),l.ok(h))}t.validateSchemaDeps=i,t.default=n})(Mf);var Sc={};Object.defineProperty(Sc,"__esModule",{value:!0});const jf=Me,PE=ie,kE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>(0,jf._)`{propertyName: ${t.propertyName}}`},code(t){const{gen:e,schema:r,data:a,it:n}=t;if((0,PE.alwaysValidSchema)(n,r))return;const s=e.name("valid");e.forIn("key",a,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,jf.not)(s),()=>{t.error(!0),n.allErrors||e.break()})}),t.ok(s)}};Sc.default=kE;var Ko={};Object.defineProperty(Ko,"__esModule",{value:!0});const Wo=je,Tr=Me,IE=Zr,Qo=ie,xE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:t})=>(0,Tr._)`{additionalProperty: ${t.additionalProperty}}`},code(t){const{gen:e,schema:r,parentSchema:a,data:n,errsCount:s,it:o}=t;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,Qo.alwaysValidSchema)(o,r))return;const c=(0,Wo.allSchemaProperties)(a.properties),u=(0,Wo.allSchemaProperties)(a.patternProperties);f(),t.ok((0,Tr._)`${s} === ${IE.default.errors}`);function f(){e.forIn("key",n,m=>{!c.length&&!u.length?h(m):e.if(g(m),()=>h(m))})}function g(m){let p;if(c.length>8){const _=(0,Qo.schemaRefOrVal)(o,a.properties,"properties");p=(0,Wo.isOwnProperty)(e,_,m)}else c.length?p=(0,Tr.or)(...c.map(_=>(0,Tr._)`${m} === ${_}`)):p=Tr.nil;return u.length&&(p=(0,Tr.or)(p,...u.map(_=>(0,Tr._)`${(0,Wo.usePattern)(t,_)}.test(${m})`))),(0,Tr.not)(p)}function d(m){e.code((0,Tr._)`delete ${n}[${m}]`)}function h(m){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){d(m);return}if(r===!1){t.setParams({additionalProperty:m}),t.error(),i||e.break();return}if(typeof r=="object"&&!(0,Qo.alwaysValidSchema)(o,r)){const p=e.name("valid");l.removeAdditional==="failing"?(v(m,p,!1),e.if((0,Tr.not)(p),()=>{t.reset(),d(m)})):(v(m,p),i||e.if((0,Tr.not)(p),()=>e.break()))}}function v(m,p,_){const w={keyword:"additionalProperties",dataProp:m,dataPropType:Qo.Type.Str};_===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,p)}}};Ko.default=xE;var $c={};Object.defineProperty($c,"__esModule",{value:!0});const TE=kr,Df=je,Pc=ie,Lf=Ko,CE={keyword:"properties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,parentSchema:a,data:n,it:s}=t;s.opts.removeAdditional==="all"&&a.additionalProperties===void 0&&Lf.default.code(new TE.KeywordCxt(s,Lf.default,"additionalProperties"));const o=(0,Df.allSchemaProperties)(r);for(const f of o)s.definedProperties.add(f);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=Pc.mergeEvaluated.props(e,(0,Pc.toHash)(o),s.props));const i=o.filter(f=>!(0,Pc.alwaysValidSchema)(s,r[f]));if(i.length===0)return;const l=e.name("valid");for(const f of i)c(f)?u(f):(e.if((0,Df.propertyInData)(e,n,f,s.opts.ownProperties)),u(f),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function c(f){return s.opts.useDefaults&&!s.compositeRule&&r[f].default!==void 0}function u(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};$c.default=CE;var kc={};Object.defineProperty(kc,"__esModule",{value:!0});const zf=je,Yo=Me,Uf=ie,qf=ie,RE={keyword:"patternProperties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,data:a,parentSchema:n,it:s}=t,{opts:o}=s,i=(0,zf.allSchemaProperties)(r),l=i.filter(v=>(0,Uf.alwaysValidSchema)(s,r[v]));if(i.length===0||l.length===i.length&&(!s.opts.unevaluated||s.props===!0))return;const c=o.strictSchema&&!o.allowMatchingProperties&&n.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof Yo.Name)&&(s.props=(0,qf.evaluatedPropsToName)(e,s.props));const{props:f}=s;g();function g(){for(const v of i)c&&d(v),s.allErrors?h(v):(e.var(u,!0),h(v),e.if(u))}function d(v){for(const m in c)new RegExp(v).test(m)&&(0,Uf.checkStrictMode)(s,`property ${m} matches pattern ${v} (use allowMatchingProperties)`)}function h(v){e.forIn("key",a,m=>{e.if((0,Yo._)`${(0,zf.usePattern)(t,v)}.test(${m})`,()=>{const p=l.includes(v);p||t.subschema({keyword:"patternProperties",schemaProp:v,dataProp:m,dataPropType:qf.Type.Str},u),s.opts.unevaluated&&f!==!0?e.assign((0,Yo._)`${f}[${m}]`,!0):!p&&!s.allErrors&&e.if((0,Yo.not)(u),()=>e.break())})})}}};kc.default=RE;var Ic={};Object.defineProperty(Ic,"__esModule",{value:!0});const OE=ie,NE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:e,schema:r,it:a}=t;if((0,OE.alwaysValidSchema)(a,r)){t.fail();return}const n=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),t.failResult(n,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Ic.default=NE;var xc={};Object.defineProperty(xc,"__esModule",{value:!0});const AE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:je.validateUnion,error:{message:"must match a schema in anyOf"}};xc.default=AE;var Tc={};Object.defineProperty(Tc,"__esModule",{value:!0});const Xo=Me,ME=ie,jE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Xo._)`{passingSchemas: ${t.passing}}`},code(t){const{gen:e,schema:r,parentSchema:a,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&a.discriminator)return;const s=r,o=e.let("valid",!1),i=e.let("passing",null),l=e.name("_valid");t.setParams({passing:i}),e.block(c),t.result(o,()=>t.reset(),()=>t.error(!0));function c(){s.forEach((u,f)=>{let g;(0,ME.alwaysValidSchema)(n,u)?e.var(l,!0):g=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,Xo._)`${l} && ${o}`).assign(o,!1).assign(i,(0,Xo._)`[${i}, ${f}]`).else(),e.if(l,()=>{e.assign(o,!0),e.assign(i,f),g&&t.mergeEvaluated(g,Xo.Name)})})}}};Tc.default=jE;var Cc={};Object.defineProperty(Cc,"__esModule",{value:!0});const DE=ie,LE={keyword:"allOf",schemaType:"array",code(t){const{gen:e,schema:r,it:a}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");const n=e.name("valid");r.forEach((s,o)=>{if((0,DE.alwaysValidSchema)(a,s))return;const i=t.subschema({keyword:"allOf",schemaProp:o},n);t.ok(n),t.mergeEvaluated(i)})}};Cc.default=LE;var Rc={};Object.defineProperty(Rc,"__esModule",{value:!0});const ei=Me,Ff=ie,zE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>(0,ei.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ei._)`{failingKeyword: ${t.ifClause}}`},code(t){const{gen:e,parentSchema:r,it:a}=t;r.then===void 0&&r.else===void 0&&(0,Ff.checkStrictMode)(a,'"if" without "then" and "else" is ignored');const n=Zf(a,"then"),s=Zf(a,"else");if(!n&&!s)return;const o=e.let("valid",!0),i=e.name("_valid");if(l(),t.reset(),n&&s){const u=e.let("ifClause");t.setParams({ifClause:u}),e.if(i,c("then",u),c("else",u))}else n?e.if(i,c("then")):e.if((0,ei.not)(i),c("else"));t.pass(o,()=>t.error(!0));function l(){const u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(u)}function c(u,f){return()=>{const g=t.subschema({keyword:u},i);e.assign(o,i),t.mergeValidEvaluated(g,o),f?e.assign(f,(0,ei._)`${u}`):t.setParams({ifClause:u})}}}};function Zf(t,e){const r=t.schema[e];return r!==void 0&&!(0,Ff.alwaysValidSchema)(t,r)}Rc.default=zE;var Oc={};Object.defineProperty(Oc,"__esModule",{value:!0});const UE=ie,qE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,UE.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Oc.default=qE,Object.defineProperty(yc,"__esModule",{value:!0});const FE=$a,ZE=wc,VE=Pa,HE=bc,BE=Ec,JE=Mf,GE=Sc,KE=Ko,WE=$c,QE=kc,YE=Ic,XE=xc,eS=Tc,tS=Cc,rS=Rc,nS=Oc;function aS(t=!1){const e=[YE.default,XE.default,eS.default,tS.default,rS.default,nS.default,GE.default,KE.default,JE.default,WE.default,QE.default];return t?e.push(ZE.default,HE.default):e.push(FE.default,VE.default),e.push(BE.default),e}yc.default=aS;var Nc={},Ac={};Object.defineProperty(Ac,"__esModule",{value:!0});const gt=Me,sS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>(0,gt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,gt._)`{format: ${t}}`},code(t,e){const{gen:r,data:a,$data:n,schema:s,schemaCode:o,it:i}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:f}=i;if(!l.validateFormats)return;n?g():d();function g(){const h=r.scopeValue("formats",{ref:f.formats,code:l.code.formats}),v=r.const("fDef",(0,gt._)`${h}[${o}]`),m=r.let("fType"),p=r.let("format");r.if((0,gt._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>r.assign(m,(0,gt._)`${v}.type || "string"`).assign(p,(0,gt._)`${v}.validate`),()=>r.assign(m,(0,gt._)`"string"`).assign(p,v)),t.fail$data((0,gt.or)(_(),w()));function _(){return l.strictSchema===!1?gt.nil:(0,gt._)`${o} && !${p}`}function w(){const b=u.$async?(0,gt._)`(${v}.async ? await ${p}(${a}) : ${p}(${a}))`:(0,gt._)`${p}(${a})`,S=(0,gt._)`(typeof ${p} == "function" ? ${b} : ${p}.test(${a}))`;return(0,gt._)`${p} && ${p} !== true && ${m} === ${e} && !${S}`}}function d(){const h=f.formats[s];if(!h){_();return}if(h===!0)return;const[v,m,p]=w(h);v===e&&t.pass(b());function _(){if(l.strictSchema===!1){f.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${c}"`}}function w(S){const I=S instanceof RegExp?(0,gt.regexpCode)(S):l.code.formats?(0,gt._)`${l.code.formats}${(0,gt.getProperty)(s)}`:void 0,k=r.scopeValue("formats",{key:s,ref:S,code:I});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,gt._)`${k}.validate`]:["string",S,k]}function b(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,gt._)`await ${p}(${a})`}return typeof m=="function"?(0,gt._)`${p}(${a})`:(0,gt._)`${p}.test(${a})`}}}};Ac.default=sS,Object.defineProperty(Nc,"__esModule",{value:!0});const oS=[Ac.default];Nc.default=oS;var ka={};Object.defineProperty(ka,"__esModule",{value:!0}),ka.contentVocabulary=ka.metadataVocabulary=void 0,ka.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],ka.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(tc,"__esModule",{value:!0});const iS=rc,lS=ac,cS=yc,uS=Nc,Vf=ka,dS=[iS.default,lS.default,(0,cS.default)(),uS.default,Vf.metadataVocabulary,Vf.contentVocabulary];tc.default=dS;var Mc={},ti={};Object.defineProperty(ti,"__esModule",{value:!0}),ti.DiscrError=void 0;var Hf;(function(t){t.Tag="tag",t.Mapping="mapping"})(Hf||(ti.DiscrError=Hf={})),Object.defineProperty(Mc,"__esModule",{value:!0});const Ia=Me,jc=ti,Bf=Qt,pS=Ea,fS=ie,hS={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:t,tagName:e}})=>t===jc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Ia._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},code(t){const{gen:e,data:r,schema:a,parentSchema:n,it:s}=t,{oneOf:o}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=a.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(a.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");const l=e.let("valid",!1),c=e.const("tag",(0,Ia._)`${r}${(0,Ia.getProperty)(i)}`);e.if((0,Ia._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:jc.DiscrError.Tag,tag:c,tagName:i})),t.ok(l);function u(){const d=g();e.if(!1);for(const h in d)e.elseIf((0,Ia._)`${c} === ${h}`),e.assign(l,f(d[h]));e.else(),t.error(!1,{discrError:jc.DiscrError.Mapping,tag:c,tagName:i}),e.endIf()}function f(d){const h=e.name("valid"),v=t.subschema({keyword:"oneOf",schemaProp:d},h);return t.mergeEvaluated(v,Ia.Name),h}function g(){var d;const h={},v=p(n);let m=!0;for(let b=0;b<o.length;b++){let S=o[b];if(S!=null&&S.$ref&&!(0,fS.schemaHasRulesButRef)(S,s.self.RULES)){const k=S.$ref;if(S=Bf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,k),S instanceof Bf.SchemaEnv&&(S=S.schema),S===void 0)throw new pS.default(s.opts.uriResolver,s.baseId,k)}const I=(d=S==null?void 0:S.properties)===null||d===void 0?void 0:d[i];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);m=m&&(v||p(S)),_(I,b)}if(!m)throw new Error(`discriminator: "${i}" must be required`);return h;function p({required:b}){return Array.isArray(b)&&b.includes(i)}function _(b,S){if(b.const)w(b.const,S);else if(b.enum)for(const I of b.enum)w(I,S);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function w(b,S){if(typeof b!="string"||b in h)throw new Error(`discriminator: "${i}" values must be unique strings`);h[b]=S}}}};Mc.default=hS;const mS={$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};(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const r=kp,a=tc,n=Mc,s=mS,o=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),a.default.forEach(h=>this.addVocabulary(h)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const h=this.opts.$data?this.$dataMetaSchema(s,o):s;this.addMetaSchema(h,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}e.Ajv=l,t.exports=e=l,t.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=kr;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Me;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var f=ps;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return f.default}});var g=Ea;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return g.default}})})(Al,Al.exports);var vS=Al.exports;const gS=Pp(vS);var qe;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{const s={};for(const o of n)s[o]=o;return s},t.getValidEnumValues=n=>{const s=t.objectKeys(n).filter(i=>typeof n[n[i]]!="number"),o={};for(const i of s)o[i]=n[i];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(s){return n[s]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const s=[];for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&s.push(o);return s},t.find=(n,s)=>{for(const o of n)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function a(n,s=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=a,t.jsonStringifyReplacer=(n,s)=>typeof s=="bigint"?s.toString():s})(qe||(qe={}));var Dc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Dc||(Dc={}));const le=qe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),hn=t=>{switch(typeof t){case"undefined":return le.undefined;case"string":return le.string;case"number":return Number.isNaN(t)?le.nan:le.number;case"boolean":return le.boolean;case"function":return le.function;case"bigint":return le.bigint;case"symbol":return le.symbol;case"object":return Array.isArray(t)?le.array:t===null?le.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?le.promise:typeof Map<"u"&&t instanceof Map?le.map:typeof Set<"u"&&t instanceof Set?le.set:typeof Date<"u"&&t instanceof Date?le.date:le.object;default:return le.unknown}},X=qe.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"]),yS=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class ur extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(o))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return n(this),a}static assert(e){if(!(e instanceof ur))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,qe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},a=[];for(const n of this.issues)if(n.path.length>0){const s=n.path[0];r[s]=r[s]||[],r[s].push(e(n))}else a.push(e(n));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}}ur.create=t=>new ur(t);const xa=(t,e)=>{let r;switch(t.code){case X.invalid_type:t.received===le.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case X.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,qe.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:r=`Unrecognized key(s) in object: ${qe.joinValues(t.keys,", ")}`;break;case X.invalid_union:r="Invalid input";break;case X.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${qe.joinValues(t.options)}`;break;case X.invalid_enum_value:r=`Invalid enum value. Expected ${qe.joinValues(t.options)}, received '${t.received}'`;break;case X.invalid_arguments:r="Invalid function arguments";break;case X.invalid_return_type:r="Invalid function return type";break;case X.invalid_date:r="Invalid date";break;case X.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:qe.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case X.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case X.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case X.custom:r="Invalid input";break;case X.invalid_intersection_types:r="Intersection results could not be merged";break;case X.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case X.not_finite:r="Number must be finite";break;default:r=e.defaultError,qe.assertNever(t)}return{message:r}};let Jf=xa;function _S(t){Jf=t}function ri(){return Jf}const ni=t=>{const{data:e,path:r,errorMaps:a,issueData:n}=t,s=[...r,...n.path||[]],o={...n,path:s};if(n.message!==void 0)return{...n,path:s,message:n.message};let i="";const l=a.filter(c=>!!c).slice().reverse();for(const c of l)i=c(o,{data:e,defaultError:i}).message;return{...n,path:s,message:i}},wS=[];function ae(t,e){const r=ri(),a=ni({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===xa?void 0:xa].filter(n=>!!n)});t.common.issues.push(a)}class Zt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const a=[];for(const n of r){if(n.status==="aborted")return be;n.status==="dirty"&&e.dirty(),a.push(n.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,r){const a=[];for(const n of r){const s=await n.key,o=await n.value;a.push({key:s,value:o})}return Zt.mergeObjectSync(e,a)}static mergeObjectSync(e,r){const a={};for(const n of r){const{key:s,value:o}=n;if(s.status==="aborted"||o.status==="aborted")return be;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(a[s.value]=o.value)}return{status:e.value,value:a}}}const be=Object.freeze({status:"aborted"}),Ta=t=>({status:"dirty",value:t}),Jt=t=>({status:"valid",value:t}),Lc=t=>t.status==="aborted",zc=t=>t.status==="dirty",Kn=t=>t.status==="valid",bs=t=>typeof Promise<"u"&&t instanceof Promise;var he;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(he||(he={}));class Jr{constructor(e,r,a,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=a,this._key=n}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 Gf=(t,e)=>{if(Kn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new ur(t.common.issues);return this._error=r,this._error}}};function Ce(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,i)=>{const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??a??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:n}}let Oe=class{get description(){return this._def.description}_getType(e){return hn(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:hn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Zt,ctx:{common:e.parent.common,data:e.data,parsedType:hn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(bs(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const a=this.safeParse(e,r);if(a.success)return a.data;throw a.error}safeParse(e,r){const a={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hn(e)},n=this._parseSync({data:e,path:a.path,parent:a});return Gf(a,n)}"~validate"(e){var a,n;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hn(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:r});return Kn(s)?{value:s.value}:{issues:r.common.issues}}catch(s){(n=(a=s==null?void 0:s.message)==null?void 0:a.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>Kn(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){const a=await this.safeParseAsync(e,r);if(a.success)return a.data;throw a.error}async safeParseAsync(e,r){const a={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hn(e)},n=this._parse({data:e,path:a.path,parent:a}),s=await(bs(n)?n:Promise.resolve(n));return Gf(a,s)}refine(e,r){const a=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,s)=>{const o=e(n),i=()=>s.addIssue({code:X.custom,...a(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,r){return this._refinement((a,n)=>e(a)?!0:(n.addIssue(typeof r=="function"?r(a,n):r),!1))}_refinement(e){return new Cr({schema:this,typeName:V.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Kr.create(this,this._def)}nullable(){return xn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yn.create(this)}promise(){return Aa.create(this,this._def)}or(e){return ks.create([this,e],this._def)}and(e){return Is.create(this,e,this._def)}transform(e){return new Cr({...Ce(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Os({...Ce(this._def),innerType:this,defaultValue:r,typeName:V.ZodDefault})}brand(){return new Fc({typeName:V.ZodBranded,type:this,...Ce(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new Ns({...Ce(this._def),innerType:this,catchValue:r,typeName:V.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return As.create(this,e)}readonly(){return Ms.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const bS=/^c[^\s-]{8,}$/i,ES=/^[0-9a-z]+$/,SS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$S=/^[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,PS=/^[a-z0-9_-]{21}$/i,kS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,IS=/^[-+]?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)?)??$/,xS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,TS="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Uc;const CS=/^(?:(?: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])$/,RS=/^(?:(?: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])$/,OS=/^(([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]))$/,NS=/^(([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])$/,AS=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,MS=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Kf="((\\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])))",jS=new RegExp(`^${Kf}$`);function Wf(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function DS(t){return new RegExp(`^${Wf(t)}$`)}function Qf(t){let e=`${Kf}T${Wf(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function LS(t,e){return!!((e==="v4"||!e)&&CS.test(t)||(e==="v6"||!e)&&OS.test(t))}function zS(t,e){if(!kS.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function US(t,e){return!!((e==="v4"||!e)&&RS.test(t)||(e==="v6"||!e)&&NS.test(t))}let Ca=class Oo extends Oe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==le.string){const s=this._getOrReturnCtx(e);return ae(s,{code:X.invalid_type,expected:le.string,received:s.parsedType}),be}const a=new Zt;let n;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:X.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="max")e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:X.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="length"){const o=e.data.length>s.value,i=e.data.length<s.value;(o||i)&&(n=this._getOrReturnCtx(e,n),o?ae(n,{code:X.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&ae(n,{code:X.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),a.dirty())}else if(s.kind==="email")xS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"email",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="emoji")Uc||(Uc=new RegExp(TS,"u")),Uc.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"emoji",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="uuid")$S.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"uuid",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="nanoid")PS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"nanoid",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid")bS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"cuid",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid2")ES.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"cuid2",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="ulid")SS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"ulid",code:X.invalid_string,message:s.message}),a.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),ae(n,{validation:"url",code:X.invalid_string,message:s.message}),a.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"regex",code:X.invalid_string,message:s.message}),a.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),a.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:{startsWith:s.value},message:s.message}),a.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:{endsWith:s.value},message:s.message}),a.dirty()):s.kind==="datetime"?Qf(s).test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:"datetime",message:s.message}),a.dirty()):s.kind==="date"?jS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:"date",message:s.message}),a.dirty()):s.kind==="time"?DS(s).test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:X.invalid_string,validation:"time",message:s.message}),a.dirty()):s.kind==="duration"?IS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"duration",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="ip"?LS(e.data,s.version)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"ip",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="jwt"?zS(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"jwt",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="cidr"?US(e.data,s.version)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"cidr",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="base64"?AS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"base64",code:X.invalid_string,message:s.message}),a.dirty()):s.kind==="base64url"?MS.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"base64url",code:X.invalid_string,message:s.message}),a.dirty()):qe.assertNever(s);return{status:a.value,value:e.data}}_regex(e,r,a){return this.refinement(n=>e.test(n),{validation:r,code:X.invalid_string,...he.errToObj(a)})}_addCheck(e){return new Oo({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...he.errToObj(e)})}url(e){return this._addCheck({kind:"url",...he.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...he.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...he.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...he.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...he.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...he.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...he.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...he.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...he.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...he.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...he.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...he.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...he.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...he.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...he.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...he.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...he.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...he.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...he.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...he.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...he.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...he.errToObj(r)})}nonempty(e){return this.min(1,he.errToObj(e))}trim(){return new Oo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Oo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Oo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ca.create=t=>new Ca({checks:[],typeName:V.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Ce(t)});function qS(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}let Es=class bp extends Oe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==le.number){const s=this._getOrReturnCtx(e);return ae(s,{code:X.invalid_type,expected:le.number,received:s.parsedType}),be}let a;const n=new Zt;for(const s of this._def.checks)s.kind==="int"?qe.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),ae(a,{code:X.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="multipleOf"?qS(e.data,s.value)!==0&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),ae(a,{code:X.not_finite,message:s.message}),n.dirty()):qe.assertNever(s);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,he.toString(r))}gt(e,r){return this.setLimit("min",e,!1,he.toString(r))}lte(e,r){return this.setLimit("max",e,!0,he.toString(r))}lt(e,r){return this.setLimit("max",e,!1,he.toString(r))}setLimit(e,r,a,n){return new bp({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:he.toString(n)}]})}_addCheck(e){return new bp({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:he.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:he.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:he.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:he.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:he.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:he.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&qe.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Es.create=t=>new Es({checks:[],typeName:V.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ce(t)});class In extends Oe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==le.bigint)return this._getInvalidInput(e);let a;const n=new Zt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:X.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):qe.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return ae(r,{code:X.invalid_type,expected:le.bigint,received:r.parsedType}),be}gte(e,r){return this.setLimit("min",e,!0,he.toString(r))}gt(e,r){return this.setLimit("min",e,!1,he.toString(r))}lte(e,r){return this.setLimit("max",e,!0,he.toString(r))}lt(e,r){return this.setLimit("max",e,!1,he.toString(r))}setLimit(e,r,a,n){return new In({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:he.toString(n)}]})}_addCheck(e){return new In({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:he.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:he.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:he.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:he.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:he.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}In.create=t=>new In({checks:[],typeName:V.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Ce(t)});let Ss=class extends Oe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==le.boolean){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.boolean,received:a.parsedType}),be}return Jt(e.data)}};Ss.create=t=>new Ss({typeName:V.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ce(t)});class Wn extends Oe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==le.date){const s=this._getOrReturnCtx(e);return ae(s,{code:X.invalid_type,expected:le.date,received:s.parsedType}),be}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return ae(s,{code:X.invalid_date}),be}const a=new Zt;let n;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:X.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),a.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:X.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),a.dirty()):qe.assertNever(s);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Wn({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:he.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:he.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}Wn.create=t=>new Wn({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:V.ZodDate,...Ce(t)});class ai extends Oe{_parse(e){if(this._getType(e)!==le.symbol){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.symbol,received:a.parsedType}),be}return Jt(e.data)}}ai.create=t=>new ai({typeName:V.ZodSymbol,...Ce(t)});class $s extends Oe{_parse(e){if(this._getType(e)!==le.undefined){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.undefined,received:a.parsedType}),be}return Jt(e.data)}}$s.create=t=>new $s({typeName:V.ZodUndefined,...Ce(t)});let Ps=class extends Oe{_parse(e){if(this._getType(e)!==le.null){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.null,received:a.parsedType}),be}return Jt(e.data)}};Ps.create=t=>new Ps({typeName:V.ZodNull,...Ce(t)});let Ra=class extends Oe{constructor(){super(...arguments),this._any=!0}_parse(e){return Jt(e.data)}};Ra.create=t=>new Ra({typeName:V.ZodAny,...Ce(t)});let Qn=class extends Oe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Jt(e.data)}};Qn.create=t=>new Qn({typeName:V.ZodUnknown,...Ce(t)});let mn=class extends Oe{_parse(e){const r=this._getOrReturnCtx(e);return ae(r,{code:X.invalid_type,expected:le.never,received:r.parsedType}),be}};mn.create=t=>new mn({typeName:V.ZodNever,...Ce(t)});class si extends Oe{_parse(e){if(this._getType(e)!==le.undefined){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.void,received:a.parsedType}),be}return Jt(e.data)}}si.create=t=>new si({typeName:V.ZodVoid,...Ce(t)});let Yn=class Nl extends Oe{_parse(e){const{ctx:r,status:a}=this._processInputParams(e),n=this._def;if(r.parsedType!==le.array)return ae(r,{code:X.invalid_type,expected:le.array,received:r.parsedType}),be;if(n.exactLength!==null){const o=r.data.length>n.exactLength.value,i=r.data.length<n.exactLength.value;(o||i)&&(ae(r,{code:o?X.too_big:X.too_small,minimum:i?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),a.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(ae(r,{code:X.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),a.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(ae(r,{code:X.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((o,i)=>n.type._parseAsync(new Jr(r,o,r.path,i)))).then(o=>Zt.mergeArray(a,o));const s=[...r.data].map((o,i)=>n.type._parseSync(new Jr(r,o,r.path,i)));return Zt.mergeArray(a,s)}get element(){return this._def.type}min(e,r){return new Nl({...this._def,minLength:{value:e,message:he.toString(r)}})}max(e,r){return new Nl({...this._def,maxLength:{value:e,message:he.toString(r)}})}length(e,r){return new Nl({...this._def,exactLength:{value:e,message:he.toString(r)}})}nonempty(e){return this.min(1,e)}};Yn.create=(t,e)=>new Yn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...Ce(e)});function Oa(t){if(t instanceof gr){const e={};for(const r in t.shape){const a=t.shape[r];e[r]=Kr.create(Oa(a))}return new gr({...t._def,shape:()=>e})}else return t instanceof Yn?new Yn({...t._def,type:Oa(t.element)}):t instanceof Kr?Kr.create(Oa(t.unwrap())):t instanceof xn?xn.create(Oa(t.unwrap())):t instanceof Gr?Gr.create(t.items.map(e=>Oa(e))):t}let gr=class Fr extends Oe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=qe.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==le.object){const c=this._getOrReturnCtx(e);return ae(c,{code:X.invalid_type,expected:le.object,received:c.parsedType}),be}const{status:a,ctx:n}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof mn&&this._def.unknownKeys==="strip"))for(const c in n.data)o.includes(c)||i.push(c);const l=[];for(const c of o){const u=s[c],f=n.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Jr(n,f,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof mn){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(c==="strict")i.length>0&&(ae(n,{code:X.unrecognized_keys,keys:i}),a.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=n.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Jr(n,f,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const f=await u.key,g=await u.value;c.push({key:f,value:g,alwaysSet:u.alwaysSet})}return c}).then(c=>Zt.mergeObjectSync(a,c)):Zt.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return he.errToObj,new Fr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,a)=>{var s,o;const n=((o=(s=this._def).errorMap)==null?void 0:o.call(s,r,a).message)??a.defaultError;return r.code==="unrecognized_keys"?{message:he.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new Fr({...this._def,unknownKeys:"strip"})}passthrough(){return new Fr({...this._def,unknownKeys:"passthrough"})}extend(e){return new Fr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Fr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:V.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new Fr({...this._def,catchall:e})}pick(e){const r={};for(const a of qe.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new Fr({...this._def,shape:()=>r})}omit(e){const r={};for(const a of qe.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new Fr({...this._def,shape:()=>r})}deepPartial(){return Oa(this)}partial(e){const r={};for(const a of qe.objectKeys(this.shape)){const n=this.shape[a];e&&!e[a]?r[a]=n:r[a]=n.optional()}return new Fr({...this._def,shape:()=>r})}required(e){const r={};for(const a of qe.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let s=this.shape[a];for(;s instanceof Kr;)s=s._def.innerType;r[a]=s}return new Fr({...this._def,shape:()=>r})}keyof(){return eh(qe.objectKeys(this.shape))}};gr.create=(t,e)=>new gr({shape:()=>t,unknownKeys:"strip",catchall:mn.create(),typeName:V.ZodObject,...Ce(e)}),gr.strictCreate=(t,e)=>new gr({shape:()=>t,unknownKeys:"strict",catchall:mn.create(),typeName:V.ZodObject,...Ce(e)}),gr.lazycreate=(t,e)=>new gr({shape:t,unknownKeys:"strip",catchall:mn.create(),typeName:V.ZodObject,...Ce(e)});let ks=class extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a=this._def.options;function n(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 o=s.map(i=>new ur(i.ctx.common.issues));return ae(r,{code:X.invalid_union,unionErrors:o}),be}if(r.common.async)return Promise.all(a.map(async s=>{const o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let s;const o=[];for(const l of a){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&&o.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=o.map(l=>new ur(l));return ae(r,{code:X.invalid_union,unionErrors:i}),be}}get options(){return this._def.options}};ks.create=(t,e)=>new ks({options:t,typeName:V.ZodUnion,...Ce(e)});const vn=t=>t instanceof xs?vn(t.schema):t instanceof Cr?vn(t.innerType()):t instanceof Ts?[t.value]:t instanceof Cs?t.options:t instanceof Rs?qe.objectValues(t.enum):t instanceof Os?vn(t._def.innerType):t instanceof $s?[void 0]:t instanceof Ps?[null]:t instanceof Kr?[void 0,...vn(t.unwrap())]:t instanceof xn?[null,...vn(t.unwrap())]:t instanceof Fc||t instanceof Ms?vn(t.unwrap()):t instanceof Ns?vn(t._def.innerType):[];let Yf=class sw extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==le.object)return ae(r,{code:X.invalid_type,expected:le.object,received:r.parsedType}),be;const a=this.discriminator,n=r.data[a],s=this.optionsMap.get(n);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}):(ae(r,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),be)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,a){const n=new Map;for(const s of r){const o=vn(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of o){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new sw({typeName:V.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...Ce(a)})}};function qc(t,e){const r=hn(t),a=hn(e);if(t===e)return{valid:!0,data:t};if(r===le.object&&a===le.object){const n=qe.objectKeys(e),s=qe.objectKeys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(const i of s){const l=qc(t[i],e[i]);if(!l.valid)return{valid:!1};o[i]=l.data}return{valid:!0,data:o}}else if(r===le.array&&a===le.array){if(t.length!==e.length)return{valid:!1};const n=[];for(let s=0;s<t.length;s++){const o=t[s],i=e[s],l=qc(o,i);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return r===le.date&&a===le.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let Is=class extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=(s,o)=>{if(Lc(s)||Lc(o))return be;const i=qc(s.value,o.value);return i.valid?((zc(s)||zc(o))&&r.dirty(),{status:r.value,value:i.data}):(ae(a,{code:X.invalid_intersection_types}),be)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([s,o])=>n(s,o)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};Is.create=(t,e,r)=>new Is({left:t,right:e,typeName:V.ZodIntersection,...Ce(r)});class Gr extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==le.array)return ae(a,{code:X.invalid_type,expected:le.array,received:a.parsedType}),be;if(a.data.length<this._def.items.length)return ae(a,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),be;!this._def.rest&&a.data.length>this._def.items.length&&(ae(a,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...a.data].map((o,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new Jr(a,o,a.path,i)):null}).filter(o=>!!o);return a.common.async?Promise.all(s).then(o=>Zt.mergeArray(r,o)):Zt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new Gr({...this._def,rest:e})}}Gr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Gr({items:t,typeName:V.ZodTuple,rest:null,...Ce(e)})};let Xf=class Ep extends Oe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==le.object)return ae(a,{code:X.invalid_type,expected:le.object,received:a.parsedType}),be;const n=[],s=this._def.keyType,o=this._def.valueType;for(const i in a.data)n.push({key:s._parse(new Jr(a,i,a.path,i)),value:o._parse(new Jr(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?Zt.mergeObjectAsync(r,n):Zt.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,a){return r instanceof Oe?new Ep({keyType:e,valueType:r,typeName:V.ZodRecord,...Ce(a)}):new Ep({keyType:Ca.create(),valueType:e,typeName:V.ZodRecord,...Ce(r)})}};class oi extends Oe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==le.map)return ae(a,{code:X.invalid_type,expected:le.map,received:a.parsedType}),be;const n=this._def.keyType,s=this._def.valueType,o=[...a.data.entries()].map(([i,l],c)=>({key:n._parse(new Jr(a,i,a.path,[c,"key"])),value:s._parse(new Jr(a,l,a.path,[c,"value"]))}));if(a.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return be;(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 o){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return be;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}oi.create=(t,e,r)=>new oi({valueType:e,keyType:t,typeName:V.ZodMap,...Ce(r)});class Xn extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==le.set)return ae(a,{code:X.invalid_type,expected:le.set,received:a.parsedType}),be;const n=this._def;n.minSize!==null&&a.data.size<n.minSize.value&&(ae(a,{code:X.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&a.data.size>n.maxSize.value&&(ae(a,{code:X.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());const s=this._def.valueType;function o(l){const c=new Set;for(const u of l){if(u.status==="aborted")return be;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...a.data.values()].map((l,c)=>s._parse(new Jr(a,l,a.path,c)));return a.common.async?Promise.all(i).then(l=>o(l)):o(i)}min(e,r){return new Xn({...this._def,minSize:{value:e,message:he.toString(r)}})}max(e,r){return new Xn({...this._def,maxSize:{value:e,message:he.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Xn.create=(t,e)=>new Xn({valueType:t,minSize:null,maxSize:null,typeName:V.ZodSet,...Ce(e)});class Na extends Oe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==le.function)return ae(r,{code:X.invalid_type,expected:le.function,received:r.parsedType}),be;function a(i,l){return ni({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ri(),xa].filter(c=>!!c),issueData:{code:X.invalid_arguments,argumentsError:l}})}function n(i,l){return ni({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ri(),xa].filter(c=>!!c),issueData:{code:X.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Aa){const i=this;return Jt(async function(...l){const c=new ur([]),u=await i._def.args.parseAsync(l,s).catch(d=>{throw c.addIssue(a(l,d)),c}),f=await Reflect.apply(o,this,u);return await i._def.returns._def.type.parseAsync(f,s).catch(d=>{throw c.addIssue(n(f,d)),c})})}else{const i=this;return Jt(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new ur([a(l,c.error)]);const u=Reflect.apply(o,this,c.data),f=i._def.returns.safeParse(u,s);if(!f.success)throw new ur([n(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Na({...this._def,args:Gr.create(e).rest(Qn.create())})}returns(e){return new Na({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,a){return new Na({args:e||Gr.create([]).rest(Qn.create()),returns:r||Qn.create(),typeName:V.ZodFunction,...Ce(a)})}}let xs=class extends Oe{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};xs.create=(t,e)=>new xs({getter:t,typeName:V.ZodLazy,...Ce(e)});let Ts=class extends Oe{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return ae(r,{received:r.data,code:X.invalid_literal,expected:this._def.value}),be}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ts.create=(t,e)=>new Ts({value:t,typeName:V.ZodLiteral,...Ce(e)});function eh(t,e){return new Cs({values:t,typeName:V.ZodEnum,...Ce(e)})}let Cs=class Sp extends Oe{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),a=this._def.values;return ae(r,{expected:qe.joinValues(a),received:r.parsedType,code:X.invalid_type}),be}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),a=this._def.values;return ae(r,{received:r.data,code:X.invalid_enum_value,options:a}),be}return Jt(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Sp.create(e,{...this._def,...r})}exclude(e,r=this._def){return Sp.create(this.options.filter(a=>!e.includes(a)),{...this._def,...r})}};Cs.create=eh;class Rs extends Oe{_parse(e){const r=qe.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==le.string&&a.parsedType!==le.number){const n=qe.objectValues(r);return ae(a,{expected:qe.joinValues(n),received:a.parsedType,code:X.invalid_type}),be}if(this._cache||(this._cache=new Set(qe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=qe.objectValues(r);return ae(a,{received:a.data,code:X.invalid_enum_value,options:n}),be}return Jt(e.data)}get enum(){return this._def.values}}Rs.create=(t,e)=>new Rs({values:t,typeName:V.ZodNativeEnum,...Ce(e)});class Aa extends Oe{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==le.promise&&r.common.async===!1)return ae(r,{code:X.invalid_type,expected:le.promise,received:r.parsedType}),be;const a=r.parsedType===le.promise?r.data:Promise.resolve(r.data);return Jt(a.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Aa.create=(t,e)=>new Aa({type:t,typeName:V.ZodPromise,...Ce(e)});class Cr extends Oe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:o=>{ae(a,o),o.fatal?r.abort():r.dirty()},get path(){return a.path}};if(s.addIssue=s.addIssue.bind(s),n.type==="preprocess"){const o=n.transform(a.data,s);if(a.common.async)return Promise.resolve(o).then(async i=>{if(r.value==="aborted")return be;const l=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return l.status==="aborted"?be:l.status==="dirty"||r.value==="dirty"?Ta(l.value):l});{if(r.value==="aborted")return be;const i=this._def.schema._parseSync({data:o,path:a.path,parent:a});return i.status==="aborted"?be:i.status==="dirty"||r.value==="dirty"?Ta(i.value):i}}if(n.type==="refinement"){const o=i=>{const l=n.refinement(i,s);if(a.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(a.common.async===!1){const i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?be:(i.status==="dirty"&&r.dirty(),o(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?be:(i.status==="dirty"&&r.dirty(),o(i.value).then(()=>({status:r.value,value:i.value}))))}if(n.type==="transform")if(a.common.async===!1){const o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!Kn(o))return be;const i=n.transform(o.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:a.data,path:a.path,parent:a}).then(o=>Kn(o)?Promise.resolve(n.transform(o.value,s)).then(i=>({status:r.value,value:i})):be);qe.assertNever(n)}}Cr.create=(t,e,r)=>new Cr({schema:t,typeName:V.ZodEffects,effect:e,...Ce(r)}),Cr.createWithPreprocess=(t,e,r)=>new Cr({schema:e,effect:{type:"preprocess",transform:t},typeName:V.ZodEffects,...Ce(r)});let Kr=class extends Oe{_parse(e){return this._getType(e)===le.undefined?Jt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Kr.create=(t,e)=>new Kr({innerType:t,typeName:V.ZodOptional,...Ce(e)});let xn=class extends Oe{_parse(e){return this._getType(e)===le.null?Jt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xn.create=(t,e)=>new xn({innerType:t,typeName:V.ZodNullable,...Ce(e)});let Os=class extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e);let a=r.data;return r.parsedType===le.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Os.create=(t,e)=>new Os({innerType:t,typeName:V.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ce(e)});let Ns=class extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return bs(n)?n.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ur(a.common.issues)},input:a.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new ur(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};Ns.create=(t,e)=>new Ns({innerType:t,typeName:V.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ce(e)});class ii extends Oe{_parse(e){if(this._getType(e)!==le.nan){const a=this._getOrReturnCtx(e);return ae(a,{code:X.invalid_type,expected:le.nan,received:a.parsedType}),be}return{status:"valid",value:e.data}}}ii.create=t=>new ii({typeName:V.ZodNaN,...Ce(t)});const FS=Symbol("zod_brand");class Fc extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}}class As extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?be:s.status==="dirty"?(r.dirty(),Ta(s.value)):this._def.out._parseAsync({data:s.value,path:a.path,parent:a})})();{const n=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?be:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:a.path,parent:a})}}static create(e,r){return new As({in:e,out:r,typeName:V.ZodPipeline})}}let Ms=class extends Oe{_parse(e){const r=this._def.innerType._parse(e),a=n=>(Kn(n)&&(n.value=Object.freeze(n.value)),n);return bs(r)?r.then(n=>a(n)):a(r)}unwrap(){return this._def.innerType}};Ms.create=(t,e)=>new Ms({innerType:t,typeName:V.ZodReadonly,...Ce(e)});function th(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function rh(t,e={},r){return t?Ra.create().superRefine((a,n)=>{const s=t(a);if(s instanceof Promise)return s.then(o=>{if(!o){const i=th(e,a),l=i.fatal??r??!0;n.addIssue({code:"custom",...i,fatal:l})}});if(!s){const o=th(e,a),i=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:i})}}):Ra.create()}const ZS={object:gr.lazycreate};var V;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(V||(V={}));const VS=(t,e={message:`Input not instance of ${t.name}`})=>rh(r=>r instanceof t,e),L=Ca.create,St=Es.create,HS=ii.create,BS=In.create,yt=Ss.create,JS=Wn.create,GS=ai.create,KS=$s.create,WS=Ps.create,nh=Ra.create,Ma=Qn.create,QS=mn.create,YS=si.create,ue=Yn.create,te=gr.create,XS=gr.strictCreate,Vt=ks.create,ah=Yf.create,e$=Is.create,t$=Gr.create,ja=Xf.create,r$=oi.create,n$=Xn.create,a$=Na.create,s$=xs.create,Ie=Ts.create,Wr=Cs.create,o$=Rs.create,i$=Aa.create,sh=Cr.create,Y=Kr.create,l$=xn.create,c$=Cr.createWithPreprocess,u$=As.create,d$=()=>L().optional(),p$=()=>St().optional(),f$=()=>yt().optional(),h$={string:t=>Ca.create({...t,coerce:!0}),number:t=>Es.create({...t,coerce:!0}),boolean:t=>Ss.create({...t,coerce:!0}),bigint:t=>In.create({...t,coerce:!0}),date:t=>Wn.create({...t,coerce:!0})},oh=be,m$=Object.freeze(Object.defineProperty({__proto__:null,BRAND:FS,DIRTY:Ta,EMPTY_PATH:wS,INVALID:be,NEVER:oh,OK:Jt,ParseStatus:Zt,Schema:Oe,ZodAny:Ra,ZodArray:Yn,ZodBigInt:In,ZodBoolean:Ss,ZodBranded:Fc,ZodCatch:Ns,ZodDate:Wn,ZodDefault:Os,ZodDiscriminatedUnion:Yf,ZodEffects:Cr,ZodEnum:Cs,ZodError:ur,get ZodFirstPartyTypeKind(){return V},ZodFunction:Na,ZodIntersection:Is,ZodIssueCode:X,ZodLazy:xs,ZodLiteral:Ts,ZodMap:oi,ZodNaN:ii,ZodNativeEnum:Rs,ZodNever:mn,ZodNull:Ps,ZodNullable:xn,ZodNumber:Es,ZodObject:gr,ZodOptional:Kr,ZodParsedType:le,ZodPipeline:As,ZodPromise:Aa,ZodReadonly:Ms,ZodRecord:Xf,ZodSchema:Oe,ZodSet:Xn,ZodString:Ca,ZodSymbol:ai,ZodTransformer:Cr,ZodTuple:Gr,ZodType:Oe,ZodUndefined:$s,ZodUnion:ks,ZodUnknown:Qn,ZodVoid:si,addIssueToContext:ae,any:nh,array:ue,bigint:BS,boolean:yt,coerce:h$,custom:rh,date:JS,datetimeRegex:Qf,defaultErrorMap:xa,discriminatedUnion:ah,effect:sh,enum:Wr,function:a$,getErrorMap:ri,getParsedType:hn,instanceof:VS,intersection:e$,isAborted:Lc,isAsync:bs,isDirty:zc,isValid:Kn,late:ZS,lazy:s$,literal:Ie,makeIssue:ni,map:r$,nan:HS,nativeEnum:o$,never:QS,null:WS,nullable:l$,number:St,object:te,get objectUtil(){return Dc},oboolean:f$,onumber:p$,optional:Y,ostring:d$,pipeline:u$,preprocess:c$,promise:i$,quotelessJson:yS,record:ja,set:n$,setErrorMap:_S,strictObject:XS,string:L,symbol:GS,transformer:sh,tuple:t$,undefined:KS,union:Vt,unknown:Ma,get util(){return qe},void:YS},Symbol.toStringTag,{value:"Module"})),js="2025-06-18",ih=[js,"2025-03-26","2024-11-05","2024-10-07"],li="2.0",lh=Vt([L(),St().int()]),ch=L(),v$=te({progressToken:Y(lh)}).passthrough(),yr=te({_meta:Y(v$)}).passthrough(),Xt=te({method:L(),params:Y(yr)}),Ds=te({_meta:Y(te({}).passthrough())}).passthrough(),Qr=te({method:L(),params:Y(Ds)}),_r=te({_meta:Y(te({}).passthrough())}).passthrough(),ci=Vt([L(),St().int()]),uh=te({jsonrpc:Ie(li),id:ci}).merge(Xt).strict(),dh=t=>uh.safeParse(t).success,ph=te({jsonrpc:Ie(li)}).merge(Qr).strict(),g$=t=>ph.safeParse(t).success,fh=te({jsonrpc:Ie(li),id:ci,result:_r}).strict(),Zc=t=>fh.safeParse(t).success;var rt;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(rt||(rt={}));const hh=te({jsonrpc:Ie(li),id:ci,error:te({code:St().int(),message:L(),data:Y(Ma())})}).strict(),y$=t=>hh.safeParse(t).success,gn=Vt([uh,ph,fh,hh]),Tn=_r.strict(),Vc=Qr.extend({method:Ie("notifications/cancelled"),params:Ds.extend({requestId:ci,reason:L().optional()})}),_$=te({src:L(),mimeType:Y(L()),sizes:Y(ue(L()))}).passthrough(),Ls=te({icons:ue(_$).optional()}).passthrough(),zs=te({name:L(),title:Y(L())}).passthrough(),mh=zs.extend({version:L(),websiteUrl:Y(L())}).merge(Ls),w$=te({experimental:Y(te({}).passthrough()),sampling:Y(te({}).passthrough()),elicitation:Y(te({}).passthrough()),roots:Y(te({listChanged:Y(yt())}).passthrough())}).passthrough(),vh=Xt.extend({method:Ie("initialize"),params:yr.extend({protocolVersion:L(),capabilities:w$,clientInfo:mh})}),b$=te({experimental:Y(te({}).passthrough()),logging:Y(te({}).passthrough()),completions:Y(te({}).passthrough()),prompts:Y(te({listChanged:Y(yt())}).passthrough()),resources:Y(te({subscribe:Y(yt()),listChanged:Y(yt())}).passthrough()),tools:Y(te({listChanged:Y(yt())}).passthrough())}).passthrough(),gh=_r.extend({protocolVersion:L(),capabilities:b$,serverInfo:mh,instructions:Y(L())}),Hc=Qr.extend({method:Ie("notifications/initialized")}),E$=t=>Hc.safeParse(t).success,Bc=Xt.extend({method:Ie("ping")}),S$=te({progress:St(),total:Y(St()),message:Y(L())}).passthrough(),Jc=Qr.extend({method:Ie("notifications/progress"),params:Ds.merge(S$).extend({progressToken:lh})}),ui=Xt.extend({params:yr.extend({cursor:Y(ch)}).optional()}),di=_r.extend({nextCursor:Y(ch)}),yh=te({uri:L(),mimeType:Y(L()),_meta:Y(te({}).passthrough())}).passthrough(),_h=yh.extend({text:L()}),Gc=L().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),wh=yh.extend({blob:Gc}),bh=zs.extend({uri:L(),description:Y(L()),mimeType:Y(L()),_meta:Y(te({}).passthrough())}).merge(Ls),$$=zs.extend({uriTemplate:L(),description:Y(L()),mimeType:Y(L()),_meta:Y(te({}).passthrough())}).merge(Ls),pi=ui.extend({method:Ie("resources/list")}),Eh=di.extend({resources:ue(bh)}),Kc=ui.extend({method:Ie("resources/templates/list")}),Sh=di.extend({resourceTemplates:ue($$)}),Wc=Xt.extend({method:Ie("resources/read"),params:yr.extend({uri:L()})}),$h=_r.extend({contents:ue(Vt([_h,wh]))}),Ph=Qr.extend({method:Ie("notifications/resources/list_changed")}),kh=Xt.extend({method:Ie("resources/subscribe"),params:yr.extend({uri:L()})}),Ih=Xt.extend({method:Ie("resources/unsubscribe"),params:yr.extend({uri:L()})}),xh=Qr.extend({method:Ie("notifications/resources/updated"),params:Ds.extend({uri:L()})}),P$=te({name:L(),description:Y(L()),required:Y(yt())}).passthrough(),k$=zs.extend({description:Y(L()),arguments:Y(ue(P$)),_meta:Y(te({}).passthrough())}).merge(Ls),Qc=ui.extend({method:Ie("prompts/list")}),Th=di.extend({prompts:ue(k$)}),Yc=Xt.extend({method:Ie("prompts/get"),params:yr.extend({name:L(),arguments:Y(ja(L()))})}),Xc=te({type:Ie("text"),text:L(),_meta:Y(te({}).passthrough())}).passthrough(),eu=te({type:Ie("image"),data:Gc,mimeType:L(),_meta:Y(te({}).passthrough())}).passthrough(),tu=te({type:Ie("audio"),data:Gc,mimeType:L(),_meta:Y(te({}).passthrough())}).passthrough(),I$=te({type:Ie("resource"),resource:Vt([_h,wh]),_meta:Y(te({}).passthrough())}).passthrough(),x$=bh.extend({type:Ie("resource_link")}),Ch=Vt([Xc,eu,tu,x$,I$]),T$=te({role:Wr(["user","assistant"]),content:Ch}).passthrough(),Rh=_r.extend({description:Y(L()),messages:ue(T$)}),Oh=Qr.extend({method:Ie("notifications/prompts/list_changed")}),C$=te({title:Y(L()),readOnlyHint:Y(yt()),destructiveHint:Y(yt()),idempotentHint:Y(yt()),openWorldHint:Y(yt())}).passthrough(),R$=zs.extend({description:Y(L()),inputSchema:te({type:Ie("object"),properties:Y(te({}).passthrough()),required:Y(ue(L()))}).passthrough(),outputSchema:Y(te({type:Ie("object"),properties:Y(te({}).passthrough()),required:Y(ue(L()))}).passthrough()),annotations:Y(C$),_meta:Y(te({}).passthrough())}).merge(Ls),ru=ui.extend({method:Ie("tools/list")}),Nh=di.extend({tools:ue(R$)}),fi=_r.extend({content:ue(Ch).default([]),structuredContent:te({}).passthrough().optional(),isError:Y(yt())});fi.or(_r.extend({toolResult:Ma()}));const nu=Xt.extend({method:Ie("tools/call"),params:yr.extend({name:L(),arguments:Y(ja(Ma()))})}),Ah=Qr.extend({method:Ie("notifications/tools/list_changed")}),hi=Wr(["debug","info","notice","warning","error","critical","alert","emergency"]),mi=Xt.extend({method:Ie("logging/setLevel"),params:yr.extend({level:hi})}),Mh=Qr.extend({method:Ie("notifications/message"),params:Ds.extend({level:hi,logger:Y(L()),data:Ma()})}),O$=te({name:L().optional()}).passthrough(),N$=te({hints:Y(ue(O$)),costPriority:Y(St().min(0).max(1)),speedPriority:Y(St().min(0).max(1)),intelligencePriority:Y(St().min(0).max(1))}).passthrough(),A$=te({role:Wr(["user","assistant"]),content:Vt([Xc,eu,tu])}).passthrough(),jh=Xt.extend({method:Ie("sampling/createMessage"),params:yr.extend({messages:ue(A$),systemPrompt:Y(L()),includeContext:Y(Wr(["none","thisServer","allServers"])),temperature:Y(St()),maxTokens:St().int(),stopSequences:Y(ue(L())),metadata:Y(te({}).passthrough()),modelPreferences:Y(N$)})}),au=_r.extend({model:L(),stopReason:Y(Wr(["endTurn","stopSequence","maxTokens"]).or(L())),role:Wr(["user","assistant"]),content:ah("type",[Xc,eu,tu])}),M$=te({type:Ie("boolean"),title:Y(L()),description:Y(L()),default:Y(yt())}).passthrough(),j$=te({type:Ie("string"),title:Y(L()),description:Y(L()),minLength:Y(St()),maxLength:Y(St()),format:Y(Wr(["email","uri","date","date-time"]))}).passthrough(),D$=te({type:Wr(["number","integer"]),title:Y(L()),description:Y(L()),minimum:Y(St()),maximum:Y(St())}).passthrough(),L$=te({type:Ie("string"),title:Y(L()),description:Y(L()),enum:ue(L()),enumNames:Y(ue(L()))}).passthrough(),z$=Vt([M$,j$,D$,L$]),Dh=Xt.extend({method:Ie("elicitation/create"),params:yr.extend({message:L(),requestedSchema:te({type:Ie("object"),properties:ja(L(),z$),required:Y(ue(L()))}).passthrough()})}),su=_r.extend({action:Wr(["accept","decline","cancel"]),content:Y(ja(L(),Ma()))}),U$=te({type:Ie("ref/resource"),uri:L()}).passthrough(),q$=te({type:Ie("ref/prompt"),name:L()}).passthrough(),ou=Xt.extend({method:Ie("completion/complete"),params:yr.extend({ref:Vt([q$,U$]),argument:te({name:L(),value:L()}).passthrough(),context:Y(te({arguments:Y(ja(L(),L()))}))})}),Lh=_r.extend({completion:te({values:ue(L()).max(100),total:Y(St().int()),hasMore:Y(yt())}).passthrough()}),F$=te({uri:L().startsWith("file://"),name:Y(L()),_meta:Y(te({}).passthrough())}).passthrough(),zh=Xt.extend({method:Ie("roots/list")}),iu=_r.extend({roots:ue(F$)}),Uh=Qr.extend({method:Ie("notifications/roots/list_changed")});Vt([Bc,vh,ou,mi,Yc,Qc,pi,Kc,Wc,kh,Ih,nu,ru]),Vt([Vc,Jc,Hc,Uh]),Vt([Tn,au,su,iu]),Vt([Bc,jh,Dh,zh]),Vt([Vc,Jc,Mh,xh,Ph,Ah,Oh]),Vt([Tn,gh,Lh,Rh,Th,Eh,Sh,$h,fi,Nh]);class st extends Error{constructor(e,r,a){super(`MCP error ${e}: ${r}`),this.code=e,this.data=a,this.name="McpError"}}const Z$=6e4;class qh{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Vc,r=>{const a=this._requestHandlerAbortControllers.get(r.params.requestId);a==null||a.abort(r.params.reason)}),this.setNotificationHandler(Jc,r=>{this._onprogress(r)}),this.setRequestHandler(Bc,r=>({}))}_setupTimeout(e,r,a,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:a,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new st(rt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,a,n;this._transport=e;const s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s==null||s(),this._onclose()};const o=(a=this.transport)===null||a===void 0?void 0:a.onerror;this._transport.onerror=l=>{o==null||o(l),this._onerror(l)};const i=(n=this._transport)===null||n===void 0?void 0:n.onmessage;this._transport.onmessage=(l,c)=>{i==null||i(l,c),Zc(l)||y$(l)?this._onresponse(l):dh(l)?this._onrequest(l,c):g$(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);const a=new st(rt.ConnectionClosed,"Connection closed");for(const n of r.values())n(a)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const a=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){var a,n;const s=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler,o=this._transport;if(s===void 0){o==null||o.send({jsonrpc:"2.0",id:e.id,error:{code:rt.MethodNotFound,message:"Method not found"}}).catch(c=>this._onerror(new Error(`Failed to send an error response: ${c}`)));return}const i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);const l={signal:i.signal,sessionId:o==null?void 0:o.sessionId,_meta:(n=e.params)===null||n===void 0?void 0:n._meta,sendNotification:c=>this.notification(c,{relatedRequestId:e.id}),sendRequest:(c,u,f)=>this.request(c,u,{...f,relatedRequestId:e.id}),authInfo:r==null?void 0:r.authInfo,requestId:e.id,requestInfo:r==null?void 0:r.requestInfo};Promise.resolve().then(()=>s(e,l)).then(c=>{if(!i.signal.aborted)return o==null?void 0:o.send({result:c,jsonrpc:"2.0",id:e.id})},c=>{var u;if(!i.signal.aborted)return o==null?void 0:o.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(c.code)?c.code:rt.InternalError,message:(u=c.message)!==null&&u!==void 0?u:"Internal error"}})}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...a}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){o(l);return}s(a)}_onresponse(e){const r=Number(e.id),a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Zc(e))a(e);else{const n=new st(e.error.code,e.error.message,e.error.data);a(n)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,a){const{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}=a??{};return new Promise((i,l)=>{var c,u,f,g,d,h;if(!this._transport){l(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(u=a==null?void 0:a.signal)===null||u===void 0||u.throwIfAborted();const v=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:v};a!=null&&a.onprogress&&(this._progressHandlers.set(v,a.onprogress),m.params={...e.params,_meta:{...((f=e.params)===null||f===void 0?void 0:f._meta)||{},progressToken:v}});const p=b=>{var S;this._responseHandlers.delete(v),this._progressHandlers.delete(v),this._cleanupTimeout(v),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(b)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(I=>this._onerror(new Error(`Failed to send cancellation: ${I}`))),l(b)};this._responseHandlers.set(v,b=>{var S;if(!(!((S=a==null?void 0:a.signal)===null||S===void 0)&&S.aborted)){if(b instanceof Error)return l(b);try{const I=r.parse(b.result);i(I)}catch(I){l(I)}}}),(g=a==null?void 0:a.signal)===null||g===void 0||g.addEventListener("abort",()=>{var b;p((b=a==null?void 0:a.signal)===null||b===void 0?void 0:b.reason)});const _=(d=a==null?void 0:a.timeout)!==null&&d!==void 0?d:Z$,w=()=>p(new st(rt.RequestTimeout,"Request timed out",{timeout:_}));this._setupTimeout(v,_,a==null?void 0:a.maxTotalTimeout,w,(h=a==null?void 0:a.resetTimeoutOnProgress)!==null&&h!==void 0?h:!1),this._transport.send(m,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(b=>{this._cleanupTimeout(v),l(b)})})}async notification(e,r){var a,n;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((n=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&n!==void 0?n:[]).includes(e.method)&&!e.params&&!(r!=null&&r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const c={...e,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(c,r).catch(u=>this._onerror(u))});return}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,r)}setRequestHandler(e,r){const a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(n,s)=>Promise.resolve(r(e.parse(n),s)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(r(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function Fh(t,e){return Object.entries(e).reduce((r,[a,n])=>(n&&typeof n=="object"?r[a]=r[a]?{...r[a],...n}:n:r[a]=n,r),{...t})}var lu={exports:{}};/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */(function(t,e){(function(r,a){a(e)})(os,function(r){function a(){for(var T=arguments.length,$=Array(T),C=0;C<T;C++)$[C]=arguments[C];if($.length>1){$[0]=$[0].slice(0,-1);for(var q=$.length-1,F=1;F<q;++F)$[F]=$[F].slice(1,-1);return $[q]=$[q].slice(1),$.join("")}else return $[0]}function n(T){return"(?:"+T+")"}function s(T){return T===void 0?"undefined":T===null?"null":Object.prototype.toString.call(T).split(" ").pop().split("]").shift().toLowerCase()}function o(T){return T.toUpperCase()}function i(T){return T!=null?T instanceof Array?T:typeof T.length!="number"||T.split||T.setInterval||T.call?[T]:Array.prototype.slice.call(T):[]}function l(T,$){var C=T;if($)for(var q in $)C[q]=$[q];return C}function c(T){var $="[A-Za-z]",C="[0-9]",q=a(C,"[A-Fa-f]"),F=n(n("%[EFef]"+q+"%"+q+q+"%"+q+q)+"|"+n("%[89A-Fa-f]"+q+"%"+q+q)+"|"+n("%"+q+q)),ye="[\\:\\/\\?\\#\\[\\]\\@]",_e="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Fe=a(ye,_e),it=T?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",bt=T?"[\\uE000-\\uF8FF]":"[]",Ue=a($,C,"[\\-\\.\\_\\~]",it);n($+a($,C,"[\\+\\-\\.]")+"*"),n(n(F+"|"+a(Ue,_e,"[\\:]"))+"*");var nt=n(n("25[0-5]")+"|"+n("2[0-4]"+C)+"|"+n("1"+C+C)+"|"+n("0?[1-9]"+C)+"|0?0?"+C),Et=n(nt+"\\."+nt+"\\."+nt+"\\."+nt),xe=n(q+"{1,4}"),dt=n(n(xe+"\\:"+xe)+"|"+Et),xt=n(n(xe+"\\:")+"{6}"+dt),pt=n("\\:\\:"+n(xe+"\\:")+"{5}"+dt),Fn=n(n(xe)+"?\\:\\:"+n(xe+"\\:")+"{4}"+dt),ln=n(n(n(xe+"\\:")+"{0,1}"+xe)+"?\\:\\:"+n(xe+"\\:")+"{3}"+dt),cn=n(n(n(xe+"\\:")+"{0,2}"+xe)+"?\\:\\:"+n(xe+"\\:")+"{2}"+dt),ss=n(n(n(xe+"\\:")+"{0,3}"+xe)+"?\\:\\:"+xe+"\\:"+dt),va=n(n(n(xe+"\\:")+"{0,4}"+xe)+"?\\:\\:"+dt),Pr=n(n(n(xe+"\\:")+"{0,5}"+xe)+"?\\:\\:"+xe),un=n(n(n(xe+"\\:")+"{0,6}"+xe)+"?\\:\\:"),ga=n([xt,pt,Fn,ln,cn,ss,va,Pr,un].join("|")),En=n(n(Ue+"|"+F)+"+");n("[vV]"+q+"+\\."+a(Ue,_e,"[\\:]")+"+"),n(n(F+"|"+a(Ue,_e))+"*");var Co=n(F+"|"+a(Ue,_e,"[\\:\\@]"));return n(n(F+"|"+a(Ue,_e,"[\\@]"))+"+"),n(n(Co+"|"+a("[\\/\\?]",bt))+"*"),{NOT_SCHEME:new RegExp(a("[^]",$,C,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(a("[^\\%\\:]",Ue,_e),"g"),NOT_HOST:new RegExp(a("[^\\%\\[\\]\\:]",Ue,_e),"g"),NOT_PATH:new RegExp(a("[^\\%\\/\\:\\@]",Ue,_e),"g"),NOT_PATH_NOSCHEME:new RegExp(a("[^\\%\\/\\@]",Ue,_e),"g"),NOT_QUERY:new RegExp(a("[^\\%]",Ue,_e,"[\\:\\@\\/\\?]",bt),"g"),NOT_FRAGMENT:new RegExp(a("[^\\%]",Ue,_e,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(a("[^]",Ue,_e),"g"),UNRESERVED:new RegExp(Ue,"g"),OTHER_CHARS:new RegExp(a("[^\\%]",Ue,Fe),"g"),PCT_ENCODED:new RegExp(F,"g"),IPV4ADDRESS:new RegExp("^("+Et+")$"),IPV6ADDRESS:new RegExp("^\\[?("+ga+")"+n(n("\\%25|\\%(?!"+q+"{2})")+"("+En+")")+"?\\]?$")}}var u=c(!1),f=c(!0),g=function(){function T($,C){var q=[],F=!0,ye=!1,_e=void 0;try{for(var Fe=$[Symbol.iterator](),it;!(F=(it=Fe.next()).done)&&(q.push(it.value),!(C&&q.length===C));F=!0);}catch(bt){ye=!0,_e=bt}finally{try{!F&&Fe.return&&Fe.return()}finally{if(ye)throw _e}}return q}return function($,C){if(Array.isArray($))return $;if(Symbol.iterator in Object($))return T($,C);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),d=function(T){if(Array.isArray(T)){for(var $=0,C=Array(T.length);$<T.length;$++)C[$]=T[$];return C}else return Array.from(T)},h=2147483647,v=36,m=1,p=26,_=38,w=700,b=72,S=128,I="-",k=/^xn--/,A=/[^\0-\x7E]/,O=/[\x2E\u3002\uFF0E\uFF61]/g,H={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},J=v-m,K=Math.floor,z=String.fromCharCode;function U(T){throw new RangeError(H[T])}function G(T,$){for(var C=[],q=T.length;q--;)C[q]=$(T[q]);return C}function se(T,$){var C=T.split("@"),q="";C.length>1&&(q=C[0]+"@",T=C[1]),T=T.replace(O,".");var F=T.split("."),ye=G(F,$).join(".");return q+ye}function ne(T){for(var $=[],C=0,q=T.length;C<q;){var F=T.charCodeAt(C++);if(F>=55296&&F<=56319&&C<q){var ye=T.charCodeAt(C++);(ye&64512)==56320?$.push(((F&1023)<<10)+(ye&1023)+65536):($.push(F),C--)}else $.push(F)}return $}var ce=function($){return String.fromCodePoint.apply(String,d($))},pe=function($){return $-48<10?$-22:$-65<26?$-65:$-97<26?$-97:v},M=function($,C){return $+22+75*($<26)-((C!=0)<<5)},R=function($,C,q){var F=0;for($=q?K($/w):$>>1,$+=K($/C);$>J*p>>1;F+=v)$=K($/J);return K(F+(J+1)*$/($+_))},D=function($){var C=[],q=$.length,F=0,ye=S,_e=b,Fe=$.lastIndexOf(I);Fe<0&&(Fe=0);for(var it=0;it<Fe;++it)$.charCodeAt(it)>=128&&U("not-basic"),C.push($.charCodeAt(it));for(var bt=Fe>0?Fe+1:0;bt<q;){for(var Ue=F,nt=1,Et=v;;Et+=v){bt>=q&&U("invalid-input");var xe=pe($.charCodeAt(bt++));(xe>=v||xe>K((h-F)/nt))&&U("overflow"),F+=xe*nt;var dt=Et<=_e?m:Et>=_e+p?p:Et-_e;if(xe<dt)break;var xt=v-dt;nt>K(h/xt)&&U("overflow"),nt*=xt}var pt=C.length+1;_e=R(F-Ue,pt,Ue==0),K(F/pt)>h-ye&&U("overflow"),ye+=K(F/pt),F%=pt,C.splice(F++,0,ye)}return String.fromCodePoint.apply(String,C)},N=function($){var C=[];$=ne($);var q=$.length,F=S,ye=0,_e=b,Fe=!0,it=!1,bt=void 0;try{for(var Ue=$[Symbol.iterator](),nt;!(Fe=(nt=Ue.next()).done);Fe=!0){var Et=nt.value;Et<128&&C.push(z(Et))}}catch(Ro){it=!0,bt=Ro}finally{try{!Fe&&Ue.return&&Ue.return()}finally{if(it)throw bt}}var xe=C.length,dt=xe;for(xe&&C.push(I);dt<q;){var xt=h,pt=!0,Fn=!1,ln=void 0;try{for(var cn=$[Symbol.iterator](),ss;!(pt=(ss=cn.next()).done);pt=!0){var va=ss.value;va>=F&&va<xt&&(xt=va)}}catch(Ro){Fn=!0,ln=Ro}finally{try{!pt&&cn.return&&cn.return()}finally{if(Fn)throw ln}}var Pr=dt+1;xt-F>K((h-ye)/Pr)&&U("overflow"),ye+=(xt-F)*Pr,F=xt;var un=!0,ga=!1,En=void 0;try{for(var Co=$[Symbol.iterator](),tw;!(un=(tw=Co.next()).done);un=!0){var rw=tw.value;if(rw<F&&++ye>h&&U("overflow"),rw==F){for(var Cl=ye,Rl=v;;Rl+=v){var Ol=Rl<=_e?m:Rl>=_e+p?p:Rl-_e;if(Cl<Ol)break;var nw=Cl-Ol,aw=v-Ol;C.push(z(M(Ol+nw%aw,0))),Cl=K(nw/aw)}C.push(z(M(Cl,0))),_e=R(ye,Pr,dt==xe),ye=0,++dt}}}catch(Ro){ga=!0,En=Ro}finally{try{!un&&Co.return&&Co.return()}finally{if(ga)throw En}}++ye,++F}return C.join("")},y=function($){return se($,function(C){return k.test(C)?D(C.slice(4).toLowerCase()):C})},P=function($){return se($,function(C){return A.test(C)?"xn--"+N(C):C})},j={version:"2.1.0",ucs2:{decode:ne,encode:ce},decode:D,encode:N,toASCII:P,toUnicode:y},Q={};function ee(T){var $=T.charCodeAt(0),C=void 0;return $<16?C="%0"+$.toString(16).toUpperCase():$<128?C="%"+$.toString(16).toUpperCase():$<2048?C="%"+($>>6|192).toString(16).toUpperCase()+"%"+($&63|128).toString(16).toUpperCase():C="%"+($>>12|224).toString(16).toUpperCase()+"%"+($>>6&63|128).toString(16).toUpperCase()+"%"+($&63|128).toString(16).toUpperCase(),C}function Se(T){for(var $="",C=0,q=T.length;C<q;){var F=parseInt(T.substr(C+1,2),16);if(F<128)$+=String.fromCharCode(F),C+=3;else if(F>=194&&F<224){if(q-C>=6){var ye=parseInt(T.substr(C+4,2),16);$+=String.fromCharCode((F&31)<<6|ye&63)}else $+=T.substr(C,6);C+=6}else if(F>=224){if(q-C>=9){var _e=parseInt(T.substr(C+4,2),16),Fe=parseInt(T.substr(C+7,2),16);$+=String.fromCharCode((F&15)<<12|(_e&63)<<6|Fe&63)}else $+=T.substr(C,9);C+=9}else $+=T.substr(C,3),C+=3}return $}function de(T,$){function C(q){var F=Se(q);return F.match($.UNRESERVED)?F:q}return T.scheme&&(T.scheme=String(T.scheme).replace($.PCT_ENCODED,C).toLowerCase().replace($.NOT_SCHEME,"")),T.userinfo!==void 0&&(T.userinfo=String(T.userinfo).replace($.PCT_ENCODED,C).replace($.NOT_USERINFO,ee).replace($.PCT_ENCODED,o)),T.host!==void 0&&(T.host=String(T.host).replace($.PCT_ENCODED,C).toLowerCase().replace($.NOT_HOST,ee).replace($.PCT_ENCODED,o)),T.path!==void 0&&(T.path=String(T.path).replace($.PCT_ENCODED,C).replace(T.scheme?$.NOT_PATH:$.NOT_PATH_NOSCHEME,ee).replace($.PCT_ENCODED,o)),T.query!==void 0&&(T.query=String(T.query).replace($.PCT_ENCODED,C).replace($.NOT_QUERY,ee).replace($.PCT_ENCODED,o)),T.fragment!==void 0&&(T.fragment=String(T.fragment).replace($.PCT_ENCODED,C).replace($.NOT_FRAGMENT,ee).replace($.PCT_ENCODED,o)),T}function ge(T){return T.replace(/^0*(.*)/,"$1")||"0"}function vt(T,$){var C=T.match($.IPV4ADDRESS)||[],q=g(C,2),F=q[1];return F?F.split(".").map(ge).join("."):T}function Te(T,$){var C=T.match($.IPV6ADDRESS)||[],q=g(C,3),F=q[1],ye=q[2];if(F){for(var _e=F.toLowerCase().split("::").reverse(),Fe=g(_e,2),it=Fe[0],bt=Fe[1],Ue=bt?bt.split(":").map(ge):[],nt=it.split(":").map(ge),Et=$.IPV4ADDRESS.test(nt[nt.length-1]),xe=Et?7:8,dt=nt.length-xe,xt=Array(xe),pt=0;pt<xe;++pt)xt[pt]=Ue[pt]||nt[dt+pt]||"";Et&&(xt[xe-1]=vt(xt[xe-1],$));var Fn=xt.reduce(function(Pr,un,ga){if(!un||un==="0"){var En=Pr[Pr.length-1];En&&En.index+En.length===ga?En.length++:Pr.push({index:ga,length:1})}return Pr},[]),ln=Fn.sort(function(Pr,un){return un.length-Pr.length})[0],cn=void 0;if(ln&&ln.length>1){var ss=xt.slice(0,ln.index),va=xt.slice(ln.index+ln.length);cn=ss.join(":")+"::"+va.join(":")}else cn=xt.join(":");return ye&&(cn+="%"+ye),cn}else return T}var me=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Ne="".match(/(){0}/)[1]===void 0;function Ae(T){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},C={},q=$.iri!==!1?f:u;$.reference==="suffix"&&(T=($.scheme?$.scheme+":":"")+"//"+T);var F=T.match(me);if(F){Ne?(C.scheme=F[1],C.userinfo=F[3],C.host=F[4],C.port=parseInt(F[5],10),C.path=F[6]||"",C.query=F[7],C.fragment=F[8],isNaN(C.port)&&(C.port=F[5])):(C.scheme=F[1]||void 0,C.userinfo=T.indexOf("@")!==-1?F[3]:void 0,C.host=T.indexOf("//")!==-1?F[4]:void 0,C.port=parseInt(F[5],10),C.path=F[6]||"",C.query=T.indexOf("?")!==-1?F[7]:void 0,C.fragment=T.indexOf("#")!==-1?F[8]:void 0,isNaN(C.port)&&(C.port=T.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?F[4]:void 0)),C.host&&(C.host=Te(vt(C.host,q),q)),C.scheme===void 0&&C.userinfo===void 0&&C.host===void 0&&C.port===void 0&&!C.path&&C.query===void 0?C.reference="same-document":C.scheme===void 0?C.reference="relative":C.fragment===void 0?C.reference="absolute":C.reference="uri",$.reference&&$.reference!=="suffix"&&$.reference!==C.reference&&(C.error=C.error||"URI is not a "+$.reference+" reference.");var ye=Q[($.scheme||C.scheme||"").toLowerCase()];if(!$.unicodeSupport&&(!ye||!ye.unicodeSupport)){if(C.host&&($.domainHost||ye&&ye.domainHost))try{C.host=j.toASCII(C.host.replace(q.PCT_ENCODED,Se).toLowerCase())}catch(_e){C.error=C.error||"Host's domain name can not be converted to ASCII via punycode: "+_e}de(C,u)}else de(C,q);ye&&ye.parse&&ye.parse(C,$)}else C.error=C.error||"URI can not be parsed.";return C}function ke(T,$){var C=$.iri!==!1?f:u,q=[];return T.userinfo!==void 0&&(q.push(T.userinfo),q.push("@")),T.host!==void 0&&q.push(Te(vt(String(T.host),C),C).replace(C.IPV6ADDRESS,function(F,ye,_e){return"["+ye+(_e?"%25"+_e:"")+"]"})),(typeof T.port=="number"||typeof T.port=="string")&&(q.push(":"),q.push(String(T.port))),q.length?q.join(""):void 0}var tt=/^\.\.?\//,Ze=/^\/\.(\/|$)/,re=/^\/\.\.(\/|$)/,ze=/^\/?(?:.|\n)*?(?=\/|$)/;function Be(T){for(var $=[];T.length;)if(T.match(tt))T=T.replace(tt,"");else if(T.match(Ze))T=T.replace(Ze,"/");else if(T.match(re))T=T.replace(re,"/"),$.pop();else if(T==="."||T==="..")T="";else{var C=T.match(ze);if(C){var q=C[0];T=T.slice(q.length),$.push(q)}else throw new Error("Unexpected dot segment condition")}return $.join("")}function Ee(T){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},C=$.iri?f:u,q=[],F=Q[($.scheme||T.scheme||"").toLowerCase()];if(F&&F.serialize&&F.serialize(T,$),T.host&&!C.IPV6ADDRESS.test(T.host)){if($.domainHost||F&&F.domainHost)try{T.host=$.iri?j.toUnicode(T.host):j.toASCII(T.host.replace(C.PCT_ENCODED,Se).toLowerCase())}catch(Fe){T.error=T.error||"Host's domain name can not be converted to "+($.iri?"Unicode":"ASCII")+" via punycode: "+Fe}}de(T,C),$.reference!=="suffix"&&T.scheme&&(q.push(T.scheme),q.push(":"));var ye=ke(T,$);if(ye!==void 0&&($.reference!=="suffix"&&q.push("//"),q.push(ye),T.path&&T.path.charAt(0)!=="/"&&q.push("/")),T.path!==void 0){var _e=T.path;!$.absolutePath&&(!F||!F.absolutePath)&&(_e=Be(_e)),ye===void 0&&(_e=_e.replace(/^\/\//,"/%2F")),q.push(_e)}return T.query!==void 0&&(q.push("?"),q.push(T.query)),T.fragment!==void 0&&(q.push("#"),q.push(T.fragment)),q.join("")}function Qe(T,$){var C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},q=arguments[3],F={};return q||(T=Ae(Ee(T,C),C),$=Ae(Ee($,C),C)),C=C||{},!C.tolerant&&$.scheme?(F.scheme=$.scheme,F.userinfo=$.userinfo,F.host=$.host,F.port=$.port,F.path=Be($.path||""),F.query=$.query):($.userinfo!==void 0||$.host!==void 0||$.port!==void 0?(F.userinfo=$.userinfo,F.host=$.host,F.port=$.port,F.path=Be($.path||""),F.query=$.query):($.path?($.path.charAt(0)==="/"?F.path=Be($.path):((T.userinfo!==void 0||T.host!==void 0||T.port!==void 0)&&!T.path?F.path="/"+$.path:T.path?F.path=T.path.slice(0,T.path.lastIndexOf("/")+1)+$.path:F.path=$.path,F.path=Be(F.path)),F.query=$.query):(F.path=T.path,$.query!==void 0?F.query=$.query:F.query=T.query),F.userinfo=T.userinfo,F.host=T.host,F.port=T.port),F.scheme=T.scheme),F.fragment=$.fragment,F}function ir(T,$,C){var q=l({scheme:"null"},C);return Ee(Qe(Ae(T,q),Ae($,q),q,!0),q)}function Mt(T,$){return typeof T=="string"?T=Ee(Ae(T,$),$):s(T)==="object"&&(T=Ae(Ee(T,$),$)),T}function wt(T,$,C){return typeof T=="string"?T=Ee(Ae(T,C),C):s(T)==="object"&&(T=Ee(T,C)),typeof $=="string"?$=Ee(Ae($,C),C):s($)==="object"&&($=Ee($,C)),T===$}function lr(T,$){return T&&T.toString().replace(!$||!$.iri?u.ESCAPE:f.ESCAPE,ee)}function jt(T,$){return T&&T.toString().replace(!$||!$.iri?u.PCT_ENCODED:f.PCT_ENCODED,Se)}var cr={scheme:"http",domainHost:!0,parse:function($,C){return $.host||($.error=$.error||"HTTP URIs must have a host."),$},serialize:function($,C){var q=String($.scheme).toLowerCase()==="https";return($.port===(q?443:80)||$.port==="")&&($.port=void 0),$.path||($.path="/"),$}},bn={scheme:"https",domainHost:cr.domainHost,parse:cr.parse,serialize:cr.serialize};function fa(T){return typeof T.secure=="boolean"?T.secure:String(T.scheme).toLowerCase()==="wss"}var ut={scheme:"ws",domainHost:!0,parse:function($,C){var q=$;return q.secure=fa(q),q.resourceName=(q.path||"/")+(q.query?"?"+q.query:""),q.path=void 0,q.query=void 0,q},serialize:function($,C){if(($.port===(fa($)?443:80)||$.port==="")&&($.port=void 0),typeof $.secure=="boolean"&&($.scheme=$.secure?"wss":"ws",$.secure=void 0),$.resourceName){var q=$.resourceName.split("?"),F=g(q,2),ye=F[0],_e=F[1];$.path=ye&&ye!=="/"?ye:void 0,$.query=_e,$.resourceName=void 0}return $.fragment=void 0,$}},Er={scheme:"wss",domainHost:ut.domainHost,parse:ut.parse,serialize:ut.serialize},qr={},$o="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",Sr="[0-9A-Fa-f]",wp=n(n("%[EFef]"+Sr+"%"+Sr+Sr+"%"+Sr+Sr)+"|"+n("%[89A-Fa-f]"+Sr+"%"+Sr+Sr)+"|"+n("%"+Sr+Sr)),ns="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",Po="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",ko=a(Po,'[\\"\\\\]'),Io="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",Un=new RegExp($o,"g"),Dt=new RegExp(wp,"g"),xo=new RegExp(a("[^]",ns,"[\\.]",'[\\"]',ko),"g"),To=new RegExp(a("[^]",$o,Io),"g"),$r=To;function as(T){var $=Se(T);return $.match(Un)?$:T}var we={scheme:"mailto",parse:function($,C){var q=$,F=q.to=q.path?q.path.split(","):[];if(q.path=void 0,q.query){for(var ye=!1,_e={},Fe=q.query.split("&"),it=0,bt=Fe.length;it<bt;++it){var Ue=Fe[it].split("=");switch(Ue[0]){case"to":for(var nt=Ue[1].split(","),Et=0,xe=nt.length;Et<xe;++Et)F.push(nt[Et]);break;case"subject":q.subject=jt(Ue[1],C);break;case"body":q.body=jt(Ue[1],C);break;default:ye=!0,_e[jt(Ue[0],C)]=jt(Ue[1],C);break}}ye&&(q.headers=_e)}q.query=void 0;for(var dt=0,xt=F.length;dt<xt;++dt){var pt=F[dt].split("@");if(pt[0]=jt(pt[0]),C.unicodeSupport)pt[1]=jt(pt[1],C).toLowerCase();else try{pt[1]=j.toASCII(jt(pt[1],C).toLowerCase())}catch(Fn){q.error=q.error||"Email address's domain name can not be converted to ASCII via punycode: "+Fn}F[dt]=pt.join("@")}return q},serialize:function($,C){var q=$,F=i($.to);if(F){for(var ye=0,_e=F.length;ye<_e;++ye){var Fe=String(F[ye]),it=Fe.lastIndexOf("@"),bt=Fe.slice(0,it).replace(Dt,as).replace(Dt,o).replace(xo,ee),Ue=Fe.slice(it+1);try{Ue=C.iri?j.toUnicode(Ue):j.toASCII(jt(Ue,C).toLowerCase())}catch(dt){q.error=q.error||"Email address's domain name can not be converted to "+(C.iri?"Unicode":"ASCII")+" via punycode: "+dt}F[ye]=bt+"@"+Ue}q.path=F.join(",")}var nt=$.headers=$.headers||{};$.subject&&(nt.subject=$.subject),$.body&&(nt.body=$.body);var Et=[];for(var xe in nt)nt[xe]!==qr[xe]&&Et.push(xe.replace(Dt,as).replace(Dt,o).replace(To,ee)+"="+nt[xe].replace(Dt,as).replace(Dt,o).replace($r,ee));return Et.length&&(q.query=Et.join("&")),q}},Ot=/^([^\:]+)\:(.*)/,qn={scheme:"urn",parse:function($,C){var q=$.path&&$.path.match(Ot),F=$;if(q){var ye=C.scheme||F.scheme||"urn",_e=q[1].toLowerCase(),Fe=q[2],it=ye+":"+(C.nid||_e),bt=Q[it];F.nid=_e,F.nss=Fe,F.path=void 0,bt&&(F=bt.parse(F,C))}else F.error=F.error||"URN can not be parsed.";return F},serialize:function($,C){var q=C.scheme||$.scheme||"urn",F=$.nid,ye=q+":"+(C.nid||F),_e=Q[ye];_e&&($=_e.serialize($,C));var Fe=$,it=$.nss;return Fe.path=(F||C.nid)+":"+it,Fe}},ha=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ma={scheme:"urn:uuid",parse:function($,C){var q=$;return q.uuid=q.nss,q.nss=void 0,!C.tolerant&&(!q.uuid||!q.uuid.match(ha))&&(q.error=q.error||"UUID is not valid."),q},serialize:function($,C){var q=$;return q.nss=($.uuid||"").toLowerCase(),q}};Q[cr.scheme]=cr,Q[bn.scheme]=bn,Q[ut.scheme]=ut,Q[Er.scheme]=Er,Q[we.scheme]=we,Q[qn.scheme]=qn,Q[ma.scheme]=ma,r.SCHEMES=Q,r.pctEncChar=ee,r.pctDecChars=Se,r.parse=Ae,r.removeDotSegments=Be,r.serialize=Ee,r.resolveComponents=Qe,r.resolve=ir,r.normalize=Mt,r.equal=wt,r.escapeComponent=lr,r.unescapeComponent=jt,Object.defineProperty(r,"__esModule",{value:!0})})})(lu,lu.exports);var V$=lu.exports,H$=function(e){for(var r=0,a=e.length,n=0,s;n<a;)r++,s=e.charCodeAt(n++),s>=55296&&s<=56319&&n<a&&(s=e.charCodeAt(n),(s&64512)==56320&&n++);return r},Da={copy:B$,checkDataType:cu,checkDataTypes:J$,coerceToTypes:G$,toHash:uu,getProperty:du,escapeQuotes:pu,equal:cs,ucs2length:H$,varOccurences:Q$,varReplace:Y$,schemaHasRules:X$,schemaHasRulesExcept:eP,schemaUnknownRules:tP,toQuotedString:fu,getPathExpr:rP,getPath:nP,getData:oP,unescapeFragment:iP,unescapeJsonPointer:mu,escapeFragment:lP,escapeJsonPointer:hu};function B$(t,e){e=e||{};for(var r in t)e[r]=t[r];return e}function cu(t,e,r,a){var n=a?" !== ":" === ",s=a?" || ":" && ",o=a?"!":"",i=a?"":"!";switch(t){case"null":return e+n+"null";case"array":return o+"Array.isArray("+e+")";case"object":return"("+o+e+s+"typeof "+e+n+'"object"'+s+i+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+n+'"number"'+s+i+"("+e+" % 1)"+s+e+n+e+(r?s+o+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+n+'"'+t+'"'+(r?s+o+"isFinite("+e+")":"")+")";default:return"typeof "+e+n+'"'+t+'"'}}function J$(t,e,r){switch(t.length){case 1:return cu(t[0],e,r,!0);default:var a="",n=uu(t);n.array&&n.object&&(a=n.null?"(":"(!"+e+" || ",a+="typeof "+e+' !== "object")',delete n.null,delete n.array,delete n.object),n.number&&delete n.integer;for(var s in n)a+=(a?" && ":"")+cu(s,e,r,!0);return a}}var Zh=uu(["string","number","integer","boolean","null"]);function G$(t,e){if(Array.isArray(e)){for(var r=[],a=0;a<e.length;a++){var n=e[a];(Zh[n]||t==="array"&&n==="array")&&(r[r.length]=n)}if(r.length)return r}else{if(Zh[e])return[e];if(t==="array"&&e==="array")return["array"]}}function uu(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!0;return e}var K$=/^[a-z$_][a-z$_0-9]*$/i,W$=/'|\\/g;function du(t){return typeof t=="number"?"["+t+"]":K$.test(t)?"."+t:"['"+pu(t)+"']"}function pu(t){return t.replace(W$,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function Q$(t,e){e+="[^0-9]";var r=t.match(new RegExp(e,"g"));return r?r.length:0}function Y$(t,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),t.replace(new RegExp(e,"g"),r+"$1")}function X$(t,e){if(typeof t=="boolean")return!t;for(var r in t)if(e[r])return!0}function eP(t,e,r){if(typeof t=="boolean")return!t&&r!="not";for(var a in t)if(a!=r&&e[a])return!0}function tP(t,e){if(typeof t!="boolean"){for(var r in t)if(!e[r])return r}}function fu(t){return"'"+pu(t)+"'"}function rP(t,e,r,a){var n=r?"'/' + "+e+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return Vh(t,n)}function nP(t,e,r){var a=fu(r?"/"+hu(e):du(e));return Vh(t,a)}var aP=/^\/(?:[^~]|~0|~1)*$/,sP=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function oP(t,e,r){var a,n,s,o;if(t==="")return"rootData";if(t[0]=="/"){if(!aP.test(t))throw new Error("Invalid JSON-pointer: "+t);n=t,s="rootData"}else{if(o=t.match(sP),!o)throw new Error("Invalid JSON-pointer: "+t);if(a=+o[1],n=o[2],n=="#"){if(a>=e)throw new Error("Cannot access property/index "+a+" levels up, current level is "+e);return r[e-a]}if(a>e)throw new Error("Cannot access data "+a+" levels up, current level is "+e);if(s="data"+(e-a||""),!n)return s}for(var i=s,l=n.split("/"),c=0;c<l.length;c++){var u=l[c];u&&(s+=du(mu(u)),i+=" && "+s)}return i}function Vh(t,e){return t=='""'?e:(t+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function iP(t){return mu(decodeURIComponent(t))}function lP(t){return encodeURIComponent(hu(t))}function hu(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function mu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var cP=Da,Hh=uP;function uP(t){cP.copy(t,this)}var Bh={exports:{}},Cn=Bh.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};vi(e,a,n,t,"",t)};Cn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},Cn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},Cn.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},Cn.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 vi(t,e,r,a,n,s,o,i,l,c){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,n,s,o,i,l,c);for(var u in a){var f=a[u];if(Array.isArray(f)){if(u in Cn.arrayKeywords)for(var g=0;g<f.length;g++)vi(t,e,r,f[g],n+"/"+u+"/"+g,s,n,u,a,g)}else if(u in Cn.propsKeywords){if(f&&typeof f=="object")for(var d in f)vi(t,e,r,f[d],n+"/"+u+"/"+dP(d),s,n,u,a,d)}else(u in Cn.keywords||t.allKeys&&!(u in Cn.skipKeywords))&&vi(t,e,r,f,n+"/"+u,s,n,u,a)}r(a,n,s,o,i,l,c)}}function dP(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var pP=Bh.exports,Us=V$,Jh=cs,gi=Da,yi=Hh,fP=pP,vu=Rn;Rn.normalizeId=On,Rn.fullPath=wi,Rn.url=bi,Rn.ids=yP,Rn.inlineRef=gu,Rn.schema=_i;function Rn(t,e,r){var a=this._refs[r];if(typeof a=="string")if(this._refs[a])a=this._refs[a];else return Rn.call(this,t,e,a);if(a=a||this._schemas[r],a instanceof yi)return gu(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var n=_i.call(this,e,r),s,o,i;return n&&(s=n.schema,e=n.root,i=n.baseId),s instanceof yi?o=s.validate||t.call(this,s.schema,e,void 0,i):s!==void 0&&(o=gu(s,this._opts.inlineRefs)?s:t.call(this,s,e,void 0,i)),o}function _i(t,e){var r=Us.parse(e),a=Kh(r),n=wi(this._getId(t.schema));if(Object.keys(t.schema).length===0||a!==n){var s=On(a),o=this._refs[s];if(typeof o=="string")return hP.call(this,t,o,r);if(o instanceof yi)o.validate||this._compile(o),t=o;else if(o=this._schemas[s],o instanceof yi){if(o.validate||this._compile(o),s==On(e))return{schema:o,root:t,baseId:n};t=o}else return;if(!t.schema)return;n=wi(this._getId(t.schema))}return Gh.call(this,r,n,t.schema,t)}function hP(t,e,r){var a=_i.call(this,t,e);if(a){var n=a.schema,s=a.baseId;t=a.root;var o=this._getId(n);return o&&(s=bi(s,o)),Gh.call(this,r,s,n,t)}}var mP=gi.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function Gh(t,e,r,a){if(t.fragment=t.fragment||"",t.fragment.slice(0,1)=="/"){for(var n=t.fragment.split("/"),s=1;s<n.length;s++){var o=n[s];if(o){if(o=gi.unescapeFragment(o),r=r[o],r===void 0)break;var i;if(!mP[o]&&(i=this._getId(r),i&&(e=bi(e,i)),r.$ref)){var l=bi(e,r.$ref),c=_i.call(this,a,l);c&&(r=c.schema,a=c.root,e=c.baseId)}}}if(r!==void 0&&r!==a.schema)return{schema:r,root:a,baseId:e}}}var vP=gi.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function gu(t,e){if(e===!1)return!1;if(e===void 0||e===!0)return yu(t);if(e)return _u(t)<=e}function yu(t){var e;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if(e=t[r],typeof e=="object"&&!yu(e))return!1}else for(var a in t)if(a=="$ref"||(e=t[a],typeof e=="object"&&!yu(e)))return!1;return!0}function _u(t){var e=0,r;if(Array.isArray(t)){for(var a=0;a<t.length;a++)if(r=t[a],typeof r=="object"&&(e+=_u(r)),e==1/0)return 1/0}else for(var n in t){if(n=="$ref")return 1/0;if(vP[n])e++;else if(r=t[n],typeof r=="object"&&(e+=_u(r)+1),e==1/0)return 1/0}return e}function wi(t,e){e!==!1&&(t=On(t));var r=Us.parse(t);return Kh(r)}function Kh(t){return Us.serialize(t).split("#")[0]+"#"}var gP=/#\/?$/;function On(t){return t?t.replace(gP,""):""}function bi(t,e){return e=On(e),Us.resolve(t,e)}function yP(t){var e=On(this._getId(t)),r={"":e},a={"":wi(e,!1)},n={},s=this;return fP(t,{allKeys:!0},function(o,i,l,c,u,f,g){if(i!==""){var d=s._getId(o),h=r[c],v=a[c]+"/"+u;if(g!==void 0&&(v+="/"+(typeof g=="number"?g:gi.escapeFragment(g))),typeof d=="string"){d=h=On(h?Us.resolve(h,d):d);var m=s._refs[d];if(typeof m=="string"&&(m=s._refs[m]),m&&m.schema){if(!Jh(o,m.schema))throw new Error('id "'+d+'" resolves to more than one schema')}else if(d!=On(v))if(d[0]=="#"){if(n[d]&&!Jh(o,n[d]))throw new Error('id "'+d+'" resolves to more than one schema');n[d]=o}else s._refs[d]=v}r[i]=h,a[i]=v}}),n}var wu=vu,bu={Validation:Wh(_P),MissingRef:Wh(Eu)};function _P(t){this.message="validation failed",this.errors=t,this.ajv=this.validation=!0}Eu.message=function(t,e){return"can't resolve reference "+e+" from id "+t};function Eu(t,e,r){this.message=r||Eu.message(t,e),this.missingRef=wu.url(t,e),this.missingSchema=wu.normalizeId(wu.fullPath(this.missingRef))}function Wh(t){return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Qh=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,a=e.cmp&&function(s){return function(o){return function(i,l){var c={key:i,value:o[i]},u={key:l,value:o[l]};return s(c,u)}}}(e.cmp),n=[];return function s(o){if(o&&o.toJSON&&typeof o.toJSON=="function"&&(o=o.toJSON()),o!==void 0){if(typeof o=="number")return isFinite(o)?""+o:"null";if(typeof o!="object")return JSON.stringify(o);var i,l;if(Array.isArray(o)){for(l="[",i=0;i<o.length;i++)i&&(l+=","),l+=s(o[i])||"null";return l+"]"}if(o===null)return"null";if(n.indexOf(o)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var c=n.push(o)-1,u=Object.keys(o).sort(a&&a(o));for(l="",i=0;i<u.length;i++){var f=u[i],g=s(o[f]);g&&(l&&(l+=","),l+=JSON.stringify(f)+":"+g)}return n.splice(c,1),"{"+l+"}"}}(t)},Yh=function(e,r,a){var n="",s=e.schema.$async===!0,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),i=e.self._getId(e.schema);if(e.opts.strictKeywords){var l=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(l){var c="unknown keyword: "+l;if(e.opts.strictKeywords==="log")e.logger.warn(c);else throw new Error(c)}}if(e.isTop&&(n+=" var validate = ",s&&(e.async=!0,n+="async "),n+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",i&&(e.opts.sourceCode||e.opts.processCode)&&(n+=" "+("/*# sourceURL="+i+" */")+" ")),typeof e.schema=="boolean"||!(o||e.schema.$ref)){var r="false schema",u=e.level,f=e.dataLevel,g=e.schema[r],d=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,S=!e.opts.allErrors,A,v="data"+(f||""),b="valid"+u;if(e.schema===!1){e.isTop?S=!0:n+=" var "+b+" = false; ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(A||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'boolean schema is false' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?s?n+=" return data; ":n+=" validate.errors = null; return true; ":n+=" var "+b+" = true; ";return e.isTop&&(n+=" }; return validate; "),n}if(e.isTop){var _=e.isTop,u=e.level=0,f=e.dataLevel=0,v="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var w="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(w);else throw new Error(w)}n+=" var vErrors = null; ",n+=" var errors = 0; ",n+=" if (rootData === undefined) rootData = data; "}else{var u=e.level,f=e.dataLevel,v="data"+(f||"");if(i&&(e.baseId=e.resolve.url(e.baseId,i)),s&&!e.async)throw new Error("async schema in sync schema");n+=" var errs_"+u+" = errors;"}var b="valid"+u,S=!e.opts.allErrors,I="",k="",A,O=e.schema.type,H=Array.isArray(O);if(O&&e.opts.nullable&&e.schema.nullable===!0&&(H?O.indexOf("null")==-1&&(O=O.concat("null")):O!="null"&&(O=[O,"null"],H=!0)),H&&O.length==1&&(O=O[0],H=!1),e.schema.$ref&&o){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(n+=" "+e.RULES.all.$comment.code(e,"$comment")),O){if(e.opts.coerceTypes)var J=e.util.coerceToTypes(e.opts.coerceTypes,O);var K=e.RULES.types[O];if(J||H||K===!0||K&&!Ze(K)){var d=e.schemaPath+".type",h=e.errSchemaPath+"/type",d=e.schemaPath+".type",h=e.errSchemaPath+"/type",z=H?"checkDataTypes":"checkDataType";if(n+=" if ("+e.util[z](O,v,e.opts.strictNumbers,!0)+") { ",J){var U="dataType"+u,G="coerced"+u;n+=" var "+U+" = typeof "+v+"; var "+G+" = undefined; ",e.opts.coerceTypes=="array"&&(n+=" if ("+U+" == 'object' && Array.isArray("+v+") && "+v+".length == 1) { "+v+" = "+v+"[0]; "+U+" = typeof "+v+"; if ("+e.util.checkDataType(e.schema.type,v,e.opts.strictNumbers)+") "+G+" = "+v+"; } "),n+=" if ("+G+" !== undefined) ; ";var se=J;if(se)for(var ne,ce=-1,pe=se.length-1;ce<pe;)ne=se[ce+=1],ne=="string"?n+=" else if ("+U+" == 'number' || "+U+" == 'boolean') "+G+" = '' + "+v+"; else if ("+v+" === null) "+G+" = ''; ":ne=="number"||ne=="integer"?(n+=" else if ("+U+" == 'boolean' || "+v+" === null || ("+U+" == 'string' && "+v+" && "+v+" == +"+v+" ",ne=="integer"&&(n+=" && !("+v+" % 1)"),n+=")) "+G+" = +"+v+"; "):ne=="boolean"?n+=" else if ("+v+" === 'false' || "+v+" === 0 || "+v+" === null) "+G+" = false; else if ("+v+" === 'true' || "+v+" === 1) "+G+" = true; ":ne=="null"?n+=" else if ("+v+" === '' || "+v+" === 0 || "+v+" === false) "+G+" = null; ":e.opts.coerceTypes=="array"&&ne=="array"&&(n+=" else if ("+U+" == 'string' || "+U+" == 'number' || "+U+" == 'boolean' || "+v+" == null) "+G+" = ["+v+"]; ");n+=" else { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(A||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",H?n+=""+O.join(","):n+=""+O,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",H?n+=""+O.join(","):n+=""+O,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } if ("+G+" !== undefined) { ";var M=f?"data"+(f-1||""):"parentData",R=f?e.dataPathArr[f]:"parentDataProperty";n+=" "+v+" = "+G+"; ",f||(n+="if ("+M+" !== undefined)"),n+=" "+M+"["+R+"] = "+G+"; } "}else{var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(A||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",H?n+=""+O.join(","):n+=""+O,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",H?n+=""+O.join(","):n+=""+O,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}n+=" } "}}if(e.schema.$ref&&!o)n+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",S&&(n+=" } if (errors === ",_?n+="0":n+="errs_"+u,n+=") { ",k+="}");else{var D=e.RULES;if(D){for(var K,N=-1,y=D.length-1;N<y;)if(K=D[N+=1],Ze(K)){if(K.type&&(n+=" if ("+e.util.checkDataType(K.type,v,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(K.type=="object"&&e.schema.properties){var g=e.schema.properties,P=Object.keys(g),j=P;if(j)for(var Q,ee=-1,Se=j.length-1;ee<Se;){Q=j[ee+=1];var de=g[Q];if(de.default!==void 0){var ge=v+e.util.getProperty(Q);if(e.compositeRule){if(e.opts.strictDefaults){var w="default is ignored for: "+ge;if(e.opts.strictDefaults==="log")e.logger.warn(w);else throw new Error(w)}}else n+=" if ("+ge+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+ge+" === null || "+ge+" === '' "),n+=" ) "+ge+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(de.default)+" ":n+=" "+JSON.stringify(de.default)+" ",n+="; "}}}else if(K.type=="array"&&Array.isArray(e.schema.items)){var vt=e.schema.items;if(vt){for(var de,ce=-1,Te=vt.length-1;ce<Te;)if(de=vt[ce+=1],de.default!==void 0){var ge=v+"["+ce+"]";if(e.compositeRule){if(e.opts.strictDefaults){var w="default is ignored for: "+ge;if(e.opts.strictDefaults==="log")e.logger.warn(w);else throw new Error(w)}}else n+=" if ("+ge+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+ge+" === null || "+ge+" === '' "),n+=" ) "+ge+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(de.default)+" ":n+=" "+JSON.stringify(de.default)+" ",n+="; "}}}}var me=K.rules;if(me){for(var Ne,Ae=-1,ke=me.length-1;Ae<ke;)if(Ne=me[Ae+=1],re(Ne)){var tt=Ne.code(e,Ne.keyword,K.type);tt&&(n+=" "+tt+" ",S&&(I+="}"))}}if(S&&(n+=" "+I+" ",I=""),K.type&&(n+=" } ",O&&O===K.type&&!J)){n+=" else { ";var d=e.schemaPath+".type",h=e.errSchemaPath+"/type",m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(A||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { type: '",H?n+=""+O.join(","):n+=""+O,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",H?n+=""+O.join(","):n+=""+O,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&S?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } "}S&&(n+=" if (errors === ",_?n+="0":n+="errs_"+u,n+=") { ",k+="}")}}}S&&(n+=" "+k+" "),_?(s?(n+=" if (errors === 0) return data; ",n+=" else throw new ValidationError(vErrors); "):(n+=" validate.errors = vErrors; ",n+=" return errors === 0; "),n+=" }; return validate;"):n+=" var "+b+" = errors === errs_"+u+";";function Ze(Be){for(var Ee=Be.rules,Qe=0;Qe<Ee.length;Qe++)if(re(Ee[Qe]))return!0}function re(Be){return e.schema[Be.keyword]!==void 0||Be.implements&&ze(Be)}function ze(Be){for(var Ee=Be.implements,Qe=0;Qe<Ee.length;Qe++)if(e.schema[Ee[Qe]]!==void 0)return!0}return n},Ei=vu,Si=Da,Xh=bu,wP=Qh,em=Yh,bP=Si.ucs2length,EP=cs,SP=Xh.Validation,$P=Su;function Su(t,e,r,a){var n=this,s=this._opts,o=[void 0],i={},l=[],c={},u=[],f={},g=[];e=e||{schema:t,refVal:o,refs:i};var d=PP.call(this,t,e,a),h=this._compilations[d.index];if(d.compiling)return h.callValidate=w;var v=this._formats,m=this.RULES;try{var p=b(t,e,r,a);h.validate=p;var _=h.callValidate;return _&&(_.schema=p.schema,_.errors=null,_.refs=p.refs,_.refVal=p.refVal,_.root=p.root,_.$async=p.$async,s.sourceCode&&(_.source=p.source)),p}finally{kP.call(this,t,e,a)}function w(){var z=h.validate,U=z.apply(this,arguments);return w.errors=z.errors,U}function b(z,U,G,se){var ne=!U||U&&U.schema==z;if(U.schema!=e.schema)return Su.call(n,z,U,G,se);var ce=z.$async===!0,pe=em({isTop:!0,schema:z,isRoot:ne,baseId:se,root:U,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:Xh.MissingRef,RULES:m,validate:em,util:Si,resolve:Ei,resolveRef:S,usePattern:H,useDefault:J,useCustomRule:K,opts:s,formats:v,logger:n.logger,self:n});pe=$i(o,TP)+$i(l,IP)+$i(u,xP)+$i(g,CP)+pe,s.processCode&&(pe=s.processCode(pe,z));var M;try{var R=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",pe);M=R(n,m,v,e,o,u,g,EP,bP,SP),o[0]=M}catch(D){throw n.logger.error("Error compiling schema, function code:",pe),D}return M.schema=z,M.errors=null,M.refs=i,M.refVal=o,M.root=ne?M:U,ce&&(M.$async=!0),s.sourceCode===!0&&(M.source={code:pe,patterns:l,defaults:u}),M}function S(z,U,G){U=Ei.url(z,U);var se=i[U],ne,ce;if(se!==void 0)return ne=o[se],ce="refVal["+se+"]",O(ne,ce);if(!G&&e.refs){var pe=e.refs[U];if(pe!==void 0)return ne=e.refVal[pe],ce=I(U,ne),O(ne,ce)}ce=I(U);var M=Ei.call(n,b,e,U);if(M===void 0){var R=r&&r[U];R&&(M=Ei.inlineRef(R,s.inlineRefs)?R:Su.call(n,R,e,r,z))}if(M===void 0)k(U);else return A(U,M),O(M,ce)}function I(z,U){var G=o.length;return o[G]=U,i[z]=G,"refVal"+G}function k(z){delete i[z]}function A(z,U){var G=i[z];o[G]=U}function O(z,U){return typeof z=="object"||typeof z=="boolean"?{code:U,schema:z,inline:!0}:{code:U,$async:z&&!!z.$async}}function H(z){var U=c[z];return U===void 0&&(U=c[z]=l.length,l[U]=z),"pattern"+U}function J(z){switch(typeof z){case"boolean":case"number":return""+z;case"string":return Si.toQuotedString(z);case"object":if(z===null)return"null";var U=wP(z),G=f[U];return G===void 0&&(G=f[U]=u.length,u[G]=z),"default"+G}}function K(z,U,G,se){if(n._opts.validateSchema!==!1){var ne=z.definition.dependencies;if(ne&&!ne.every(function(j){return Object.prototype.hasOwnProperty.call(G,j)}))throw new Error("parent schema must have all required keywords: "+ne.join(","));var ce=z.definition.validateSchema;if(ce){var pe=ce(U);if(!pe){var M="keyword schema is invalid: "+n.errorsText(ce.errors);if(n._opts.validateSchema=="log")n.logger.error(M);else throw new Error(M)}}}var R=z.definition.compile,D=z.definition.inline,N=z.definition.macro,y;if(R)y=R.call(n,U,G,se);else if(N)y=N.call(n,U,G,se),s.validateSchema!==!1&&n.validateSchema(y,!0);else if(D)y=D.call(n,se,z.keyword,U,G);else if(y=z.definition.validate,!y)return;if(y===void 0)throw new Error('custom keyword "'+z.keyword+'"failed to compile');var P=g.length;return g[P]=y,{code:"customRule"+P,validate:y}}}function PP(t,e,r){var a=tm.call(this,t,e,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:t,root:e,baseId:r},{index:a,compiling:!1})}function kP(t,e,r){var a=tm.call(this,t,e,r);a>=0&&this._compilations.splice(a,1)}function tm(t,e,r){for(var a=0;a<this._compilations.length;a++){var n=this._compilations[a];if(n.schema==t&&n.root==e&&n.baseId==r)return a}return-1}function IP(t,e){return"var pattern"+t+" = new RegExp("+Si.toQuotedString(e[t])+");"}function xP(t){return"var default"+t+" = defaults["+t+"];"}function TP(t,e){return e[t]===void 0?"":"var refVal"+t+" = refVal["+t+"];"}function CP(t){return"var customRule"+t+" = customRules["+t+"];"}function $i(t,e){if(!t.length)return"";for(var r="",a=0;a<t.length;a++)r+=e(a,t);return r}var rm={exports:{}},Pi=rm.exports=function(){this._cache={}};Pi.prototype.put=function(e,r){this._cache[e]=r},Pi.prototype.get=function(e){return this._cache[e]},Pi.prototype.del=function(e){delete this._cache[e]},Pi.prototype.clear=function(){this._cache={}};var RP=rm.exports,OP=Da,NP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,AP=[0,31,28,31,30,31,30,31,31,30,31,30,31],MP=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,nm=/^(?=.{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,jP=/^(?:[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,DP=/^(?:[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,am=/^(?:(?:[^\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,sm=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,om=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,im=/^(?:\/(?:[^~/]|~0|~1)*)*$/,lm=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,cm=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,LP=ki;function ki(t){return t=t=="full"?"full":"fast",OP.copy(ki[t])}ki.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":am,url:sm,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,hostname:nm,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:pm,uuid:om,"json-pointer":im,"json-pointer-uri-fragment":lm,"relative-json-pointer":cm},ki.full={date:um,time:dm,"date-time":qP,uri:ZP,"uri-reference":DP,"uri-template":am,url:sm,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:nm,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:pm,uuid:om,"json-pointer":im,"json-pointer-uri-fragment":lm,"relative-json-pointer":cm};function zP(t){return t%4===0&&(t%100!==0||t%400===0)}function um(t){var e=t.match(NP);if(!e)return!1;var r=+e[1],a=+e[2],n=+e[3];return a>=1&&a<=12&&n>=1&&n<=(a==2&&zP(r)?29:AP[a])}function dm(t,e){var r=t.match(MP);if(!r)return!1;var a=r[1],n=r[2],s=r[3],o=r[5];return(a<=23&&n<=59&&s<=59||a==23&&n==59&&s==60)&&(!e||o)}var UP=/t|\s/i;function qP(t){var e=t.split(UP);return e.length==2&&um(e[0])&&dm(e[1],!0)}var FP=/\/|:/;function ZP(t){return FP.test(t)&&jP.test(t)}var VP=/[^\\]\\Z/;function pm(t){if(VP.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}var HP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,u="data"+(o||""),f="valid"+s,g,d;if(i=="#"||i=="#/")e.isRoot?(g=e.async,d="validate"):(g=e.root.schema.$async===!0,d="root.refVal[0]");else{var h=e.resolveRef(e.baseId,i,e.isRoot);if(h===void 0){var v=e.MissingRefError.message(e.baseId,i);if(e.opts.missingRefs=="fail"){e.logger.error(v);var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(i)+"' } ",e.opts.messages!==!1&&(n+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(i)+"' "),e.opts.verbose&&(n+=" , schema: "+e.util.toQuotedString(i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&c?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c&&(n+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(v),c&&(n+=" if (true) { ");else throw new e.MissingRefError(e.baseId,i,v)}else if(h.inline){var _=e.util.copy(e);_.level++;var w="valid"+_.level;_.schema=h.schema,_.schemaPath="",_.errSchemaPath=i;var b=e.validate(_).replace(/validate\.schema/g,h.code);n+=" "+b+" ",c&&(n+=" if ("+w+") { ")}else g=h.$async===!0||e.async&&h.$async!==!1,d=h.code}if(d){var m=m||[];m.push(n),n="",e.opts.passContext?n+=" "+d+".call(this, ":n+=" "+d+"( ",n+=" "+u+", (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var S=o?"data"+(o-1||""):"parentData",I=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+S+" , "+I+", rootData) ";var k=n;if(n=m.pop(),g){if(!e.async)throw new Error("async schema referenced by sync schema");c&&(n+=" var "+f+"; "),n+=" try { await "+k+"; ",c&&(n+=" "+f+" = true; "),n+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",c&&(n+=" "+f+" = false; "),n+=" } ",c&&(n+=" if ("+f+") { ")}else n+=" if (!"+k+") { if (vErrors === null) vErrors = "+d+".errors; else vErrors = vErrors.concat("+d+".errors); errors = vErrors.length; } ",c&&(n+=" else { ")}return n},BP=function(e,r,a){var n=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c=e.util.copy(e),u="";c.level++;var f="valid"+c.level,g=c.baseId,d=!0,h=s;if(h)for(var v,m=-1,p=h.length-1;m<p;)v=h[m+=1],(e.opts.strictKeywords?typeof v=="object"&&Object.keys(v).length>0||v===!1:e.util.schemaHasRules(v,e.RULES.all))&&(d=!1,c.schema=v,c.schemaPath=o+"["+m+"]",c.errSchemaPath=i+"/"+m,n+=" "+e.validate(c)+" ",c.baseId=g,l&&(n+=" if ("+f+") { ",u+="}"));return l&&(d?n+=" if (true) { ":n+=" "+u.slice(0,-1)+" "),n},JP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,h=e.util.copy(e),v="";h.level++;var m="valid"+h.level,p=i.every(function(A){return e.opts.strictKeywords?typeof A=="object"&&Object.keys(A).length>0||A===!1:e.util.schemaHasRules(A,e.RULES.all)});if(p){var _=h.baseId;n+=" var "+d+" = errors; var "+g+" = false; ";var w=e.compositeRule;e.compositeRule=h.compositeRule=!0;var b=i;if(b)for(var S,I=-1,k=b.length-1;I<k;)S=b[I+=1],h.schema=S,h.schemaPath=l+"["+I+"]",h.errSchemaPath=c+"/"+I,n+=" "+e.validate(h)+" ",h.baseId=_,n+=" "+g+" = "+g+" || "+m+"; if (!"+g+") { ",v+="}";e.compositeRule=h.compositeRule=w,n+=" "+v+" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else u&&(n+=" if (true) { ");return n},GP=function(e,r,a){var n=" ",s=e.schema[r],o=e.errSchemaPath+"/"+r;e.opts.allErrors;var i=e.util.toQuotedString(s);return e.opts.$comment===!0?n+=" console.log("+i+");":typeof e.opts.$comment=="function"&&(n+=" self._opts.$comment("+i+", "+e.util.toQuotedString(o)+", validate.root.schema);"),n},KP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data;d&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; "),d||(n+=" var schema"+s+" = validate.schema"+l+";"),n+="var "+g+" = equal("+f+", schema"+s+"); if (!"+g+") { ";var h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to constant' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;return n=h.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",u&&(n+=" else { "),n},WP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,h=e.util.copy(e),v="";h.level++;var m="valid"+h.level,p="i"+s,_=h.dataLevel=e.dataLevel+1,w="data"+_,b=e.baseId,S=e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all);if(n+="var "+d+" = errors;var "+g+";",S){var I=e.compositeRule;e.compositeRule=h.compositeRule=!0,h.schema=i,h.schemaPath=l,h.errSchemaPath=c,n+=" var "+m+" = false; for (var "+p+" = 0; "+p+" < "+f+".length; "+p+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var k=f+"["+p+"]";h.dataPathArr[_]=p;var A=e.validate(h);h.baseId=b,e.util.varOccurences(A,w)<2?n+=" "+e.util.varReplace(A,w,k)+" ":n+=" var "+w+" = "+k+"; "+A+" ",n+=" if ("+m+") break; } ",e.compositeRule=h.compositeRule=I,n+=" "+v+" if (!"+m+") {"}else n+=" if ("+f+".length == 0) {";var O=O||[];O.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should contain a valid item' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var H=n;return n=O.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+H+"]); ":n+=" validate.errors = ["+H+"]; return false; ":n+=" var err = "+H+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { ",S&&(n+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } "),e.opts.allErrors&&(n+=" } "),n},QP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="errs__"+s,d=e.util.copy(e),h="";d.level++;var v="valid"+d.level,m={},p={},_=e.opts.ownProperties;for(I in i)if(I!="__proto__"){var w=i[I],b=Array.isArray(w)?p:m;b[I]=w}n+="var "+g+" = errors;";var S=e.errorPath;n+="var missing"+s+";";for(var I in p)if(b=p[I],b.length){if(n+=" if ( "+f+e.util.getProperty(I)+" !== undefined ",_&&(n+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(I)+"') "),u){n+=" && ( ";var k=b;if(k)for(var A,O=-1,H=k.length-1;O<H;){A=k[O+=1],O&&(n+=" || ");var J=e.util.getProperty(A),K=f+J;n+=" ( ( "+K+" === undefined ",_&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(A)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?A:J)+") ) "}n+=")) { ";var z="missing"+s,U="' + "+z+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(S,z,!0):S+" + "+z);var G=G||[];G.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(I)+"', missingProperty: '"+U+"', depsCount: "+b.length+", deps: '"+e.util.escapeQuotes(b.length==1?b[0]:b.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",b.length==1?n+="property "+e.util.escapeQuotes(b[0]):n+="properties "+e.util.escapeQuotes(b.join(", ")),n+=" when property "+e.util.escapeQuotes(I)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var se=n;n=G.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+se+"]); ":n+=" validate.errors = ["+se+"]; return false; ":n+=" var err = "+se+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{n+=" ) { ";var ne=b;if(ne)for(var A,ce=-1,pe=ne.length-1;ce<pe;){A=ne[ce+=1];var J=e.util.getProperty(A),U=e.util.escapeQuotes(A),K=f+J;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(S,A,e.opts.jsonPointers)),n+=" if ( "+K+" === undefined ",_&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(A)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(I)+"', missingProperty: '"+U+"', depsCount: "+b.length+", deps: '"+e.util.escapeQuotes(b.length==1?b[0]:b.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",b.length==1?n+="property "+e.util.escapeQuotes(b[0]):n+="properties "+e.util.escapeQuotes(b.join(", ")),n+=" when property "+e.util.escapeQuotes(I)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}n+=" } ",u&&(h+="}",n+=" else { ")}e.errorPath=S;var M=d.baseId;for(var I in m){var w=m[I];(e.opts.strictKeywords?typeof w=="object"&&Object.keys(w).length>0||w===!1:e.util.schemaHasRules(w,e.RULES.all))&&(n+=" "+v+" = true; if ( "+f+e.util.getProperty(I)+" !== undefined ",_&&(n+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(I)+"') "),n+=") { ",d.schema=w,d.schemaPath=l+e.util.getProperty(I),d.errSchemaPath=c+"/"+e.util.escapeFragment(I),n+=" "+e.validate(d)+" ",d.baseId=M,n+=" } ",u&&(n+=" if ("+v+") { ",h+="}"))}return u&&(n+=" "+h+" if ("+g+" == errors) {"),n},YP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data;d&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var h="i"+s,v="schema"+s;d||(n+=" var "+v+" = validate.schema"+l+";"),n+="var "+g+";",d&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=""+g+" = false;for (var "+h+"=0; "+h+"<"+v+".length; "+h+"++) if (equal("+f+", "+v+"["+h+"])) { "+g+" = true; break; }",d&&(n+=" } "),n+=" if (!"+g+") { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var p=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",u&&(n+=" else { "),n},XP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||"");if(e.opts.format===!1)return u&&(n+=" if (true) { "),n;var g=e.opts.$data&&i&&i.$data,d;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i;var h=e.opts.unknownFormats,v=Array.isArray(h);if(g){var m="format"+s,p="isObject"+s,_="formatType"+s;n+=" var "+m+" = formats["+d+"]; var "+p+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+_+" = "+p+" && "+m+".type || 'string'; if ("+p+") { ",e.async&&(n+=" var async"+s+" = "+m+".async; "),n+=" "+m+" = "+m+".validate; } if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),n+=" (",h!="ignore"&&(n+=" ("+d+" && !"+m+" ",v&&(n+=" && self._opts.unknownFormats.indexOf("+d+") == -1 "),n+=") || "),n+=" ("+m+" && "+_+" == '"+a+"' && !(typeof "+m+" == 'function' ? ",e.async?n+=" (async"+s+" ? await "+m+"("+f+") : "+m+"("+f+")) ":n+=" "+m+"("+f+") ",n+=" : "+m+".test("+f+"))))) {"}else{var m=e.formats[i];if(!m){if(h=="ignore")return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),u&&(n+=" if (true) { "),n;if(v&&h.indexOf(i)>=0)return u&&(n+=" if (true) { "),n;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var p=typeof m=="object"&&!(m instanceof RegExp)&&m.validate,_=p&&m.type||"string";if(p){var w=m.async===!0;m=m.validate}if(_!=a)return u&&(n+=" if (true) { "),n;if(w){if(!e.async)throw new Error("async format in sync schema");var b="formats"+e.util.getProperty(i)+".validate";n+=" if (!(await "+b+"("+f+"))) { "}else{n+=" if (! ";var b="formats"+e.util.getProperty(i);p&&(b+=".validate"),typeof m=="function"?n+=" "+b+"("+f+") ":n+=" "+b+".test("+f+") ",n+=") { "}}var S=S||[];S.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",g?n+=""+d:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match format "`,g?n+="' + "+d+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var I=n;return n=S.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+I+"]); ":n+=" validate.errors = ["+I+"]; return false; ":n+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { "),n},ek=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,h=e.util.copy(e);h.level++;var v="valid"+h.level,m=e.schema.then,p=e.schema.else,_=m!==void 0&&(e.opts.strictKeywords?typeof m=="object"&&Object.keys(m).length>0||m===!1:e.util.schemaHasRules(m,e.RULES.all)),w=p!==void 0&&(e.opts.strictKeywords?typeof p=="object"&&Object.keys(p).length>0||p===!1:e.util.schemaHasRules(p,e.RULES.all)),b=h.baseId;if(_||w){var S;h.createErrors=!1,h.schema=i,h.schemaPath=l,h.errSchemaPath=c,n+=" var "+d+" = errors; var "+g+" = true; ";var I=e.compositeRule;e.compositeRule=h.compositeRule=!0,n+=" "+e.validate(h)+" ",h.baseId=b,h.createErrors=!0,n+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.compositeRule=h.compositeRule=I,_?(n+=" if ("+v+") { ",h.schema=e.schema.then,h.schemaPath=e.schemaPath+".then",h.errSchemaPath=e.errSchemaPath+"/then",n+=" "+e.validate(h)+" ",h.baseId=b,n+=" "+g+" = "+v+"; ",_&&w?(S="ifClause"+s,n+=" var "+S+" = 'then'; "):S="'then'",n+=" } ",w&&(n+=" else { ")):n+=" if (!"+v+") { ",w&&(h.schema=e.schema.else,h.schemaPath=e.schemaPath+".else",h.errSchemaPath=e.errSchemaPath+"/else",n+=" "+e.validate(h)+" ",h.baseId=b,n+=" "+g+" = "+v+"; ",_&&w?(S="ifClause"+s,n+=" var "+S+" = 'else'; "):S="'else'",n+=" } "),n+=" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+S+" } ",e.opts.messages!==!1&&(n+=` , message: 'should match "' + `+S+` + '" schema' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } ",u&&(n+=" else { ")}else u&&(n+=" if (true) { ");return n},tk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,h=e.util.copy(e),v="";h.level++;var m="valid"+h.level,p="i"+s,_=h.dataLevel=e.dataLevel+1,w="data"+_,b=e.baseId;if(n+="var "+d+" = errors;var "+g+";",Array.isArray(i)){var S=e.schema.additionalItems;if(S===!1){n+=" "+g+" = "+f+".length <= "+i.length+"; ";var I=c;c=e.errSchemaPath+"/additionalItems",n+=" if (!"+g+") { ";var k=k||[];k.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+i.length+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var A=n;n=k.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+A+"]); ":n+=" validate.errors = ["+A+"]; return false; ":n+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",c=I,u&&(v+="}",n+=" else { ")}var O=i;if(O){for(var H,J=-1,K=O.length-1;J<K;)if(H=O[J+=1],e.opts.strictKeywords?typeof H=="object"&&Object.keys(H).length>0||H===!1:e.util.schemaHasRules(H,e.RULES.all)){n+=" "+m+" = true; if ("+f+".length > "+J+") { ";var z=f+"["+J+"]";h.schema=H,h.schemaPath=l+"["+J+"]",h.errSchemaPath=c+"/"+J,h.errorPath=e.util.getPathExpr(e.errorPath,J,e.opts.jsonPointers,!0),h.dataPathArr[_]=J;var U=e.validate(h);h.baseId=b,e.util.varOccurences(U,w)<2?n+=" "+e.util.varReplace(U,w,z)+" ":n+=" var "+w+" = "+z+"; "+U+" ",n+=" } ",u&&(n+=" if ("+m+") { ",v+="}")}}if(typeof S=="object"&&(e.opts.strictKeywords?typeof S=="object"&&Object.keys(S).length>0||S===!1:e.util.schemaHasRules(S,e.RULES.all))){h.schema=S,h.schemaPath=e.schemaPath+".additionalItems",h.errSchemaPath=e.errSchemaPath+"/additionalItems",n+=" "+m+" = true; if ("+f+".length > "+i.length+") { for (var "+p+" = "+i.length+"; "+p+" < "+f+".length; "+p+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var z=f+"["+p+"]";h.dataPathArr[_]=p;var U=e.validate(h);h.baseId=b,e.util.varOccurences(U,w)<2?n+=" "+e.util.varReplace(U,w,z)+" ":n+=" var "+w+" = "+z+"; "+U+" ",u&&(n+=" if (!"+m+") break; "),n+=" } } ",u&&(n+=" if ("+m+") { ",v+="}")}}else if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){h.schema=i,h.schemaPath=l,h.errSchemaPath=c,n+=" for (var "+p+" = 0; "+p+" < "+f+".length; "+p+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var z=f+"["+p+"]";h.dataPathArr[_]=p;var U=e.validate(h);h.baseId=b,e.util.varOccurences(U,w)<2?n+=" "+e.util.varReplace(U,w,z)+" ":n+=" var "+w+" = "+z+"; "+U+" ",u&&(n+=" if (!"+m+") break; "),n+=" }"}return u&&(n+=" "+v+" if ("+d+" == errors) {"),n},fm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,b,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i;var h=r=="maximum",v=h?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[v],p=e.opts.$data&&m&&m.$data,_=h?"<":">",w=h?">":"<",b=void 0;if(!(g||typeof i=="number"||i===void 0))throw new Error(r+" must be number");if(!(p||m===void 0||typeof m=="number"||typeof m=="boolean"))throw new Error(v+" must be number or boolean");if(p){var S=e.util.getData(m.$data,o,e.dataPathArr),I="exclusive"+s,k="exclType"+s,A="exclIsNumber"+s,O="op"+s,H="' + "+O+" + '";n+=" var schemaExcl"+s+" = "+S+"; ",S="schemaExcl"+s,n+=" var "+I+"; var "+k+" = typeof "+S+"; if ("+k+" != 'boolean' && "+k+" != 'undefined' && "+k+" != 'number') { ";var b=v,J=J||[];J.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(b||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: '"+v+" should be boolean' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var K=n;n=J.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+K+"]); ":n+=" validate.errors = ["+K+"]; return false; ":n+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" "+k+" == 'number' ? ( ("+I+" = "+d+" === undefined || "+S+" "+_+"= "+d+") ? "+f+" "+w+"= "+S+" : "+f+" "+w+" "+d+" ) : ( ("+I+" = "+S+" === true) ? "+f+" "+w+"= "+d+" : "+f+" "+w+" "+d+" ) || "+f+" !== "+f+") { var op"+s+" = "+I+" ? '"+_+"' : '"+_+"='; ",i===void 0&&(b=v,c=e.errSchemaPath+"/"+v,d=S,g=p)}else{var A=typeof m=="number",H=_;if(A&&g){var O="'"+H+"'";n+=" if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" ( "+d+" === undefined || "+m+" "+_+"= "+d+" ? "+f+" "+w+"= "+m+" : "+f+" "+w+" "+d+" ) || "+f+" !== "+f+") { "}else{A&&i===void 0?(I=!0,b=v,c=e.errSchemaPath+"/"+v,d=m,w+="="):(A&&(d=Math[h?"min":"max"](m,i)),m===(A?d:!0)?(I=!0,b=v,c=e.errSchemaPath+"/"+v,w+="="):(I=!1,H+="="));var O="'"+H+"'";n+=" if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" "+f+" "+w+" "+d+" || "+f+" !== "+f+") { "}}b=b||r;var J=J||[];J.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(b||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { comparison: "+O+", limit: "+d+", exclusive: "+I+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be "+H+" ",g?n+="' + "+d:n+=""+d+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var K=n;return n=J.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+K+"]); ":n+=" validate.errors = ["+K+"]; return false; ":n+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { "),n},hm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,v,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var h=r=="maxItems"?">":"<";n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" "+f+".length "+h+" "+d+") { ";var v=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxItems"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+d+" + '":n+=""+i,n+=" items' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var p=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},mm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,v,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var h=r=="maxLength"?">":"<";n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),e.opts.unicode===!1?n+=" "+f+".length ":n+=" ucs2length("+f+") ",n+=" "+h+" "+d+") { ";var v=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be ",r=="maxLength"?n+="longer":n+="shorter",n+=" than ",g?n+="' + "+d+" + '":n+=""+i,n+=" characters' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var p=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},vm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,v,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var h=r=="maxProperties"?">":"<";n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" Object.keys("+f+").length "+h+" "+d+") { ";var v=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxProperties"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+d+" + '":n+=""+i,n+=" properties' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var p=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},rk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");n+="var division"+s+";if (",g&&(n+=" "+d+" !== undefined && ( typeof "+d+" != 'number' || "),n+=" (division"+s+" = "+f+" / "+d+", ",e.opts.multipleOfPrecision?n+=" Math.abs(Math.round(division"+s+") - division"+s+") > 1e-"+e.opts.multipleOfPrecision+" ":n+=" division"+s+" !== parseInt(division"+s+") ",n+=" ) ",g&&(n+=" ) "),n+=" ) { ";var h=h||[];h.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { multipleOf: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be multiple of ",g?n+="' + "+d:n+=""+d+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var v=n;return n=h.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},nk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="errs__"+s,d=e.util.copy(e);d.level++;var h="valid"+d.level;if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=l,d.errSchemaPath=c,n+=" var "+g+" = errors; ";var v=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.createErrors=!1;var m;d.opts.allErrors&&(m=d.opts.allErrors,d.opts.allErrors=!1),n+=" "+e.validate(d)+" ",d.createErrors=!0,m&&(d.opts.allErrors=m),e.compositeRule=d.compositeRule=v,n+=" if ("+h+") { ";var p=p||[];p.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var _=n;n=p.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+_+"]); ":n+=" validate.errors = ["+_+"]; return false; ":n+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { errors = "+g+"; if (vErrors !== null) { if ("+g+") vErrors.length = "+g+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(n+=" if (false) { ");return n},ak=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d="errs__"+s,h=e.util.copy(e),v="";h.level++;var m="valid"+h.level,p=h.baseId,_="prevValid"+s,w="passingSchemas"+s;n+="var "+d+" = errors , "+_+" = false , "+g+" = false , "+w+" = null; ";var b=e.compositeRule;e.compositeRule=h.compositeRule=!0;var S=i;if(S)for(var I,k=-1,A=S.length-1;k<A;)I=S[k+=1],(e.opts.strictKeywords?typeof I=="object"&&Object.keys(I).length>0||I===!1:e.util.schemaHasRules(I,e.RULES.all))?(h.schema=I,h.schemaPath=l+"["+k+"]",h.errSchemaPath=c+"/"+k,n+=" "+e.validate(h)+" ",h.baseId=p):n+=" var "+m+" = true; ",k&&(n+=" if ("+m+" && "+_+") { "+g+" = false; "+w+" = ["+w+", "+k+"]; } else { ",v+="}"),n+=" if ("+m+") { "+g+" = "+_+" = true; "+w+" = "+k+"; }";return e.compositeRule=h.compositeRule=b,n+=""+v+"if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+w+" } ",e.opts.messages!==!1&&(n+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+="} else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; }",e.opts.allErrors&&(n+=" } "),n},sk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i;var h=g?"(new RegExp("+d+"))":e.usePattern(i);n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),n+=" !"+h+".test("+f+") ) { ";var v=v||[];v.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { pattern: ",g?n+=""+d:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match pattern "`,g?n+="' + "+d+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var m=n;return n=v.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+m+"]); ":n+=" validate.errors = ["+m+"]; return false; ":n+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},ok=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="errs__"+s,d=e.util.copy(e),h="";d.level++;var v="valid"+d.level,m="key"+s,p="idx"+s,_=d.dataLevel=e.dataLevel+1,w="data"+_,b="dataProperties"+s,S=Object.keys(i||{}).filter(ce),I=e.schema.patternProperties||{},k=Object.keys(I).filter(ce),A=e.schema.additionalProperties,O=S.length||k.length,H=A===!1,J=typeof A=="object"&&Object.keys(A).length,K=e.opts.removeAdditional,z=H||J||K,U=e.opts.ownProperties,G=e.baseId,se=e.schema.required;if(se&&!(e.opts.$data&&se.$data)&&se.length<e.opts.loopRequired)var ne=e.util.toHash(se);function ce(wt){return wt!=="__proto__"}if(n+="var "+g+" = errors;var "+v+" = true;",U&&(n+=" var "+b+" = undefined;"),z){if(U?n+=" "+b+" = "+b+" || Object.keys("+f+"); for (var "+p+"=0; "+p+"<"+b+".length; "+p+"++) { var "+m+" = "+b+"["+p+"]; ":n+=" for (var "+m+" in "+f+") { ",O){if(n+=" var isAdditional"+s+" = !(false ",S.length)if(S.length>8)n+=" || validate.schema"+l+".hasOwnProperty("+m+") ";else{var pe=S;if(pe)for(var M,R=-1,D=pe.length-1;R<D;)M=pe[R+=1],n+=" || "+m+" == "+e.util.toQuotedString(M)+" "}if(k.length){var N=k;if(N)for(var y,P=-1,j=N.length-1;P<j;)y=N[P+=1],n+=" || "+e.usePattern(y)+".test("+m+") "}n+=" ); if (isAdditional"+s+") { "}if(K=="all")n+=" delete "+f+"["+m+"]; ";else{var Q=e.errorPath,ee="' + "+m+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),H)if(K)n+=" delete "+f+"["+m+"]; ";else{n+=" "+v+" = false; ";var Se=c;c=e.errSchemaPath+"/additionalProperties";var de=de||[];de.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+ee+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is an invalid additional property":n+="should NOT have additional properties",n+="' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var ge=n;n=de.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+ge+"]); ":n+=" validate.errors = ["+ge+"]; return false; ":n+=" var err = "+ge+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=Se,u&&(n+=" break; ")}else if(J)if(K=="failing"){n+=" var "+g+" = errors; ";var vt=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.schema=A,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var Te=f+"["+m+"]";d.dataPathArr[_]=m;var me=e.validate(d);d.baseId=G,e.util.varOccurences(me,w)<2?n+=" "+e.util.varReplace(me,w,Te)+" ":n+=" var "+w+" = "+Te+"; "+me+" ",n+=" if (!"+v+") { errors = "+g+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+f+"["+m+"]; } ",e.compositeRule=d.compositeRule=vt}else{d.schema=A,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var Te=f+"["+m+"]";d.dataPathArr[_]=m;var me=e.validate(d);d.baseId=G,e.util.varOccurences(me,w)<2?n+=" "+e.util.varReplace(me,w,Te)+" ":n+=" var "+w+" = "+Te+"; "+me+" ",u&&(n+=" if (!"+v+") break; ")}e.errorPath=Q}O&&(n+=" } "),n+=" } ",u&&(n+=" if ("+v+") { ",h+="}")}var Ne=e.opts.useDefaults&&!e.compositeRule;if(S.length){var Ae=S;if(Ae)for(var M,ke=-1,tt=Ae.length-1;ke<tt;){M=Ae[ke+=1];var Ze=i[M];if(e.opts.strictKeywords?typeof Ze=="object"&&Object.keys(Ze).length>0||Ze===!1:e.util.schemaHasRules(Ze,e.RULES.all)){var re=e.util.getProperty(M),Te=f+re,ze=Ne&&Ze.default!==void 0;d.schema=Ze,d.schemaPath=l+re,d.errSchemaPath=c+"/"+e.util.escapeFragment(M),d.errorPath=e.util.getPath(e.errorPath,M,e.opts.jsonPointers),d.dataPathArr[_]=e.util.toQuotedString(M);var me=e.validate(d);if(d.baseId=G,e.util.varOccurences(me,w)<2){me=e.util.varReplace(me,w,Te);var Be=Te}else{var Be=w;n+=" var "+w+" = "+Te+"; "}if(ze)n+=" "+me+" ";else{if(ne&&ne[M]){n+=" if ( "+Be+" === undefined ",U&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(M)+"') "),n+=") { "+v+" = false; ";var Q=e.errorPath,Se=c,Ee=e.util.escapeQuotes(M);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(Q,M,e.opts.jsonPointers)),c=e.errSchemaPath+"/required";var de=de||[];de.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+Ee+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+Ee+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var ge=n;n=de.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+ge+"]); ":n+=" validate.errors = ["+ge+"]; return false; ":n+=" var err = "+ge+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=Se,e.errorPath=Q,n+=" } else { "}else u?(n+=" if ( "+Be+" === undefined ",U&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(M)+"') "),n+=") { "+v+" = true; } else { "):(n+=" if ("+Be+" !== undefined ",U&&(n+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(M)+"') "),n+=" ) { ");n+=" "+me+" } "}}u&&(n+=" if ("+v+") { ",h+="}")}}if(k.length){var Qe=k;if(Qe)for(var y,ir=-1,Mt=Qe.length-1;ir<Mt;){y=Qe[ir+=1];var Ze=I[y];if(e.opts.strictKeywords?typeof Ze=="object"&&Object.keys(Ze).length>0||Ze===!1:e.util.schemaHasRules(Ze,e.RULES.all)){d.schema=Ze,d.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(y),d.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(y),U?n+=" "+b+" = "+b+" || Object.keys("+f+"); for (var "+p+"=0; "+p+"<"+b+".length; "+p+"++) { var "+m+" = "+b+"["+p+"]; ":n+=" for (var "+m+" in "+f+") { ",n+=" if ("+e.usePattern(y)+".test("+m+")) { ",d.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var Te=f+"["+m+"]";d.dataPathArr[_]=m;var me=e.validate(d);d.baseId=G,e.util.varOccurences(me,w)<2?n+=" "+e.util.varReplace(me,w,Te)+" ":n+=" var "+w+" = "+Te+"; "+me+" ",u&&(n+=" if (!"+v+") break; "),n+=" } ",u&&(n+=" else "+v+" = true; "),n+=" } ",u&&(n+=" if ("+v+") { ",h+="}")}}}return u&&(n+=" "+h+" if ("+g+" == errors) {"),n},ik=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="errs__"+s,d=e.util.copy(e),h="";d.level++;var v="valid"+d.level;if(n+="var "+g+" = errors;",e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=l,d.errSchemaPath=c;var m="key"+s,p="idx"+s,_="i"+s,w="' + "+m+" + '",b=d.dataLevel=e.dataLevel+1,S="data"+b,I="dataProperties"+s,k=e.opts.ownProperties,A=e.baseId;k&&(n+=" var "+I+" = undefined; "),k?n+=" "+I+" = "+I+" || Object.keys("+f+"); for (var "+p+"=0; "+p+"<"+I+".length; "+p+"++) { var "+m+" = "+I+"["+p+"]; ":n+=" for (var "+m+" in "+f+") { ",n+=" var startErrs"+s+" = errors; ";var O=m,H=e.compositeRule;e.compositeRule=d.compositeRule=!0;var J=e.validate(d);d.baseId=A,e.util.varOccurences(J,S)<2?n+=" "+e.util.varReplace(J,S,O)+" ":n+=" var "+S+" = "+O+"; "+J+" ",e.compositeRule=d.compositeRule=H,n+=" if (!"+v+") { for (var "+_+"=startErrs"+s+"; "+_+"<errors; "+_+"++) { vErrors["+_+"].propertyName = "+m+"; } var err = ",e.createErrors!==!1?(n+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+w+"' } ",e.opts.messages!==!1&&(n+=" , message: 'property name \\'"+w+"\\' is invalid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),u&&(n+=" break; "),n+=" } }"}return u&&(n+=" "+h+" if ("+g+" == errors) {"),n},lk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data;d&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var h="schema"+s;if(!d)if(i.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var v=[],m=i;if(m)for(var p,_=-1,w=m.length-1;_<w;){p=m[_+=1];var b=e.schema.properties[p];b&&(e.opts.strictKeywords?typeof b=="object"&&Object.keys(b).length>0||b===!1:e.util.schemaHasRules(b,e.RULES.all))||(v[v.length]=p)}}else var v=i;if(d||v.length){var S=e.errorPath,I=d||v.length>=e.opts.loopRequired,k=e.opts.ownProperties;if(u)if(n+=" var missing"+s+"; ",I){d||(n+=" var "+h+" = validate.schema"+l+"; ");var A="i"+s,O="schema"+s+"["+A+"]",H="' + "+O+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(S,O,e.opts.jsonPointers)),n+=" var "+g+" = true; ",d&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=" for (var "+A+" = 0; "+A+" < "+h+".length; "+A+"++) { "+g+" = "+f+"["+h+"["+A+"]] !== undefined ",k&&(n+=" && Object.prototype.hasOwnProperty.call("+f+", "+h+"["+A+"]) "),n+="; if (!"+g+") break; } ",d&&(n+=" } "),n+=" if (!"+g+") { ";var J=J||[];J.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var K=n;n=J.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+K+"]); ":n+=" validate.errors = ["+K+"]; return false; ":n+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else{n+=" if ( ";var z=v;if(z)for(var U,A=-1,G=z.length-1;A<G;){U=z[A+=1],A&&(n+=" || ");var se=e.util.getProperty(U),ne=f+se;n+=" ( ( "+ne+" === undefined ",k&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(U)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?U:se)+") ) "}n+=") { ";var O="missing"+s,H="' + "+O+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(S,O,!0):S+" + "+O);var J=J||[];J.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var K=n;n=J.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+K+"]); ":n+=" validate.errors = ["+K+"]; return false; ":n+=" var err = "+K+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else if(I){d||(n+=" var "+h+" = validate.schema"+l+"; ");var A="i"+s,O="schema"+s+"["+A+"]",H="' + "+O+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(S,O,e.opts.jsonPointers)),d&&(n+=" if ("+h+" && !Array.isArray("+h+")) { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+h+" !== undefined) { "),n+=" for (var "+A+" = 0; "+A+" < "+h+".length; "+A+"++) { if ("+f+"["+h+"["+A+"]] === undefined ",k&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", "+h+"["+A+"]) "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",d&&(n+=" } ")}else{var ce=v;if(ce)for(var U,pe=-1,M=ce.length-1;pe<M;){U=ce[pe+=1];var se=e.util.getProperty(U),H=e.util.escapeQuotes(U),ne=f+se;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(S,U,e.opts.jsonPointers)),n+=" if ( "+ne+" === undefined ",k&&(n+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(U)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+H+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+H+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=S}else u&&(n+=" if (true) {");return n},ck=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data,h;if(d?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",h="schema"+s):h=i,(i||d)&&e.opts.uniqueItems!==!1){d&&(n+=" var "+g+"; if ("+h+" === false || "+h+" === undefined) "+g+" = true; else if (typeof "+h+" != 'boolean') "+g+" = false; else { "),n+=" var i = "+f+".length , "+g+" = true , j; if (i > 1) { ";var v=e.schema.items&&e.schema.items.type,m=Array.isArray(v);if(!v||v=="object"||v=="array"||m&&(v.indexOf("object")>=0||v.indexOf("array")>=0))n+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+f+"[i], "+f+"[j])) { "+g+" = false; break outer; } } } ";else{n+=" var itemIndices = {}, item; for (;i--;) { var item = "+f+"[i]; ";var p="checkDataType"+(m?"s":"");n+=" if ("+e.util[p](v,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(n+=` if (typeof item == 'string') item = '"' + item; `),n+=" if (typeof itemIndices[item] == 'number') { "+g+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}n+=" } ",d&&(n+=" } "),n+=" if (!"+g+") { ";var _=_||[];_.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(n+=" , schema: ",d?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),n+=" } "):n+=" {} ";var w=n;n=_.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+w+"]); ":n+=" validate.errors = ["+w+"]; return false; ":n+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { ")}else u&&(n+=" if (true) { ");return n},uk={$ref:HP,allOf:BP,anyOf:JP,$comment:GP,const:KP,contains:WP,dependencies:QP,enum:YP,format:XP,if:ek,items:tk,maximum:fm,minimum:fm,maxItems:hm,minItems:hm,maxLength:mm,minLength:mm,maxProperties:vm,minProperties:vm,multipleOf:rk,not:nk,oneOf:ak,pattern:sk,properties:ok,propertyNames:ik,required:lk,uniqueItems:ck,validate:Yh},gm=uk,$u=Da.toHash,dk=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],r=["type","$comment"],a=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],n=["number","integer","string","array","object","boolean","null"];return e.all=$u(r),e.types=$u(n),e.forEach(function(s){s.rules=s.rules.map(function(o){var i;if(typeof o=="object"){var l=Object.keys(o)[0];i=o[l],o=l,i.forEach(function(u){r.push(u),e.all[u]=!0})}r.push(o);var c=e.all[o]={keyword:o,code:gm[o],implements:i};return c}),e.all.$comment={keyword:"$comment",code:gm.$comment},s.type&&(e.types[s.type]=s)}),e.keywords=$u(r.concat(a)),e.custom={},e},ym=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],pk=function(t,e){for(var r=0;r<e.length;r++){t=JSON.parse(JSON.stringify(t));var a=e[r].split("/"),n=t,s;for(s=1;s<a.length;s++)n=n[a[s]];for(s=0;s<ym.length;s++){var o=ym[s],i=n[o];i&&(n[o]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return t},fk=bu.MissingRef,hk=_m;function _m(t,e,r){var a=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var n=s(t).then(function(){var i=a._addSchema(t,void 0,e);return i.validate||o(i)});return r&&n.then(function(i){r(null,i)},r),n;function s(i){var l=i.$schema;return l&&!a.getSchema(l)?_m.call(a,{$ref:l},!0):Promise.resolve()}function o(i){try{return a._compile(i)}catch(c){if(c instanceof fk)return l(c);throw c}function l(c){var u=c.missingSchema;if(d(u))throw new Error("Schema "+u+" is loaded but "+c.missingRef+" cannot be resolved");var f=a._loadingSchemas[u];return f||(f=a._loadingSchemas[u]=a._opts.loadSchema(u),f.then(g,g)),f.then(function(h){if(!d(u))return s(h).then(function(){d(u)||a.addSchema(h,u,void 0,e)})}).then(function(){return o(i)});function g(){delete a._loadingSchemas[u]}function d(h){return a._refs[h]||a._schemas[h]}}}}var mk=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,f,g="data"+(o||""),d="valid"+s,h="errs__"+s,v=e.opts.$data&&i&&i.$data,m;v?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",m="schema"+s):m=i;var p=this,_="definition"+s,w=p.definition,b="",S,I,k,A,O;if(v&&w.$data){O="keywordValidate"+s;var H=w.validateSchema;n+=" var "+_+" = RULES.custom['"+r+"'].definition; var "+O+" = "+_+".validate;"}else{if(A=e.useCustomRule(p,i,e.schema,e),!A)return;m="validate.schema"+l,O=A.code,S=w.compile,I=w.inline,k=w.macro}var J=O+".errors",K="i"+s,z="ruleErr"+s,U=w.async;if(U&&!e.async)throw new Error("async keyword in sync schema");if(I||k||(n+=""+J+" = null;"),n+="var "+h+" = errors;var "+d+";",v&&w.$data&&(b+="}",n+=" if ("+m+" === undefined) { "+d+" = true; } else { ",H&&(b+="}",n+=" "+d+" = "+_+".validateSchema("+m+"); if ("+d+") { ")),I)w.statements?n+=" "+A.validate+" ":n+=" "+d+" = "+A.validate+"; ";else if(k){var G=e.util.copy(e),b="";G.level++;var se="valid"+G.level;G.schema=A.validate,G.schemaPath="";var ne=e.compositeRule;e.compositeRule=G.compositeRule=!0;var ce=e.validate(G).replace(/validate\.schema/g,O);e.compositeRule=G.compositeRule=ne,n+=" "+ce}else{var pe=pe||[];pe.push(n),n="",n+=" "+O+".call( ",e.opts.passContext?n+="this":n+="self",S||w.schema===!1?n+=" , "+g+" ":n+=" , "+m+" , "+g+" , validate.schema"+e.schemaPath+" ",n+=" , (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var M=o?"data"+(o-1||""):"parentData",R=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+M+" , "+R+" , rootData ) ";var D=n;n=pe.pop(),w.errors===!1?(n+=" "+d+" = ",U&&(n+="await "),n+=""+D+"; "):U?(J="customErrors"+s,n+=" var "+J+" = null; try { "+d+" = await "+D+"; } catch (e) { "+d+" = false; if (e instanceof ValidationError) "+J+" = e.errors; else throw e; } "):n+=" "+J+" = null; "+d+" = "+D+"; "}if(w.modifying&&(n+=" if ("+M+") "+g+" = "+M+"["+R+"];"),n+=""+b,w.valid)u&&(n+=" if (true) { ");else{n+=" if ( ",w.valid===void 0?(n+=" !",k?n+=""+se:n+=""+d):n+=" "+!w.valid+" ",n+=") { ",f=p.keyword;var pe=pe||[];pe.push(n),n="";var pe=pe||[];pe.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(f||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { keyword: '"+p.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+p.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var N=n;n=pe.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+N+"]); ":n+=" validate.errors = ["+N+"]; return false; ":n+=" var err = "+N+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var y=n;n=pe.pop(),I?w.errors?w.errors!="full"&&(n+=" for (var "+K+"="+h+"; "+K+"<errors; "+K+"++) { var "+z+" = vErrors["+K+"]; if ("+z+".dataPath === undefined) "+z+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+z+".schemaPath === undefined) { "+z+'.schemaPath = "'+c+'"; } ',e.opts.verbose&&(n+=" "+z+".schema = "+m+"; "+z+".data = "+g+"; "),n+=" } "):w.errors===!1?n+=" "+y+" ":(n+=" if ("+h+" == errors) { "+y+" } else { for (var "+K+"="+h+"; "+K+"<errors; "+K+"++) { var "+z+" = vErrors["+K+"]; if ("+z+".dataPath === undefined) "+z+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+z+".schemaPath === undefined) { "+z+'.schemaPath = "'+c+'"; } ',e.opts.verbose&&(n+=" "+z+".schema = "+m+"; "+z+".data = "+g+"; "),n+=" } } "):k?(n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: '"+(f||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { keyword: '"+p.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+p.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; ")):w.errors===!1?n+=" "+y+" ":(n+=" if (Array.isArray("+J+")) { if (vErrors === null) vErrors = "+J+"; else vErrors = vErrors.concat("+J+"); errors = vErrors.length; for (var "+K+"="+h+"; "+K+"<errors; "+K+"++) { var "+z+" = vErrors["+K+"]; if ("+z+".dataPath === undefined) "+z+".dataPath = (dataPath || '') + "+e.errorPath+"; "+z+'.schemaPath = "'+c+'"; ',e.opts.verbose&&(n+=" "+z+".schema = "+m+"; "+z+".data = "+g+"; "),n+=" } } else { "+y+" } "),n+=" } ",u&&(n+=" else { ")}return n};const wm={$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 bm=wm,vk={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:bm.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:bm.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},gk=/^[a-z_$][a-z0-9_$-]*$/i,yk=mk,_k=vk,wk={add:bk,get:Ek,remove:Sk,validate:Pu};function bk(t,e){var r=this.RULES;if(r.keywords[t])throw new Error("Keyword "+t+" is already defined");if(!gk.test(t))throw new Error("Keyword "+t+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var a=e.type;if(Array.isArray(a))for(var n=0;n<a.length;n++)o(t,a[n],e);else o(t,a,e);var s=e.metaSchema;s&&(e.$data&&this._opts.$data&&(s={anyOf:[s,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(s,!0))}r.keywords[t]=r.all[t]=!0;function o(i,l,c){for(var u,f=0;f<r.length;f++){var g=r[f];if(g.type==l){u=g;break}}u||(u={type:l,rules:[]},r.push(u));var d={keyword:i,definition:c,custom:!0,code:yk,implements:c.implements};u.rules.push(d),r.custom[i]=d}return this}function Ek(t){var e=this.RULES.custom[t];return e?e.definition:this.RULES.keywords[t]||!1}function Sk(t){var e=this.RULES;delete e.keywords[t],delete e.all[t],delete e.custom[t];for(var r=0;r<e.length;r++)for(var a=e[r].rules,n=0;n<a.length;n++)if(a[n].keyword==t){a.splice(n,1);break}return this}function Pu(t,e){Pu.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(_k,!0);if(r(t))return!0;if(Pu.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}const $k={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var Em=$P,ea=vu,Pk=RP,Sm=Hh,kk=Qh,Ik=LP,xk=dk,$m=pk,Pm=Da,Tk=mt;mt.prototype.validate=Rk,mt.prototype.compile=Ok,mt.prototype.addSchema=Nk,mt.prototype.addMetaSchema=Ak,mt.prototype.validateSchema=Mk,mt.prototype.getSchema=Dk,mt.prototype.removeSchema=zk,mt.prototype.addFormat=Jk,mt.prototype.errorsText=Bk,mt.prototype._addSchema=Uk,mt.prototype._compile=qk,mt.prototype.compileAsync=hk;var Ii=wk;mt.prototype.addKeyword=Ii.add,mt.prototype.getKeyword=Ii.get,mt.prototype.removeKeyword=Ii.remove,mt.prototype.validateKeyword=Ii.validate;var km=bu;mt.ValidationError=km.Validation,mt.MissingRefError=km.MissingRef,mt.$dataMetaSchema=$m;var xi="http://json-schema.org/draft-07/schema",Im=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],Ck=["/properties"];function mt(t){if(!(this instanceof mt))return new mt(t);t=this._opts=Pm.copy(t)||{},Xk(this),this._schemas={},this._refs={},this._fragments={},this._formats=Ik(t.format),this._cache=t.cache||new Pk,this._loadingSchemas={},this._compilations=[],this.RULES=xk(),this._getId=Fk(t),t.loopRequired=t.loopRequired||1/0,t.errorDataPath=="property"&&(t._errorDataPathProperty=!0),t.serialize===void 0&&(t.serialize=kk),this._metaOpts=Yk(this),t.formats&&Wk(this),t.keywords&&Qk(this),Gk(this),typeof t.meta=="object"&&this.addMetaSchema(t.meta),t.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),Kk(this)}function Rk(t,e){var r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error('no schema with key or ref "'+t+'"')}else{var a=this._addSchema(t);r=a.validate||this._compile(a)}var n=r(e);return r.$async!==!0&&(this.errors=r.errors),n}function Ok(t,e){var r=this._addSchema(t,void 0,e);return r.validate||this._compile(r)}function Nk(t,e,r,a){if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.addSchema(t[n],void 0,r,a);return this}var s=this._getId(t);if(s!==void 0&&typeof s!="string")throw new Error("schema id must be string");return e=ea.normalizeId(e||s),Tm(this,e),this._schemas[e]=this._addSchema(t,r,a,!0),this}function Ak(t,e,r){return this.addSchema(t,e,r,!0),this}function Mk(t,e){var r=t.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||jk(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,t);if(!a&&e){var n="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(n);else throw new Error(n)}return a}function jk(t){var e=t._opts.meta;return t._opts.defaultMeta=typeof e=="object"?t._getId(e)||e:t.getSchema(xi)?xi:void 0,t._opts.defaultMeta}function Dk(t){var e=xm(this,t);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return Lk(this,t)}}function Lk(t,e){var r=ea.schema.call(t,{schema:{}},e);if(r){var a=r.schema,n=r.root,s=r.baseId,o=Em.call(t,a,n,void 0,s);return t._fragments[e]=new Sm({ref:e,fragment:!0,schema:a,root:n,baseId:s,validate:o}),o}}function xm(t,e){return e=ea.normalizeId(e),t._schemas[e]||t._refs[e]||t._fragments[e]}function zk(t){if(t instanceof RegExp)return Ti(this,this._schemas,t),Ti(this,this._refs,t),this;switch(typeof t){case"undefined":return Ti(this,this._schemas),Ti(this,this._refs),this._cache.clear(),this;case"string":var e=xm(this,t);return e&&this._cache.del(e.cacheKey),delete this._schemas[t],delete this._refs[t],this;case"object":var r=this._opts.serialize,a=r?r(t):t;this._cache.del(a);var n=this._getId(t);n&&(n=ea.normalizeId(n),delete this._schemas[n],delete this._refs[n])}return this}function Ti(t,e,r){for(var a in e){var n=e[a];!n.meta&&(!r||r.test(a))&&(t._cache.del(n.cacheKey),delete e[a])}}function Uk(t,e,r,a){if(typeof t!="object"&&typeof t!="boolean")throw new Error("schema should be object or boolean");var n=this._opts.serialize,s=n?n(t):t,o=this._cache.get(s);if(o)return o;a=a||this._opts.addUsedSchema!==!1;var i=ea.normalizeId(this._getId(t));i&&a&&Tm(this,i);var l=this._opts.validateSchema!==!1&&!e,c;l&&!(c=i&&i==ea.normalizeId(t.$schema))&&this.validateSchema(t,!0);var u=ea.ids.call(this,t),f=new Sm({id:i,schema:t,localRefs:u,cacheKey:s,meta:r});return i[0]!="#"&&a&&(this._refs[i]=f),this._cache.put(s,f),l&&c&&this.validateSchema(t,!0),f}function qk(t,e){if(t.compiling)return t.validate=n,n.schema=t.schema,n.errors=null,n.root=e||n,t.schema.$async===!0&&(n.$async=!0),n;t.compiling=!0;var r;t.meta&&(r=this._opts,this._opts=this._metaOpts);var a;try{a=Em.call(this,t.schema,e,t.localRefs)}catch(s){throw delete t.validate,s}finally{t.compiling=!1,t.meta&&(this._opts=r)}return t.validate=a,t.refs=a.refs,t.refVal=a.refVal,t.root=a.root,a;function n(){var s=t.validate,o=s.apply(this,arguments);return n.errors=s.errors,o}}function Fk(t){switch(t.schemaId){case"auto":return Hk;case"id":return Zk;default:return Vk}}function Zk(t){return t.$id&&this.logger.warn("schema $id ignored",t.$id),t.id}function Vk(t){return t.id&&this.logger.warn("schema id ignored",t.id),t.$id}function Hk(t){if(t.$id&&t.id&&t.$id!=t.id)throw new Error("schema $id is different from id");return t.$id||t.id}function Bk(t,e){if(t=t||this.errors,!t)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,a=e.dataVar===void 0?"data":e.dataVar,n="",s=0;s<t.length;s++){var o=t[s];o&&(n+=a+o.dataPath+" "+o.message+r)}return n.slice(0,-r.length)}function Jk(t,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[t]=e,this}function Gk(t){var e;if(t._opts.$data&&(e=$k,t.addMetaSchema(e,e.$id,!0)),t._opts.meta!==!1){var r=wm;t._opts.$data&&(r=$m(r,Ck)),t.addMetaSchema(r,xi,!0),t._refs["http://json-schema.org/schema"]=xi}}function Kk(t){var e=t._opts.schemas;if(e)if(Array.isArray(e))t.addSchema(e);else for(var r in e)t.addSchema(e[r],r)}function Wk(t){for(var e in t._opts.formats){var r=t._opts.formats[e];t.addFormat(e,r)}}function Qk(t){for(var e in t._opts.keywords){var r=t._opts.keywords[e];t.addKeyword(e,r)}}function Tm(t,e){if(t._schemas[e]||t._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function Yk(t){for(var e=Pm.copy(t._opts),r=0;r<Im.length;r++)delete e[Im[r]];return e}function Xk(t){var e=t._opts.logger;if(e===!1)t.logger={log:ku,warn:ku,error:ku};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");t.logger=e}}function ku(){}const Cm=Pp(Tk);class qs extends qh{constructor(e,r){var a;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=r==null?void 0:r.capabilities)!==null&&a!==void 0?a:{},this._ajv=new Cm}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fh(this._capabilities,e)}assertCapability(e,r){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const a=await this.request({method:"initialize",params:{protocolVersion:js,capabilities:this._capabilities,clientInfo:this._clientInfo}},gh,r);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!ih.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(a.protocolVersion),this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,a,n,s,o;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break}}async ping(e){return this.request({method:"ping"},Tn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Lh,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Tn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Rh,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Th,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Eh,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Sh,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},$h,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Tn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Tn,r)}async callTool(e,r=fi,a){const n=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!n.structuredContent&&!n.isError)throw new st(rt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{if(!s(n.structuredContent))throw new st(rt.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(o){throw o instanceof st?o:new st(rt.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return n}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const r of e)if(r.outputSchema)try{const a=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const a=await this.request({method:"tools/list",params:e},Nh,r);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class Rm extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function Iu(t){}function Om(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=Iu,onError:r=Iu,onRetry:a=Iu,onComment:n}=t;let s="",o=!0,i,l="",c="";function u(v){const m=o?v.replace(/^\xEF\xBB\xBF/,""):v,[p,_]=eI(`${s}${m}`);for(const w of p)f(w);s=_,o=!1}function f(v){if(v===""){d();return}if(v.startsWith(":")){n&&n(v.slice(v.startsWith(": ")?2:1));return}const m=v.indexOf(":");if(m!==-1){const p=v.slice(0,m),_=v[m+1]===" "?2:1,w=v.slice(m+_);g(p,w,v);return}g(v,"",v)}function g(v,m,p){switch(v){case"event":c=m;break;case"data":l=`${l}${m}
9
- `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?a(parseInt(m,10)):r(new Rm(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:p}));break;default:r(new Rm(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:m,line:p}));break}}function d(){l.length>0&&e({id:i,event:c||void 0,data:l.endsWith(`
10
- `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function h(v={}){s&&v.consume&&f(s),o=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:h}}function eI(t){const e=[];let r="",a=0;for(;a<t.length;){const n=t.indexOf("\r",a),s=t.indexOf(`
11
- `,a);let o=-1;if(n!==-1&&s!==-1?o=Math.min(n,s):n!==-1?n===t.length-1?o=-1:o=n:s!==-1&&(o=s),o===-1){r=t.slice(a);break}else{const i=t.slice(a,o);e.push(i),a=o+1,t[a-1]==="\r"&&t[a]===`
12
- `&&a++}}return[e,r]}class Nm extends Event{constructor(e,r){var a,n;super(e),this.code=(a=r==null?void 0:r.code)!=null?a:void 0,this.message=(n=r==null?void 0:r.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,a){return a(Am(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(Am(this),r)}}function tI(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function xu(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(xu).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${xu(t.cause)}`:t.message:`${t}`}function Am(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var Mm=t=>{throw TypeError(t)},Tu=(t,e,r)=>e.has(t)||Mm("Cannot "+r),Le=(t,e,r)=>(Tu(t,e,"read from private field"),r?r.call(t):e.get(t)),Ct=(t,e,r)=>e.has(t)?Mm("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),lt=(t,e,r,a)=>(Tu(t,e,"write to private field"),e.set(t,r),r),yn=(t,e,r)=>(Tu(t,e,"access private method"),r),er,ta,La,Ci,Ri,Fs,za,Zs,Nn,Ua,qa,Fa,Vs,Rr,Cu,Ru,Ou,jm,Nu,Au,Hs,Mu,ju;class Oi extends EventTarget{constructor(e,r){var a,n;super(),Ct(this,Rr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ct(this,er),Ct(this,ta),Ct(this,La),Ct(this,Ci),Ct(this,Ri),Ct(this,Fs),Ct(this,za),Ct(this,Zs,null),Ct(this,Nn),Ct(this,Ua),Ct(this,qa,null),Ct(this,Fa,null),Ct(this,Vs,null),Ct(this,Ru,async s=>{var o;Le(this,Ua).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){yn(this,Rr,Hs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?lt(this,La,new URL(s.url)):lt(this,La,void 0),c!==200){yn(this,Rr,Hs).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){yn(this,Rr,Hs).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(Le(this,er)===this.CLOSED)return;lt(this,er,this.OPEN);const f=new Event("open");if((o=Le(this,Vs))==null||o.call(this,f),this.dispatchEvent(f),typeof i!="object"||!i||!("getReader"in i)){yn(this,Rr,Hs).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const g=new TextDecoder,d=i.getReader();let h=!0;do{const{done:v,value:m}=await d.read();m&&Le(this,Ua).feed(g.decode(m,{stream:!v})),v&&(h=!1,Le(this,Ua).reset(),yn(this,Rr,Mu).call(this))}while(h)}),Ct(this,Ou,s=>{lt(this,Nn,void 0),!(s.name==="AbortError"||s.type==="aborted")&&yn(this,Rr,Mu).call(this,xu(s))}),Ct(this,Nu,s=>{typeof s.id=="string"&&lt(this,Zs,s.id);const o=new MessageEvent(s.event||"message",{data:s.data,origin:Le(this,La)?Le(this,La).origin:Le(this,ta).origin,lastEventId:s.id||""});Le(this,Fa)&&(!s.event||s.event==="message")&&Le(this,Fa).call(this,o),this.dispatchEvent(o)}),Ct(this,Au,s=>{lt(this,Fs,s)}),Ct(this,ju,()=>{lt(this,za,void 0),Le(this,er)===this.CONNECTING&&yn(this,Rr,Cu).call(this)});try{if(e instanceof URL)lt(this,ta,e);else if(typeof e=="string")lt(this,ta,new URL(e,rI()));else throw new Error("Invalid URL")}catch{throw tI("An invalid or illegal string was specified")}lt(this,Ua,Om({onEvent:Le(this,Nu),onRetry:Le(this,Au)})),lt(this,er,this.CONNECTING),lt(this,Fs,3e3),lt(this,Ri,(a=r==null?void 0:r.fetch)!=null?a:globalThis.fetch),lt(this,Ci,(n=r==null?void 0:r.withCredentials)!=null?n:!1),yn(this,Rr,Cu).call(this)}get readyState(){return Le(this,er)}get url(){return Le(this,ta).href}get withCredentials(){return Le(this,Ci)}get onerror(){return Le(this,qa)}set onerror(e){lt(this,qa,e)}get onmessage(){return Le(this,Fa)}set onmessage(e){lt(this,Fa,e)}get onopen(){return Le(this,Vs)}set onopen(e){lt(this,Vs,e)}addEventListener(e,r,a){const n=r;super.addEventListener(e,n,a)}removeEventListener(e,r,a){const n=r;super.removeEventListener(e,n,a)}close(){Le(this,za)&&clearTimeout(Le(this,za)),Le(this,er)!==this.CLOSED&&(Le(this,Nn)&&Le(this,Nn).abort(),lt(this,er,this.CLOSED),lt(this,Nn,void 0))}}er=new WeakMap,ta=new WeakMap,La=new WeakMap,Ci=new WeakMap,Ri=new WeakMap,Fs=new WeakMap,za=new WeakMap,Zs=new WeakMap,Nn=new WeakMap,Ua=new WeakMap,qa=new WeakMap,Fa=new WeakMap,Vs=new WeakMap,Rr=new WeakSet,Cu=function(){lt(this,er,this.CONNECTING),lt(this,Nn,new AbortController),Le(this,Ri)(Le(this,ta),yn(this,Rr,jm).call(this)).then(Le(this,Ru)).catch(Le(this,Ou))},Ru=new WeakMap,Ou=new WeakMap,jm=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Le(this,Zs)?{"Last-Event-ID":Le(this,Zs)}:void 0},cache:"no-store",signal:(t=Le(this,Nn))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Nu=new WeakMap,Au=new WeakMap,Hs=function(t,e){var r;Le(this,er)!==this.CLOSED&&lt(this,er,this.CLOSED);const a=new Nm("error",{code:e,message:t});(r=Le(this,qa))==null||r.call(this,a),this.dispatchEvent(a)},Mu=function(t,e){var r;if(Le(this,er)===this.CLOSED)return;lt(this,er,this.CONNECTING);const a=new Nm("error",{code:e,message:t});(r=Le(this,qa))==null||r.call(this,a),this.dispatchEvent(a),lt(this,za,setTimeout(Le(this,ju),Le(this,Fs)))},ju=new WeakMap,Oi.CONNECTING=0,Oi.OPEN=1,Oi.CLOSED=2;function rI(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}let Du;Du=globalThis.crypto;async function nI(t){return(await Du).getRandomValues(new Uint8Array(t))}async function aI(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let r="";const a=await nI(t);for(let n=0;n<t;n++){const s=a[n]%e.length;r+=e[s]}return r}async function sI(t){return await aI(t)}async function oI(t){const e=await(await Du).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function iI(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await sI(t),r=await oI(e);return{code_verifier:e,code_challenge:r}}const Ut=L().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:X.custom,message:"URL must be parseable",fatal:!0}),oh}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),lI=te({resource:L().url(),authorization_servers:ue(Ut).optional(),jwks_uri:L().url().optional(),scopes_supported:ue(L()).optional(),bearer_methods_supported:ue(L()).optional(),resource_signing_alg_values_supported:ue(L()).optional(),resource_name:L().optional(),resource_documentation:L().optional(),resource_policy_uri:L().url().optional(),resource_tos_uri:L().url().optional(),tls_client_certificate_bound_access_tokens:yt().optional(),authorization_details_types_supported:ue(L()).optional(),dpop_signing_alg_values_supported:ue(L()).optional(),dpop_bound_access_tokens_required:yt().optional()}).passthrough(),Dm=te({issuer:L(),authorization_endpoint:Ut,token_endpoint:Ut,registration_endpoint:Ut.optional(),scopes_supported:ue(L()).optional(),response_types_supported:ue(L()),response_modes_supported:ue(L()).optional(),grant_types_supported:ue(L()).optional(),token_endpoint_auth_methods_supported:ue(L()).optional(),token_endpoint_auth_signing_alg_values_supported:ue(L()).optional(),service_documentation:Ut.optional(),revocation_endpoint:Ut.optional(),revocation_endpoint_auth_methods_supported:ue(L()).optional(),revocation_endpoint_auth_signing_alg_values_supported:ue(L()).optional(),introspection_endpoint:L().optional(),introspection_endpoint_auth_methods_supported:ue(L()).optional(),introspection_endpoint_auth_signing_alg_values_supported:ue(L()).optional(),code_challenge_methods_supported:ue(L()).optional()}).passthrough(),cI=te({issuer:L(),authorization_endpoint:Ut,token_endpoint:Ut,userinfo_endpoint:Ut.optional(),jwks_uri:Ut,registration_endpoint:Ut.optional(),scopes_supported:ue(L()).optional(),response_types_supported:ue(L()),response_modes_supported:ue(L()).optional(),grant_types_supported:ue(L()).optional(),acr_values_supported:ue(L()).optional(),subject_types_supported:ue(L()),id_token_signing_alg_values_supported:ue(L()),id_token_encryption_alg_values_supported:ue(L()).optional(),id_token_encryption_enc_values_supported:ue(L()).optional(),userinfo_signing_alg_values_supported:ue(L()).optional(),userinfo_encryption_alg_values_supported:ue(L()).optional(),userinfo_encryption_enc_values_supported:ue(L()).optional(),request_object_signing_alg_values_supported:ue(L()).optional(),request_object_encryption_alg_values_supported:ue(L()).optional(),request_object_encryption_enc_values_supported:ue(L()).optional(),token_endpoint_auth_methods_supported:ue(L()).optional(),token_endpoint_auth_signing_alg_values_supported:ue(L()).optional(),display_values_supported:ue(L()).optional(),claim_types_supported:ue(L()).optional(),claims_supported:ue(L()).optional(),service_documentation:L().optional(),claims_locales_supported:ue(L()).optional(),ui_locales_supported:ue(L()).optional(),claims_parameter_supported:yt().optional(),request_parameter_supported:yt().optional(),request_uri_parameter_supported:yt().optional(),require_request_uri_registration:yt().optional(),op_policy_uri:Ut.optional(),op_tos_uri:Ut.optional()}).passthrough().merge(Dm.pick({code_challenge_methods_supported:!0})),Lm=te({access_token:L(),id_token:L().optional(),token_type:L(),expires_in:St().optional(),scope:L().optional(),refresh_token:L().optional()}).strip(),uI=te({error:L(),error_description:L().optional(),error_uri:L().optional()}),zm=Ut.optional().or(Ie("").transform(()=>{})),dI=te({redirect_uris:ue(Ut),token_endpoint_auth_method:L().optional(),grant_types:ue(L()).optional(),response_types:ue(L()).optional(),client_name:L().optional(),client_uri:Ut.optional(),logo_uri:zm,scope:L().optional(),contacts:ue(L()).optional(),tos_uri:zm,policy_uri:L().optional(),jwks_uri:Ut.optional(),jwks:nh().optional(),software_id:L().optional(),software_version:L().optional(),software_statement:L().optional()}).strip(),pI=te({client_id:L(),client_secret:L().optional(),client_id_issued_at:St().optional(),client_secret_expires_at:St().optional()}).strip(),fI=dI.merge(pI);te({error:L(),error_description:L().optional()}).strip(),te({token:L(),token_type_hint:L().optional()}).strip();function hI(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function mI({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),a=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==a.origin||r.pathname.length<a.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return n.startsWith(s)}class qt extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Lu extends qt{}Lu.errorCode="invalid_request";class Ni extends qt{}Ni.errorCode="invalid_client";class Ai extends qt{}Ai.errorCode="invalid_grant";class Mi extends qt{}Mi.errorCode="unauthorized_client";class zu extends qt{}zu.errorCode="unsupported_grant_type";class Uu extends qt{}Uu.errorCode="invalid_scope";class qu extends qt{}qu.errorCode="access_denied";class Za extends qt{}Za.errorCode="server_error";class Fu extends qt{}Fu.errorCode="temporarily_unavailable";class Zu extends qt{}Zu.errorCode="unsupported_response_type";class Vu extends qt{}Vu.errorCode="unsupported_token_type";class Hu extends qt{}Hu.errorCode="invalid_token";class Bu extends qt{}Bu.errorCode="method_not_allowed";class Ju extends qt{}Ju.errorCode="too_many_requests";class Gu extends qt{}Gu.errorCode="invalid_client_metadata";class Ku extends qt{}Ku.errorCode="insufficient_scope";const vI={[Lu.errorCode]:Lu,[Ni.errorCode]:Ni,[Ai.errorCode]:Ai,[Mi.errorCode]:Mi,[zu.errorCode]:zu,[Uu.errorCode]:Uu,[qu.errorCode]:qu,[Za.errorCode]:Za,[Fu.errorCode]:Fu,[Zu.errorCode]:Zu,[Vu.errorCode]:Vu,[Hu.errorCode]:Hu,[Bu.errorCode]:Bu,[Ju.errorCode]:Ju,[Gu.errorCode]:Gu,[Ku.errorCode]:Ku};class Or extends Error{constructor(e){super(e??"Unauthorized")}}const Wu="code",Qu="S256";function Um(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function qm(t,e,r,a){const{client_id:n,client_secret:s}=e;switch(t){case"client_secret_basic":gI(n,s,r);return;case"client_secret_post":yI(n,s,a);return;case"none":_I(n,a);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function gI(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const a=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${a}`)}function yI(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function _I(t,e){e.set("client_id",t)}async function Yu(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const a=uI.parse(JSON.parse(r)),{error:n,error_description:s,error_uri:o}=a,i=vI[n]||Za;return new i(s||"",o)}catch(a){const n=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${a}. Raw body: ${r}`;return new Za(n)}}async function Va(t,e){var r,a;try{return await Xu(t,e)}catch(n){if(n instanceof Ni||n instanceof Mi)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await Xu(t,e);if(n instanceof Ai)return await((a=t.invalidateCredentials)===null||a===void 0?void 0:a.call(t,"tokens")),await Xu(t,e);throw n}}async function Xu(t,{serverUrl:e,authorizationCode:r,scope:a,resourceMetadataUrl:n,fetchFn:s}){let o,i;try{o=await bI(e,{resourceMetadataUrl:n},s),o.authorization_servers&&o.authorization_servers.length>0&&(i=o.authorization_servers[0])}catch{}i||(i=e);const l=await wI(e,t,o),c=await kI(i,{fetchFn:s});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const v=await CI(i,{metadata:c,clientMetadata:t.clientMetadata,fetchFn:s});await t.saveClientInformation(v),u=v}if(r!==void 0){const v=await t.codeVerifier(),m=await xI(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:t.redirectUrl,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(m),"AUTHORIZED"}const f=await t.tokens();if(f!=null&&f.refresh_token)try{const v=await TI(i,{metadata:c,clientInformation:u,refreshToken:f.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof qt)||v instanceof Za))throw v}const g=t.state?await t.state():void 0,{authorizationUrl:d,codeVerifier:h}=await II(i,{metadata:c,clientInformation:u,state:g,redirectUrl:t.redirectUrl,scope:a||t.clientMetadata.scope,resource:l});return await t.saveCodeVerifier(h),await t.redirectToAuthorization(d),"REDIRECT"}async function wI(t,e,r){const a=hI(t);if(e.validateResourceURL)return await e.validateResourceURL(a,r==null?void 0:r.resource);if(r){if(!mI({requestedResource:a,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function ed(t){const e=t.headers.get("WWW-Authenticate");if(!e)return;const[r,a]=e.split(" ");if(r.toLowerCase()!=="bearer"||!a)return;const s=/resource_metadata="([^"]*)"/.exec(e);if(s)try{return new URL(s[1])}catch{return}}async function bI(t,e,r=fetch){const a=await $I(t,"oauth-protected-resource",r,{protocolVersion:e==null?void 0:e.protocolVersion,metadataUrl:e==null?void 0:e.resourceMetadataUrl});if(!a||a.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return lI.parse(await a.json())}async function td(t,e,r=fetch){try{return await r(t,{headers:e})}catch(a){if(a instanceof TypeError)return e?td(t,void 0,r):void 0;throw a}}function EI(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Fm(t,e,r=fetch){return await td(t,{"MCP-Protocol-Version":e},r)}function SI(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function $I(t,e,r,a){var n,s;const o=new URL(t),i=(n=a==null?void 0:a.protocolVersion)!==null&&n!==void 0?n:js;let l;if(a!=null&&a.metadataUrl)l=new URL(a.metadataUrl);else{const u=EI(e,o.pathname);l=new URL(u,(s=a==null?void 0:a.metadataServerUrl)!==null&&s!==void 0?s:o),l.search=o.search}let c=await Fm(l,i,r);if(!(a!=null&&a.metadataUrl)&&SI(c,o.pathname)){const u=new URL(`/.well-known/${e}`,o);c=await Fm(u,i,r)}return c}function PI(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",a=[];if(!r)return a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),a;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),a.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),a}async function kI(t,{fetchFn:e=fetch,protocolVersion:r=js}={}){const a={"MCP-Protocol-Version":r,Accept:"application/json"},n=PI(t);for(const{url:s,type:o}of n){const i=await td(s,a,e);if(i){if(!i.ok){if(i.status>=400&&i.status<500)continue;throw new Error(`HTTP ${i.status} trying to load ${o==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return o==="oauth"?Dm.parse(await i.json()):cI.parse(await i.json())}}}async function II(t,{metadata:e,clientInformation:r,redirectUrl:a,scope:n,state:s,resource:o}){let i;if(e){if(i=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Wu))throw new Error(`Incompatible auth server: does not support response type ${Wu}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Qu))throw new Error(`Incompatible auth server: does not support code challenge method ${Qu}`)}else i=new URL("/authorize",t);const l=await iI(),c=l.code_verifier,u=l.code_challenge;return i.searchParams.set("response_type",Wu),i.searchParams.set("client_id",r.client_id),i.searchParams.set("code_challenge",u),i.searchParams.set("code_challenge_method",Qu),i.searchParams.set("redirect_uri",String(a)),s&&i.searchParams.set("state",s),n&&i.searchParams.set("scope",n),n!=null&&n.includes("offline_access")&&i.searchParams.append("prompt","consent"),o&&i.searchParams.set("resource",o.href),{authorizationUrl:i,codeVerifier:c}}async function xI(t,{metadata:e,clientInformation:r,authorizationCode:a,codeVerifier:n,redirectUri:s,resource:o,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",f=e!=null&&e.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e!=null&&e.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const g=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:a,code_verifier:n,redirect_uri:String(s)});if(i)i(g,d,t,e);else{const v=(c=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&c!==void 0?c:[],m=Um(r,v);qm(m,r,g,d)}o&&d.set("resource",o.href);const h=await(l??fetch)(f,{method:"POST",headers:g,body:d});if(!h.ok)throw await Yu(h);return Lm.parse(await h.json())}async function TI(t,{metadata:e,clientInformation:r,refreshToken:a,resource:n,addClientAuthentication:s,fetchFn:o}){var i;const l="refresh_token";let c;if(e){if(c=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",t);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),f=new URLSearchParams({grant_type:l,refresh_token:a});if(s)s(u,f,t,e);else{const d=(i=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],h=Um(r,d);qm(h,r,u,f)}n&&f.set("resource",n.href);const g=await(o??fetch)(c,{method:"POST",headers:u,body:f});if(!g.ok)throw await Yu(g);return Lm.parse({refresh_token:a,...await g.json()})}async function CI(t,{metadata:e,clientMetadata:r,fetchFn:a}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);const s=await(a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Yu(s);return fI.parse(await s.json())}class RI extends Error{constructor(e,r,a){super(`SSE error: ${r}`),this.code=e,this.event=a}}class Bs{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r==null?void 0:r.eventSourceInit,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Or("No auth provider");let r;try{r=await Va(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Or;return await this._startOrAuth()}async _commonHeaders(){var e;const r={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(r.Authorization=`Bearer ${a.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,a;const n=(a=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&a!==void 0?a:fetch;return new Promise((s,o)=>{this._eventSource=new Oi(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await n(i,{...l,headers:c});return u.status===401&&u.headers.has("www-authenticate")&&(this._resourceMetadataUrl=ed(u)),u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(s,o);return}const c=new RI(i.code,i.message,i);o(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const c=i;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){o(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}s()}),this._eventSource.onmessage=i=>{var l,c;const u=i;let f;try{f=gn.parse(JSON.parse(u.data))}catch(g){(l=this.onerror)===null||l===void 0||l.call(this,g);return}(c=this.onmessage)===null||c===void 0||c.call(this,f)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Or("No auth provider");if(await Va(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Or("Failed to authorize")}async close(){var e,r,a;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var r,a,n;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},i=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,o);if(!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=ed(i),await Va(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Or;return this.send(e)}const l=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${l}`)}}catch(s){throw(n=this.onerror)===null||n===void 0||n.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}}class rd extends TransformStream{constructor({onError:e,onRetry:r,onComment:a}={}){let n;super({start(s){n=Om({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:a})},transform(s){n.feed(s)}})}}const OI={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class ji extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class Js{constructor(e,r){var a;this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch,this._sessionId=r==null?void 0:r.sessionId,this._reconnectionOptions=(a=r==null?void 0:r.reconnectionOptions)!==null&&a!==void 0?a:OI}async _authThenStart(){var e;if(!this._authProvider)throw new Or("No auth provider");let r;try{r=await Va(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Or;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const a=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...a})}async _startOrAuthSse(e){var r,a,n;const{resumptionToken:s}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),s&&o.set("last-event-id",s);const i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:o,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new ji(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(o){throw(n=this.onerror)===null||n===void 0||n.call(this,o),o}}_getNextReconnectionDelay(e){const r=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(a,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var a;const n=this._reconnectionOptions.maxRetries;if(n>0&&r>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,a){if(!e)return;const{onresumptiontoken:n,replayMessageId:s}=r;let o;(async()=>{var l,c,u,f;try{const g=e.pipeThrough(new TextDecoderStream).pipeThrough(new rd).getReader();for(;;){const{value:d,done:h}=await g.read();if(h)break;if(d.id&&(o=d.id,n==null||n(d.id)),!d.event||d.event==="message")try{const v=gn.parse(JSON.parse(d.data));s!==void 0&&Zc(v)&&(v.id=s),(l=this.onmessage)===null||l===void 0||l.call(this,v)}catch(v){(c=this.onerror)===null||c===void 0||c.call(this,v)}}}catch(g){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${g}`)),a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:n,replayMessageId:s},0)}catch(d){(f=this.onerror)===null||f===void 0||f.call(this,new Error(`Failed to reconnect: ${d instanceof Error?d.message:String(d)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Or("No auth provider");if(await Va(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Or("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var a,n,s,o;try{const{resumptionToken:i,onresumptiontoken:l}=r||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:dh(e)?e.id:void 0}).catch(m=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,m)});return}const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const u={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},f=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,u),g=f.headers.get("mcp-session-id");if(g&&(this._sessionId=g),!f.ok){if(f.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new ji(401,"Server returned 401 after successful authentication");if(this._resourceMetadataUrl=ed(f),await Va(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Or;return this._hasCompletedAuthFlow=!0,this.send(e)}const m=await f.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${f.status}): ${m}`)}if(this._hasCompletedAuthFlow=!1,f.status===202){E$(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,m)});return}const h=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,v=f.headers.get("content-type");if(h)if(v!=null&&v.includes("text/event-stream"))this._handleSseStream(f.body,{onresumptiontoken:l},!1);else if(v!=null&&v.includes("application/json")){const m=await f.json(),p=Array.isArray(m)?m.map(_=>gn.parse(_)):[gn.parse(m)];for(const _ of p)(s=this.onmessage)===null||s===void 0||s.call(this,_)}else throw new ji(-1,`Unexpected content type: ${v}`)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,a;if(this._sessionId)try{const n=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},o=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!o.ok&&o.status!==405)throw new ji(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(n){throw(a=this.onerror)===null||a===void 0||a.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}const NI="mcp";class Zm{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,NI),this._socket.onerror=a=>{var n;const s="error"in a?a.error:new Error(`WebSocket error: ${JSON.stringify(a)}`);r(s),(n=this.onerror)===null||n===void 0||n.call(this,s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var a;(a=this.onclose)===null||a===void 0||a.call(this)},this._socket.onmessage=a=>{var n,s;let o;try{o=gn.parse(JSON.parse(a.data))}catch(i){(n=this.onerror)===null||n===void 0||n.call(this,i);return}(s=this.onmessage)===null||s===void 0||s.call(this,o)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((r,a)=>{var n;if(!this._socket){a(new Error("Not connected"));return}(n=this._socket)===null||n===void 0||n.send(JSON.stringify(e)),r()})}}function Di(){const t=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return Di=function(){return t},Di()}(function(t,e){const r=$t,a=$t,n=t();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(a(429))/5)+parseInt(a(423))/6*(-parseInt(a(418))/7)+-parseInt(a(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Di,650197);const Vm=()=>{const t=$t,e={EGhzU:function(r,a){return r!==a},kIrDB:"undefined",llYQe:function(r,a){return r!==a},PZfJg:function(r,a){return r(a)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:e[t(407)](typeof window,e.kIrDB)?window:e.llYQe(typeof global,e.kIrDB)?global:typeof self!==t(398)?self:e.PZfJg(Function,e[t(399)])()},AI=(t,e,r)=>{const a=$t,n=$t,s={};s[a(410)]=n(398),s.dBkaX=function(i,l){return i===l},s[n(393)]="function";const o=s;typeof window!==o[n(410)]?t.postMessage(e,"*",r):n(428)in t&&o.dBkaX(typeof t.postMessage,o[a(393)])&&t.postMessage(e,r)},MI=(t,e)=>{const r=$t,a=$t,n={};n.MbsGh="addEventListener",n.PPniK=function(o,i){return o===i},n[r(419)]=a(412),n[a(404)]="onmessage",n[r(397)]="undefined";const s=n;s.MbsGh in t&&s.PPniK(typeof t[r(427)],s.wRKyh)?t[r(427)](r(400),e):s.thraG in t&&typeof t[a(413)]!==s[a(397)]&&(t.onmessage=e)};class Li{constructor(e){const r=$t;this[r(406)]=e}async start(){const e=$t,r=$t;this[e(406)]&&(this[e(406)][e(413)]=a=>{var n,s;const o=e,i=r;try{const l=gn[o(402)](a.data[o(400)]);(n=this[o(413)])==null||n.call(this,l,a[i(409)].extra)}catch(l){const c=new Error("MessageChannel failed to parse message: "+l);(s=this[i(408)])==null||s.call(this,c)}},this._port[e(396)]=a=>{var n;const s=r,o=r,i=new Error(s(394)+JSON[o(395)](a));(n=this.onerror)==null||n.call(this,i)},this[e(406)][e(434)]())}async send(e,r){const a={lEyuq:function(n){return n()},YihNw:function(n,s){return n(s)}};return new Promise((n,s)=>{var o;const i=$t,l=$t;try{const c={};c[i(403)]=r==null?void 0:r[i(403)];const u={};u[l(400)]=e,u.extra=c,this[l(406)]&&this[i(406)].postMessage(u),a.lEyuq(n)}catch(c){const u=c instanceof Error?c:new Error(a.YihNw(String,c));(o=this[l(408)])==null||o.call(this,u),s(u)}})}async close(){var e,r;const a=$t,n=$t;(e=this._port)==null||e[a(431)](),this._port=void 0,(r=this[n(420)])==null||r.call(this)}}class nd extends Li{constructor(e,r=Vm()){const a=$t,n=$t,s={EkZCC:function(i,l,c,u){return i(l,c,u)}};super(),this[a(391)]=e,this[n(401)]=r;const o=new MessageChannel;this[n(406)]=o.port1,s[n(426)](AI,this[a(401)],{endpoint:this[n(391)]},[o[n(414)]])}}class ad extends Li{constructor(e,r=Vm()){const a=$t,n={mOWMr:function(s,o){return s===o},kgkem:function(s,o,i){return s(o,i)}};super(),this._endpoint=e,this._globalObject=r,this[a(432)]=new Promise(s=>{const o=a,i=a;n[o(392)](MI,this[i(401)],l=>{const c=i,u=i;l.data&&n[c(425)](l.data[u(422)],this[u(391)])&&(this[u(406)]=l.ports[-1*4852+1*1601+3251],s())})})}async listen(){return this[$t(432)]}}function $t(t,e){const r=Di();return $t=function(a,n){return a=a-(17*-491+-669+9407),r[a]},$t(t,e)}const jI=()=>{const t=new MessageChannel;return[new Li(t.port1),new Li(t.port2)]};(function(t,e){const r=Xe,a=Xe,n=t();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(a(357))/5+-parseInt(a(389))/6*(-parseInt(r(396))/7)+parseInt(a(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(zi,-763475+-52067*10+1724410);const DI=async(t,e,r)=>{var a;const n=Xe,s=Xe,o={};o[n(345)]="tools/list",o.rqstG="tools/call",o.WqUnk="resources/list",o[n(329)]=s(358),o[n(365)]=n(335),o.ookoz="resources/unsubscribe",o[n(385)]=n(340),o.VTIWq="prompts/list",o.SkoRK=n(376),o.QUtUV=n(388),o.XtowM=s(332);const i=o,{id:l,method:c,params:u}=r;let f={};switch(c){case i[s(345)]:f=await e.listTools(u);break;case i.rqstG:f=await e.callTool(u);break;case i[n(334)]:f=await e[n(350)](u);break;case i[s(329)]:f=await e.listResourceTemplates(u);break;case n(372):f=await e[n(383)](u);break;case i.HgYgW:f=await e.subscribeResource(u);break;case i.ookoz:f=await e.unsubscribeResource(u);break;case i[n(385)]:f=await e.getPrompt(u);break;case i.VTIWq:f=await e.listPrompts(u);break;case i[n(344)]:f=await e[n(376)]();break;case i.QUtUV:f=await e.complete(u);break;case n(390):f=await e[n(336)](u==null?void 0:u.level);break}const g={};g[n(361)]=f,g[n(394)]=i[n(364)],g.id=l,await((a=t==null?void 0:t.transport)==null?void 0:a[n(392)](g))},LI=async(t,e,r)=>{var a;const n=Xe,s=Xe,o={};o.jQBBS="sampling/createMessage",o.EZqgC="elicitation/create",o[n(370)]=s(376),o.aVeaL=s(332);const i=o,{id:l,method:c,params:u}=r;let f={};switch(c){case n(368):const d={};d.method=c,d[s(367)]=u,f=await e.request(d,iu);break;case i[s(391)]:const h={};h.method=c,h[s(367)]=u,f=await e[s(381)](h,au);break;case i.EZqgC:const v={};v.method=c,v.params=u,f=await e.request(v,su);break;case i[s(370)]:const m={};m.method=c,f=await e[s(381)](m,Tn);break}const g={};return g[s(361)]=f,g.jsonrpc=i[s(387)],g.id=l,await((a=t==null?void 0:t[n(371)])==null?void 0:a.send(g)),f},zI=(t,e)=>{const r=Xe,a={gXsjT:function(s,o){return s===o},oegpC:r(351),lZOUC:function(s,o,i,l){return s(o,i,l)},ifIKG:"2.0"},n=t._onrequest;t._onrequest=async(s,o)=>{var i,l,c,u,f;const g=r,d=r,{id:h,method:v}=s;try{a[g(333)](v,a.oegpC)?await n[g(386)](t,s,o):await a.lZOUC(DI,t,e,s)}catch(m){const{code:p,message:_,data:w}=m;try{if(p){const b={};b.code=p,b.message=_,b.data=w;const S={};S.error=b,S[g(394)]=a[d(331)],S.id=h,await((i=t==null?void 0:t.transport)==null?void 0:i.send(S))}else(c=(l=t==null?void 0:t[d(371)])==null?void 0:l.onerror)==null||c.call(l,m)}catch(b){(f=(u=t==null?void 0:t[g(371)])==null?void 0:u.onerror)==null||f.call(u,b)}}}},UI=(t,e)=>{const r=Xe,a=Xe,n={};n[r(363)]=function(o,i){return o!==i},n[r(398)]=r(353),n.hzhyg="notifications/cancelled";const s=n;t._onnotification=async o=>{var i,l;const c=r,u=a,{method:f,params:g}=o;if(s[c(363)](f,s[u(398)])&&(s[c(363)](f,s.hzhyg)||g!=null&&g.forward))try{await e.notification(o)}catch(d){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,d)}}},qI=(t,e)=>async r=>{var a,n,s,o,i;const l=Xe,c=Xe,u={};u.SEmWX=l(332);const f=u;try{return await LI(t,e,r)}catch(g){const{code:d,message:h,data:v}=g;try{if(d){const m={};m[c(377)]=d,m.message=h,m.data=v;const p={};p[c(348)]=m,p.jsonrpc=f[l(338)],p.id=r.id,await((a=t==null?void 0:t.transport)==null?void 0:a[c(392)](p))}else(s=(n=t==null?void 0:t.transport)==null?void 0:n[c(339)])==null||s.call(n,g)}catch(m){(i=(o=t==null?void 0:t[l(371)])==null?void 0:o[c(339)])==null||i.call(o,m)}}},FI=(t,e)=>async r=>{var a,n,s;const o=Xe,i=Xe,l={};l.dtUgZ=function(g,d){return g!==d},l.jgCIb=o(353),l.uUjKY="2.0";const c=l,{method:u,params:f}=r;if(c.dtUgZ(u,c.jgCIb)&&(u!==o(400)||f!=null&&f.forward))try{const g={...r};g[o(394)]=c[i(352)],await((a=e==null?void 0:e[o(371)])==null?void 0:a[o(392)](g))}catch(g){(s=(n=t==null?void 0:t[o(371)])==null?void 0:n[i(339)])==null||s.call(n,g)}};function Xe(t,e){const r=zi();return Xe=function(a,n){return a=a-(9*-113+-1439*-1+-97),r[a]},Xe(t,e)}const ZI=(t,e)=>async r=>{var a,n,s,o,i,l;const c=Xe,u=Xe,f={};f[c(401)]=u(332);const g=f;try{await((a=e==null?void 0:e.transport)==null?void 0:a.send(r))}catch(d){const{code:h,message:v,data:m}=d;try{if(h){const p={};p.code=h,p[c(399)]=v,p.data=m;const _={};_[c(348)]=p,_[c(394)]=g.OhJjz,_.id=r.id,await((n=t==null?void 0:t[c(371)])==null?void 0:n.send(_))}else(o=(s=t==null?void 0:t.transport)==null?void 0:s[u(339)])==null||o.call(s,d)}catch(p){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,p)}}},sd=()=>{const t=Xe,e=Xe,r={vnkqu:function(c,u){return c!==u},wxDWr:function(c,u){return c(u)},GdkkV:function(c,u){return c===u}},a=[],n=(c,u)=>{const f=Xe,g=Xe;if(u){const d=[];for(const h of a)try{d.push(h(c,u))}catch{}for(const h of d)if(r[f(379)](h,null))return h}else for(const d of a)try{r[g(343)](d,c)}catch{}},s=c=>{const u=Xe;r[u(384)](typeof c,u(369))&&!a.includes(c)&&a.push(c)},o=c=>{const u=a.indexOf(c);u!==-1&&a.splice(u,1*-6854+8*-33+7119)},i=()=>{const c=Xe;a[c(374)]=7102*1+5522+-526*24},l={};return l[t(346)]=n,l[e(330)]=s,l.removeListener=o,l[t(359)]=i,l},VI=t=>{const e=Xe,r=Xe,a={xwPeb:function(n){return n()},Mfvzm:function(n){return n()}};{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(326)](sd);t._onresponse=n,t[e(395)]=s,t.removeResponseListener=o,t.clearResponseListener=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[r(326)](sd);t[r(328)]=n,t.addRequestListener=s,t[r(354)]=o,t[r(341)]=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(375)](sd);t[e(342)]=n,t[e(327)]=s,t.removeNotificationListener=o,t.clearNotificationListener=i}};function zi(){const t=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return zi=function(){return t},zi()}const HI=(t,{beforeInit:e,afterInit:r}={})=>{const a=Xe,n=Xe,s={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:a(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},o=new Map(t._notificationHandlers);t[a(393)][a(402)](),t._notificationHandlers[a(402)](),s.tqDZP(typeof e,s[a(380)])&&e(),s[a(362)](t._onresponse.name,s[a(360)])&&(t[n(349)]=t._onresponse),s[a(347)](VI,t),t.addResponseListener(i=>{const l=n;t.originalOnResponse[l(386)](t,i)}),s.tqDZP(typeof r,s[n(380)])&&s[a(397)](r),t[n(327)](i=>{const{method:l}=i,c=o.get(l);s.tqDZP(typeof c,s.cjSoZ)&&c(i)})},BI=Yr,JI=Yr;(function(t,e){const r=Yr,a=Yr,n=t();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(a(398))/4+parseInt(r(390))/5*(parseInt(a(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(a(395))/9)+parseInt(a(399))/10*(parseInt(a(385))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ui,-1*-881393+2*180895+1*-644809);function Yr(t,e){const r=Ui();return Yr=function(a,n){return a=a-(-1861+-499*4+4241),r[a]},Yr(t,e)}function Ui(){const t=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return Ui=function(){return t},Ui()}const GI=()=>{const t=Yr,e=Yr,r={};r.REzPF=function(n,s){return n&s},r.suJHI=function(n,s){return n===s},r[t(386)]=function(n,s){return n&s},r[e(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const a=r;return a.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[e(391)]():a.dHTfU.replace(/[xy]/g,n=>{const s=t,o=t,i=a[s(392)](crypto[s(384)](new Uint8Array(-25*-62+7113+2*-4331))[741*2+-1385*-2+4252*-1],8648+-107*62+-1999);return(a.suJHI(n,"x")?i:a[o(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},KI=t=>{const e=Yr,r=Yr,a=new Uint8Array(t);return crypto.getRandomValues(a),Array[e(401)](a,n=>n[r(403)](-3*1739+-6509+2*5871)[e(387)](2,"0")).join("")},An={};An[BI(391)]=GI,An[JI(396)]=KI;const dr=Xr;(function(t,e){const r=Xr,a=Xr,n=t();for(;;)try{if(parseInt(r(521))/1*(parseInt(a(499))/2)+parseInt(a(543))/3*(parseInt(a(514))/4)+parseInt(r(502))/5*(parseInt(a(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(qi,1472653*1+-2*-897917+-2275789);const WI=(t,e)=>{const r=Xr,a=Xr,n={FyYHt:function(l,c,u){return l(c,u)},Fxtoq:function(l,c,u){return l(c,u)}};zI(t,e),UI(t,e);const s=qI(e,t),o=n[r(510)](ZI,e,t),i=n[a(549)](FI,e,t);e[a(537)](s),e[r(519)](o),e.addNotificationListener(i),t[a(556)]=()=>{const l=a;e.removeRequestListener(s),e[l(530)](o),e[l(529)](i)}},od=(t,e,r)=>{const a=Xr,n={pMiva:function(i,l){return i instanceof l},TeTEy:a(546),fyZbd:function(i,l,c){return i(l,c)}},s=()=>{var i;const l=a;n.pMiva(r,Bs)&&((i=r._eventSource)==null||i.addEventListener(n[l(547)],()=>{var c;const u=l;(c=r[u(509)])==null||c[u(546)]()})),WI(t,e)},o={};o.afterInit=s,n.fyZbd(HI,e,o)},Hm=(t,e=An.randomUUID())=>{const r=Xr,a=Xr,n={OfssH:function(u,f,g){return u(f,g)}},s={};s[r(528)]=e;const o=s,i={};i[r(528)]=e;const l={};l[a(558)]=i,l[r(534)]=r(524);const c={requestInit:l,eventSourceInit:{async fetch(u,f){const g=r,d=a,h=new Headers((f==null?void 0:f[g(558)])||{});Object.entries(o)[d(498)](([m,p])=>{h[d(527)](m,p)});const v={...f};return v[d(558)]=h,n.OfssH(fetch,u,v)},withCredentials:!0}};return t&&(c.requestInit[r(558)].Authorization=r(533)+t,o.Authorization="Bearer "+t),c},Bm=(t,e=An[dr(517)]())=>{const r=dr,a=dr,n={};n.nwQhY="include";const s=n,o={};o["stream-session-id"]=e;const i={};i.headers=o,i.credentials=s[r(520)];const l={};l[r(544)]=i;const c=l;return t&&(c.requestInit.headers[a(552)]=a(533)+t),c},id=async(t,e,r)=>{const a=dr,n=dr,s={CFfFC:function(i){return i()},egwVO:function(i,l,c,u){return i(l,c,u)}},o=s.CFfFC(r);try{return await t[a(538)](o),o}catch(i){if(i instanceof Or){const l=await e();return await o[n(505)](l),await s[a(525)](id,t,e,r)}else throw i}};function Xr(t,e){const r=qi();return Xr=function(a,n){return a=a-(74*-67+-8341+-73*-189),r[a]},Xr(t,e)}const Jm=(t,e)=>{const r=dr,a=dr,n={};n.RsKXs=function(o,i){return o in i},n.PBhps="waitForOAuthCode",n[r(535)]="function",n[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=n;if(s.RsKXs(s[a(551)],t))return t[a(523)];if(typeof e===s.yTKoP)return e;throw new Error(s.RZhOv)},QI=async t=>{const e=dr,r=dr,a={TFSRn:function(O,H,J){return O(H,J)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(O){return O()},WIVYl:function(O,H,J,K){return O(H,J,K)},jniGY:"sessionId"},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:f}=t,g={};g.authProvider=l,g.requestInit=c,g.eventSourceInit=u;const d=g,h=i||An.randomUUID(),v=a[e(506)](Hm,o,h);if(c){const O={...v.requestInit,...c};O.headers={...v[e(544)].headers,...c.headers},d.requestInit=O}else d[r(544)]=v.requestInit;if(u){const O={...v[e(559)],...u};d.eventSourceInit=O}else d.eventSourceInit=v.eventSourceInit;const m={};m.listChanged=!0;const p={};p.roots=m,p.sampling={},p[e(511)]={};const _=p,w={};w[r(536)]=a.HwvVa,w.version=e(526);const b={};b.capabilities=_;const S=new qs(w,b),I=()=>new Bs(new URL(s),d);let k=a[r(504)](I);if(l){const O=a[e(506)](Jm,l,f);k=await a[r(513)](id,S,O,I)}else await S[e(538)](k);a[r(513)](od,S,n,k),k[r(557)]=k[r(542)].searchParams[r(532)](a.jniGY);const A={};return A.transport=k,A.sessionId=k[e(557)],A};function qi(){const t=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return qi=function(){return t},qi()}const YI=async t=>{const e=dr,r=dr,a={Vajmx:e(500),biJOc:function(O){return O()},zXcpO:function(O,H,J){return O(H,J)},zDnjZ:function(O,H,J,K){return O(H,J,K)},FQMAh:function(O,H,J,K){return O(H,J,K)}},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:f}=t,g={};g.authProvider=l,g.requestInit=c,g.reconnectionOptions=u;const d=g,h=i||An.randomUUID(),v=Bm(o,h);if(c){const O={...v.requestInit,...c};O.headers={...v.requestInit.headers,...c.headers},d[e(544)]=O}else d.requestInit=v.requestInit;const m={};m.listChanged=!0;const p={};p[r(550)]=m,p.sampling={},p.elicitation={};const _=p,w={};w[e(536)]=a[r(508)],w[e(555)]="1.0.0";const b={};b.capabilities=_;const S=new qs(w,b),I=()=>new Js(new URL(s),d);let k=a[e(503)](I);if(l){const O=a[e(501)](Jm,l,f);k=await a.zDnjZ(id,S,O,I)}else await S.connect(k);a.FQMAh(od,S,n,k);const A={};return A.transport=k,A[r(557)]=k.sessionId,A},XI=async t=>{const e=dr,r=dr,a={QgzDy:e(540),jkaVB:function(p,_,w,b){return p(_,w,b)}},{client:n,url:s,token:o,sessionId:i}=t,l={};l.listChanged=!0;const c={};c[e(550)]=l,c[e(515)]={},c[r(511)]={};const u=c,f={};f.name=a[r(548)],f[r(555)]=r(526);const g={};g.capabilities=u;const d=new qs(f,g),h=i||An[r(517)](),v=new Zm(new URL(s+e(522)+h+r(554)+o));await d.connect(v),a.jkaVB(od,d,n,v);const m={};return m[e(512)]=v,m[r(557)]=h,m},Gs=tr,Fi=tr;function tr(t,e){const r=Zi();return tr=function(a,n){return a=a-(-16761+51*337),r[a]},tr(t,e)}(function(t,e){const r=tr,a=tr,n=t();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(a(449))/5)+-parseInt(a(455))/6+-parseInt(r(427))/7+-parseInt(a(438))/8*(parseInt(a(459))/9)+parseInt(r(430))/10*(parseInt(a(436))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Zi,-220880+1*-333337+-2*-384996);function Zi(){const t=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return Zi=function(){return t},Zi()}const ex=()=>An.randomBytes(3485*1+-261+-3184);class tx{constructor(e){const r=tr,a=tr;this._callBackPromise={};const{clientMetadata:n,state:s,redirectCallback:o,getAuthCodeByState:i,waitForOAuthCode:l}=e;this[r(428)]=n,this[r(454)]=n[r(445)][0],this._state=s||ex(),this._redirectCallback=o||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[a(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,a,n,s,o,i;const l=tr,c=tr,u={qITTp:function(h,v,m){return h(v,m)},qcFPW:l(452)},f=await u.qITTp(fetch,e,{method:u[l(453)]});!f.ok&&((a=(r=this._callBackPromise).reject)==null||a.call(r,c(446)+f.statusText));const g=await this._getAuthCodeByState(this[c(454)],this[l(442)]);if(!g.ok){(s=(n=this[l(433)]).reject)==null||s.call(n,"Failed to fetch auth code: "+g.statusText);return}const d=await g[l(431)]();(i=(o=this[c(433)])[l(456)])==null||i.call(o,d[l(432)])}async getAuthCodeByStateFunction(e,r){const a=tr,n=tr,s={};s.tuSmb=a(429);const o=s,i={};i[a(460)]=o.tuSmb;const l={};return l[n(441)]=r,fetch(e,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const e=tr,r=this[e(433)];return()=>new Promise((a,n)=>{const s=e;r.resolve=a,r[s(434)]=n})}get redirectUrl(){return this[tr(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[Gs(447)](){return this[Gs(444)]}[Fi(435)](e){const r=Gs;this[r(444)]=e}[Fi(457)](){return this[Fi(439)]}saveTokens(e){this._tokens=e}[Fi(450)](e){this[Gs(443)](e)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this[Gs(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(t,e){for(var r=Hi,a=Hi,n=t();;)try{var s=parseInt(r(361))/1*(parseInt(a(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(a(354))/6*(parseInt(r(360))/7)+parseInt(a(362))/8+parseInt(a(364))/9+-parseInt(a(356))/10*(parseInt(r(355))/11);if(s===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Vi,-73523*-3+1*-407717+530518);function Vi(){var t=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return Vi=function(){return t},Vi()}function Hi(t,e){var r=Vi();return Hi=function(a,n){a=a-(-1*-642+503*-5+2227);var s=r[a];return s},Hi(t,e)}class rx extends qh{constructor(e,r){var a;super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(hi.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{const o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=(a=r==null?void 0:r.capabilities)!==null&&a!==void 0?a:{},this._instructions=r==null?void 0:r.instructions,this.setRequestHandler(vh,n=>this._oninitialize(n)),this.setNotificationHandler(Hc,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)}),this._capabilities.logging&&this.setRequestHandler(mi,async(n,s)=>{var o;const i=s.sessionId||((o=s.requestInfo)===null||o===void 0?void 0:o.headers["mcp-session-id"])||void 0,{level:l}=n.params,c=hi.safeParse(l);return c.success&&this._loggingLevels.set(i,c.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fh(this._capabilities,e)}assertCapabilityForMethod(e){var r,a,n;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(!((a=this._clientCapabilities)===null||a===void 0)&&a.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break}}async _oninitialize(e){const r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:ih.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"},Tn)}async createMessage(e,r){return this.request({method:"sampling/createMessage",params:e},au,r)}async elicitInput(e,r){const a=await this.request({method:"elicitation/create",params:e},su,r);if(a.action==="accept"&&a.content)try{const n=new Cm,s=n.compile(e.requestedSchema);if(!s(a.content))throw new st(rt.InvalidParams,`Elicitation response content does not match requested schema: ${n.errorsText(s.errors)}`)}catch(n){throw n instanceof st?n:new st(rt.InternalError,`Error validating elicitation response: ${n}`)}return a}async listRoots(e,r){return this.request({method:"roots/list",params:e},iu,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const nx=Symbol("Let zodToJsonSchema decide on which parser to use"),Gm={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"},ax=t=>typeof t=="string"?{...Gm,name:t}:{...Gm,...t},sx=t=>{const e=ax(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}};function Km(t,e,r,a){a!=null&&a.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Ke(t,e,r,a,n){t[e]=r,Km(t,e,a,n)}const Wm=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function rr(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Wm(e,t.currentPath):e.join("/")}}function ox(t,e){var a,n,s;const r={type:"array"};return(a=t.type)!=null&&a._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==V.ZodAny&&(r.items=Je(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Ke(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Ke(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Ke(r,"minItems",t.exactLength.value,t.exactLength.message,e),Ke(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function ix(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const a of t.checks)switch(a.kind){case"min":e.target==="jsonSchema7"?a.inclusive?Ke(r,"minimum",a.value,a.message,e):Ke(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),Ke(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?Ke(r,"maximum",a.value,a.message,e):Ke(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),Ke(r,"maximum",a.value,a.message,e));break;case"multipleOf":Ke(r,"multipleOf",a.value,a.message,e);break}return r}function lx(){return{type:"boolean"}}function Qm(t,e){return Je(t.type._def,e)}const cx=(t,e)=>Je(t.innerType._def,e);function Ym(t,e,r){const a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,s)=>Ym(t,e,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ux(t,e)}}const ux=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const a of t.checks)switch(a.kind){case"min":Ke(r,"minimum",a.value,a.message,e);break;case"max":Ke(r,"maximum",a.value,a.message,e);break}return r};function dx(t,e){return{...Je(t.innerType._def,e),default:t.defaultValue()}}function px(t,e){return e.effectStrategy==="input"?Je(t.schema._def,e):rr(e)}function fx(t){return{type:"string",enum:Array.from(t.values)}}const hx=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function mx(t,e){const r=[Je(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Je(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let a=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const n=[];return r.forEach(s=>{if(hx(s))n.push(...s.allOf),s.unevaluatedProperties===void 0&&(a=void 0);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:i,...l}=s;o=l}else a=void 0;n.push(o)}}),n.length?{allOf:n,...a}:void 0}function vx(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let ld;const Nr={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:()=>(ld===void 0&&(ld=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ld),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 Xm(t,e){const r={type:"string"};if(t.checks)for(const a of t.checks)switch(a.kind){case"min":Ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e);break;case"max":Ke(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ar(r,"email",a.message,e);break;case"format:idn-email":Ar(r,"idn-email",a.message,e);break;case"pattern:zod":Gt(r,Nr.email,a.message,e);break}break;case"url":Ar(r,"uri",a.message,e);break;case"uuid":Ar(r,"uuid",a.message,e);break;case"regex":Gt(r,a.regex,a.message,e);break;case"cuid":Gt(r,Nr.cuid,a.message,e);break;case"cuid2":Gt(r,Nr.cuid2,a.message,e);break;case"startsWith":Gt(r,RegExp(`^${cd(a.value,e)}`),a.message,e);break;case"endsWith":Gt(r,RegExp(`${cd(a.value,e)}$`),a.message,e);break;case"datetime":Ar(r,"date-time",a.message,e);break;case"date":Ar(r,"date",a.message,e);break;case"time":Ar(r,"time",a.message,e);break;case"duration":Ar(r,"duration",a.message,e);break;case"length":Ke(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e),Ke(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"includes":{Gt(r,RegExp(cd(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&Ar(r,"ipv4",a.message,e),a.version!=="v4"&&Ar(r,"ipv6",a.message,e);break}case"base64url":Gt(r,Nr.base64url,a.message,e);break;case"jwt":Gt(r,Nr.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&Gt(r,Nr.ipv4Cidr,a.message,e),a.version!=="v4"&&Gt(r,Nr.ipv6Cidr,a.message,e);break}case"emoji":Gt(r,Nr.emoji(),a.message,e);break;case"ulid":{Gt(r,Nr.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ar(r,"binary",a.message,e);break}case"contentEncoding:base64":{Ke(r,"contentEncoding","base64",a.message,e);break}case"pattern:zod":{Gt(r,Nr.base64,a.message,e);break}}break}case"nanoid":Gt(r,Nr.nanoid,a.message,e)}return r}function cd(t,e){return e.patternStrategy==="escape"?yx(t):t}const gx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function yx(t){let e="";for(let r=0;r<t.length;r++)gx.has(t[r])||(e+="\\"),e+=t[r];return e}function Ar(t,e,r,a){var n;t.format||(n=t.anyOf)!=null&&n.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&a.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&a.errorMessages&&{errorMessage:{format:r}}})):Ke(t,"format",e,r,a)}function Gt(t,e,r,a){var n;t.pattern||(n=t.allOf)!=null&&n.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&a.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:ev(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):Ke(t,"pattern",ev(e,a),r,a)}function ev(t,e){var l;if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},a=r.i?t.source.toLowerCase():t.source;let n="",s=!1,o=!1,i=!1;for(let c=0;c<a.length;c++){if(s){n+=a[c],s=!1;continue}if(r.i){if(o){if(a[c].match(/[a-z]/)){i?(n+=a[c],n+=`${a[c-2]}-${a[c]}`.toUpperCase(),i=!1):a[c+1]==="-"&&((l=a[c+2])!=null&&l.match(/[a-z]/))?(n+=a[c],i=!0):n+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){n+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(r.m){if(a[c]==="^"){n+=`(^|(?<=[\r
8
+ deps: ${u}}`};const n={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(l){const[c,u]=s(l);o(l,c),i(l,u)}};function s({schema:l}){const c={},u={};for(const h in l){if(h==="__proto__")continue;const g=Array.isArray(l[h])?c:u;g[h]=l[h]}return[c,u]}function o(l,c=l.schema){const{gen:u,data:h,it:g}=l;if(Object.keys(c).length===0)return;const d=u.let("missing");for(const f in c){const v=c[f];if(v.length===0)continue;const m=(0,a.propertyInData)(u,h,f,g.opts.ownProperties);l.setParams({property:f,depsCount:v.length,deps:v.join(", ")}),g.allErrors?u.if(m,()=>{for(const p of v)(0,a.checkReportMissingProp)(l,p)}):(u.if((0,e._)`${m} && (${(0,a.checkMissingProp)(l,v,d)})`),(0,a.reportMissingProp)(l,d),u.else())}}t.validatePropertyDeps=o;function i(l,c=l.schema){const{gen:u,data:h,keyword:g,it:d}=l,f=u.name("valid");for(const v in c)(0,r.alwaysValidSchema)(d,c[v])||(u.if((0,a.propertyInData)(u,h,v,d.opts.ownProperties),()=>{const m=l.subschema({keyword:g,schemaProp:v},f);l.mergeValidEvaluated(m,f)},()=>u.var(f,!0)),l.ok(f))}t.validateSchemaDeps=i,t.default=n})(jp);var hc={};Object.defineProperty(hc,"__esModule",{value:!0});const Dp=Me,jE=se,DE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:{message:"property name must be valid",params:({params:t})=>(0,Dp._)`{propertyName: ${t.propertyName}}`},code(t){const{gen:e,schema:r,data:a,it:n}=t;if((0,jE.alwaysValidSchema)(n,r))return;const s=e.name("valid");e.forIn("key",a,o=>{t.setParams({propertyName:o}),t.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,Dp.not)(s),()=>{t.error(!0),n.allErrors||e.break()})}),t.ok(s)}};hc.default=DE;var Zo={};Object.defineProperty(Zo,"__esModule",{value:!0});const Vo=je,$r=Me,LE=Nr,Ho=se,zE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:{message:"must NOT have additional properties",params:({params:t})=>(0,$r._)`{additionalProperty: ${t.additionalProperty}}`},code(t){const{gen:e,schema:r,parentSchema:a,data:n,errsCount:s,it:o}=t;if(!s)throw new Error("ajv implementation error");const{allErrors:i,opts:l}=o;if(o.props=!0,l.removeAdditional!=="all"&&(0,Ho.alwaysValidSchema)(o,r))return;const c=(0,Vo.allSchemaProperties)(a.properties),u=(0,Vo.allSchemaProperties)(a.patternProperties);h(),t.ok((0,$r._)`${s} === ${LE.default.errors}`);function h(){e.forIn("key",n,m=>{!c.length&&!u.length?f(m):e.if(g(m),()=>f(m))})}function g(m){let p;if(c.length>8){const y=(0,Ho.schemaRefOrVal)(o,a.properties,"properties");p=(0,Vo.isOwnProperty)(e,y,m)}else c.length?p=(0,$r.or)(...c.map(y=>(0,$r._)`${m} === ${y}`)):p=$r.nil;return u.length&&(p=(0,$r.or)(p,...u.map(y=>(0,$r._)`${(0,Vo.usePattern)(t,y)}.test(${m})`))),(0,$r.not)(p)}function d(m){e.code((0,$r._)`delete ${n}[${m}]`)}function f(m){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){d(m);return}if(r===!1){t.setParams({additionalProperty:m}),t.error(),i||e.break();return}if(typeof r=="object"&&!(0,Ho.alwaysValidSchema)(o,r)){const p=e.name("valid");l.removeAdditional==="failing"?(v(m,p,!1),e.if((0,$r.not)(p),()=>{t.reset(),d(m)})):(v(m,p),i||e.if((0,$r.not)(p),()=>e.break()))}}function v(m,p,y){const _={keyword:"additionalProperties",dataProp:m,dataPropType:Ho.Type.Str};y===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,p)}}};Zo.default=zE;var mc={};Object.defineProperty(mc,"__esModule",{value:!0});const UE=wr,Lp=je,vc=se,zp=Zo,qE={keyword:"properties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,parentSchema:a,data:n,it:s}=t;s.opts.removeAdditional==="all"&&a.additionalProperties===void 0&&zp.default.code(new UE.KeywordCxt(s,zp.default,"additionalProperties"));const o=(0,Lp.allSchemaProperties)(r);for(const h of o)s.definedProperties.add(h);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=vc.mergeEvaluated.props(e,(0,vc.toHash)(o),s.props));const i=o.filter(h=>!(0,vc.alwaysValidSchema)(s,r[h]));if(i.length===0)return;const l=e.name("valid");for(const h of i)c(h)?u(h):(e.if((0,Lp.propertyInData)(e,n,h,s.opts.ownProperties)),u(h),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(h),t.ok(l);function c(h){return s.opts.useDefaults&&!s.compositeRule&&r[h].default!==void 0}function u(h){t.subschema({keyword:"properties",schemaProp:h,dataProp:h},l)}}};mc.default=qE;var gc={};Object.defineProperty(gc,"__esModule",{value:!0});const Up=je,Bo=Me,qp=se,Fp=se,FE={keyword:"patternProperties",type:"object",schemaType:"object",code(t){const{gen:e,schema:r,data:a,parentSchema:n,it:s}=t,{opts:o}=s,i=(0,Up.allSchemaProperties)(r),l=i.filter(v=>(0,qp.alwaysValidSchema)(s,r[v]));if(i.length===0||l.length===i.length&&(!s.opts.unevaluated||s.props===!0))return;const c=o.strictSchema&&!o.allowMatchingProperties&&n.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof Bo.Name)&&(s.props=(0,Fp.evaluatedPropsToName)(e,s.props));const{props:h}=s;g();function g(){for(const v of i)c&&d(v),s.allErrors?f(v):(e.var(u,!0),f(v),e.if(u))}function d(v){for(const m in c)new RegExp(v).test(m)&&(0,qp.checkStrictMode)(s,`property ${m} matches pattern ${v} (use allowMatchingProperties)`)}function f(v){e.forIn("key",a,m=>{e.if((0,Bo._)`${(0,Up.usePattern)(t,v)}.test(${m})`,()=>{const p=l.includes(v);p||t.subschema({keyword:"patternProperties",schemaProp:v,dataProp:m,dataPropType:Fp.Type.Str},u),s.opts.unevaluated&&h!==!0?e.assign((0,Bo._)`${h}[${m}]`,!0):!p&&!s.allErrors&&e.if((0,Bo.not)(u),()=>e.break())})})}}};gc.default=FE;var yc={};Object.defineProperty(yc,"__esModule",{value:!0});const ZE=se,VE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:e,schema:r,it:a}=t;if((0,ZE.alwaysValidSchema)(a,r)){t.fail();return}const n=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},n),t.failResult(n,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};yc.default=VE;var _c={};Object.defineProperty(_c,"__esModule",{value:!0});const HE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:je.validateUnion,error:{message:"must match a schema in anyOf"}};_c.default=HE;var wc={};Object.defineProperty(wc,"__esModule",{value:!0});const Jo=Me,BE=se,JE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:{message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Jo._)`{passingSchemas: ${t.passing}}`},code(t){const{gen:e,schema:r,parentSchema:a,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(n.opts.discriminator&&a.discriminator)return;const s=r,o=e.let("valid",!1),i=e.let("passing",null),l=e.name("_valid");t.setParams({passing:i}),e.block(c),t.result(o,()=>t.reset(),()=>t.error(!0));function c(){s.forEach((u,h)=>{let g;(0,BE.alwaysValidSchema)(n,u)?e.var(l,!0):g=t.subschema({keyword:"oneOf",schemaProp:h,compositeRule:!0},l),h>0&&e.if((0,Jo._)`${l} && ${o}`).assign(o,!1).assign(i,(0,Jo._)`[${i}, ${h}]`).else(),e.if(l,()=>{e.assign(o,!0),e.assign(i,h),g&&t.mergeEvaluated(g,Jo.Name)})})}}};wc.default=JE;var bc={};Object.defineProperty(bc,"__esModule",{value:!0});const GE=se,KE={keyword:"allOf",schemaType:"array",code(t){const{gen:e,schema:r,it:a}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");const n=e.name("valid");r.forEach((s,o)=>{if((0,GE.alwaysValidSchema)(a,s))return;const i=t.subschema({keyword:"allOf",schemaProp:o},n);t.ok(n),t.mergeEvaluated(i)})}};bc.default=KE;var Ec={};Object.defineProperty(Ec,"__esModule",{value:!0});const Go=Me,Zp=se,WE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:{message:({params:t})=>(0,Go.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Go._)`{failingKeyword: ${t.ifClause}}`},code(t){const{gen:e,parentSchema:r,it:a}=t;r.then===void 0&&r.else===void 0&&(0,Zp.checkStrictMode)(a,'"if" without "then" and "else" is ignored');const n=Vp(a,"then"),s=Vp(a,"else");if(!n&&!s)return;const o=e.let("valid",!0),i=e.name("_valid");if(l(),t.reset(),n&&s){const u=e.let("ifClause");t.setParams({ifClause:u}),e.if(i,c("then",u),c("else",u))}else n?e.if(i,c("then")):e.if((0,Go.not)(i),c("else"));t.pass(o,()=>t.error(!0));function l(){const u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(u)}function c(u,h){return()=>{const g=t.subschema({keyword:u},i);e.assign(o,i),t.mergeValidEvaluated(g,o),h?e.assign(h,(0,Go._)`${u}`):t.setParams({ifClause:u})}}}};function Vp(t,e){const r=t.schema[e];return r!==void 0&&!(0,Zp.alwaysValidSchema)(t,r)}Ec.default=WE;var $c={};Object.defineProperty($c,"__esModule",{value:!0});const QE=se,YE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,QE.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};$c.default=YE,Object.defineProperty(cc,"__esModule",{value:!0});const XE=ya,e$=dc,t$=_a,r$=fc,n$=pc,a$=jp,s$=hc,o$=Zo,i$=mc,l$=gc,c$=yc,u$=_c,d$=wc,f$=bc,p$=Ec,h$=$c;function m$(t=!1){const e=[c$.default,u$.default,d$.default,f$.default,p$.default,h$.default,s$.default,o$.default,a$.default,i$.default,l$.default];return t?e.push(e$.default,r$.default):e.push(XE.default,t$.default),e.push(n$.default),e}cc.default=m$;var Sc={},Pc={};Object.defineProperty(Pc,"__esModule",{value:!0});const vt=Me,v$={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:{message:({schemaCode:t})=>(0,vt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,vt._)`{format: ${t}}`},code(t,e){const{gen:r,data:a,$data:n,schema:s,schemaCode:o,it:i}=t,{opts:l,errSchemaPath:c,schemaEnv:u,self:h}=i;if(!l.validateFormats)return;n?g():d();function g(){const f=r.scopeValue("formats",{ref:h.formats,code:l.code.formats}),v=r.const("fDef",(0,vt._)`${f}[${o}]`),m=r.let("fType"),p=r.let("format");r.if((0,vt._)`typeof ${v} == "object" && !(${v} instanceof RegExp)`,()=>r.assign(m,(0,vt._)`${v}.type || "string"`).assign(p,(0,vt._)`${v}.validate`),()=>r.assign(m,(0,vt._)`"string"`).assign(p,v)),t.fail$data((0,vt.or)(y(),_()));function y(){return l.strictSchema===!1?vt.nil:(0,vt._)`${o} && !${p}`}function _(){const w=u.$async?(0,vt._)`(${v}.async ? await ${p}(${a}) : ${p}(${a}))`:(0,vt._)`${p}(${a})`,E=(0,vt._)`(typeof ${p} == "function" ? ${w} : ${p}.test(${a}))`;return(0,vt._)`${p} && ${p} !== true && ${m} === ${e} && !${E}`}}function d(){const f=h.formats[s];if(!f){y();return}if(f===!0)return;const[v,m,p]=_(f);v===e&&t.pass(w());function y(){if(l.strictSchema===!1){h.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${c}"`}}function _(E){const P=E instanceof RegExp?(0,vt.regexpCode)(E):l.code.formats?(0,vt._)`${l.code.formats}${(0,vt.getProperty)(s)}`:void 0,T=r.scopeValue("formats",{key:s,ref:E,code:P});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,vt._)`${T}.validate`]:["string",E,T]}function w(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,vt._)`await ${p}(${a})`}return typeof m=="function"?(0,vt._)`${p}(${a})`:(0,vt._)`${p}.test(${a})`}}}};Pc.default=v$,Object.defineProperty(Sc,"__esModule",{value:!0});const g$=[Pc.default];Sc.default=g$;var wa={};Object.defineProperty(wa,"__esModule",{value:!0}),wa.contentVocabulary=wa.metadataVocabulary=void 0,wa.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"],wa.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"],Object.defineProperty(Bl,"__esModule",{value:!0});const y$=Jl,_$=Kl,w$=cc,b$=Sc,Hp=wa,E$=[y$.default,_$.default,(0,w$.default)(),b$.default,Hp.metadataVocabulary,Hp.contentVocabulary];Bl.default=E$;var Tc={},Ko={};Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.DiscrError=void 0;var Bp;(function(t){t.Tag="tag",t.Mapping="mapping"})(Bp||(Ko.DiscrError=Bp={})),Object.defineProperty(Tc,"__esModule",{value:!0});const ba=Me,xc=Ko,Jp=Vt,$$=va,S$=se,P$={keyword:"discriminator",type:"object",schemaType:"object",error:{message:({params:{discrError:t,tagName:e}})=>t===xc.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ba._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},code(t){const{gen:e,data:r,schema:a,parentSchema:n,it:s}=t,{oneOf:o}=n;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const i=a.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(a.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");const l=e.let("valid",!1),c=e.const("tag",(0,ba._)`${r}${(0,ba.getProperty)(i)}`);e.if((0,ba._)`typeof ${c} == "string"`,()=>u(),()=>t.error(!1,{discrError:xc.DiscrError.Tag,tag:c,tagName:i})),t.ok(l);function u(){const d=g();e.if(!1);for(const f in d)e.elseIf((0,ba._)`${c} === ${f}`),e.assign(l,h(d[f]));e.else(),t.error(!1,{discrError:xc.DiscrError.Mapping,tag:c,tagName:i}),e.endIf()}function h(d){const f=e.name("valid"),v=t.subschema({keyword:"oneOf",schemaProp:d},f);return t.mergeEvaluated(v,ba.Name),f}function g(){var d;const f={},v=p(n);let m=!0;for(let w=0;w<o.length;w++){let E=o[w];if(E!=null&&E.$ref&&!(0,S$.schemaHasRulesButRef)(E,s.self.RULES)){const T=E.$ref;if(E=Jp.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,T),E instanceof Jp.SchemaEnv&&(E=E.schema),E===void 0)throw new $$.default(s.opts.uriResolver,s.baseId,T)}const P=(d=E==null?void 0:E.properties)===null||d===void 0?void 0:d[i];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);m=m&&(v||p(E)),y(P,w)}if(!m)throw new Error(`discriminator: "${i}" must be required`);return f;function p({required:w}){return Array.isArray(w)&&w.includes(i)}function y(w,E){if(w.const)_(w.const,E);else if(w.enum)for(const P of w.enum)_(P,E);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function _(w,E){if(typeof w!="string"||w in f)throw new Error(`discriminator: "${i}" values must be unique strings`);f[w]=E}}}};Tc.default=P$;const T$={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0};(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const r=xf,a=Bl,n=Tc,s=T$,o=["/properties"],i="http://json-schema.org/draft-07/schema";class l extends r.default{_addVocabularies(){super._addVocabularies(),a.default.forEach(f=>this.addVocabulary(f)),this.opts.discriminator&&this.addKeyword(n.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const f=this.opts.$data?this.$dataMetaSchema(s,o):s;this.addMetaSchema(f,i,!1),this.refs["http://json-schema.org/schema"]=i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(i)?i:void 0)}}e.Ajv=l,t.exports=e=l,t.exports.Ajv=l,Object.defineProperty(e,"__esModule",{value:!0}),e.default=l;var c=wr;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return c.KeywordCxt}});var u=Me;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var h=os;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return h.default}});var g=va;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return g.default}})})(Sl,Sl.exports);var x$=Sl.exports;const k$=Tf(x$);var Ue;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{const s={};for(const o of n)s[o]=o;return s},t.getValidEnumValues=n=>{const s=t.objectKeys(n).filter(i=>typeof n[n[i]]!="number"),o={};for(const i of s)o[i]=n[i];return t.objectValues(o)},t.objectValues=n=>t.objectKeys(n).map(function(s){return n[s]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const s=[];for(const o in n)Object.prototype.hasOwnProperty.call(n,o)&&s.push(o);return s},t.find=(n,s)=>{for(const o of n)if(s(o))return o},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function a(n,s=" | "){return n.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}t.joinValues=a,t.jsonStringifyReplacer=(n,s)=>typeof s=="bigint"?s.toString():s})(Ue||(Ue={}));var kc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(kc||(kc={}));const oe=Ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),an=t=>{switch(typeof t){case"undefined":return oe.undefined;case"string":return oe.string;case"number":return Number.isNaN(t)?oe.nan:oe.number;case"boolean":return oe.boolean;case"function":return oe.function;case"bigint":return oe.bigint;case"symbol":return oe.symbol;case"object":return Array.isArray(t)?oe.array:t===null?oe.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?oe.promise:typeof Map<"u"&&t instanceof Map?oe.map:typeof Set<"u"&&t instanceof Set?oe.set:typeof Date<"u"&&t instanceof Date?oe.date:oe.object;default:return oe.unknown}},Y=Ue.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),I$=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class tr extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(n);else if(o.code==="invalid_return_type")n(o.returnTypeError);else if(o.code==="invalid_arguments")n(o.argumentsError);else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(o))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return n(this),a}static assert(e){if(!(e instanceof tr))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ue.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r={},a=[];for(const n of this.issues)if(n.path.length>0){const s=n.path[0];r[s]=r[s]||[],r[s].push(e(n))}else a.push(e(n));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}}tr.create=t=>new tr(t);const Ea=(t,e)=>{let r;switch(t.code){case Y.invalid_type:t.received===oe.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case Y.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Ue.jsonStringifyReplacer)}`;break;case Y.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ue.joinValues(t.keys,", ")}`;break;case Y.invalid_union:r="Invalid input";break;case Y.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ue.joinValues(t.options)}`;break;case Y.invalid_enum_value:r=`Invalid enum value. Expected ${Ue.joinValues(t.options)}, received '${t.received}'`;break;case Y.invalid_arguments:r="Invalid function arguments";break;case Y.invalid_return_type:r="Invalid function return type";break;case Y.invalid_date:r="Invalid date";break;case Y.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Ue.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case Y.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case Y.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case Y.custom:r="Invalid input";break;case Y.invalid_intersection_types:r="Intersection results could not be merged";break;case Y.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case Y.not_finite:r="Number must be finite";break;default:r=e.defaultError,Ue.assertNever(t)}return{message:r}};let Gp=Ea;function C$(t){Gp=t}function Wo(){return Gp}const Qo=t=>{const{data:e,path:r,errorMaps:a,issueData:n}=t,s=[...r,...n.path||[]],o={...n,path:s};if(n.message!==void 0)return{...n,path:s,message:n.message};let i="";const l=a.filter(c=>!!c).slice().reverse();for(const c of l)i=c(o,{data:e,defaultError:i}).message;return{...n,path:s,message:i}},R$=[];function ae(t,e){const r=Wo(),a=Qo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ea?void 0:Ea].filter(n=>!!n)});t.common.issues.push(a)}class Dt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const a=[];for(const n of r){if(n.status==="aborted")return be;n.status==="dirty"&&e.dirty(),a.push(n.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,r){const a=[];for(const n of r){const s=await n.key,o=await n.value;a.push({key:s,value:o})}return Dt.mergeObjectSync(e,a)}static mergeObjectSync(e,r){const a={};for(const n of r){const{key:s,value:o}=n;if(s.status==="aborted"||o.status==="aborted")return be;s.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||n.alwaysSet)&&(a[s.value]=o.value)}return{status:e.value,value:a}}}const be=Object.freeze({status:"aborted"}),$a=t=>({status:"dirty",value:t}),qt=t=>({status:"valid",value:t}),Ic=t=>t.status==="aborted",Cc=t=>t.status==="dirty",Fn=t=>t.status==="valid",ms=t=>typeof Promise<"u"&&t instanceof Promise;var fe;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(fe||(fe={}));class Lr{constructor(e,r,a,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=a,this._key=n}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 Kp=(t,e)=>{if(Fn(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new tr(t.common.issues);return this._error=r,this._error}}};function Ce(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,i)=>{const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??a??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:n}}let Oe=class{get description(){return this._def.description}_getType(e){return an(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:an(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Dt,ctx:{common:e.parent.common,data:e.data,parsedType:an(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(ms(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const a=this.safeParse(e,r);if(a.success)return a.data;throw a.error}safeParse(e,r){const a={common:{issues:[],async:(r==null?void 0:r.async)??!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:an(e)},n=this._parseSync({data:e,path:a.path,parent:a});return Kp(a,n)}"~validate"(e){var a,n;const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:an(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:r});return Fn(s)?{value:s.value}:{issues:r.common.issues}}catch(s){(n=(a=s==null?void 0:s.message)==null?void 0:a.toLowerCase())!=null&&n.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(s=>Fn(s)?{value:s.value}:{issues:r.common.issues})}async parseAsync(e,r){const a=await this.safeParseAsync(e,r);if(a.success)return a.data;throw a.error}async safeParseAsync(e,r){const a={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:an(e)},n=this._parse({data:e,path:a.path,parent:a}),s=await(ms(n)?n:Promise.resolve(n));return Kp(a,s)}refine(e,r){const a=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,s)=>{const o=e(n),i=()=>s.addIssue({code:Y.custom,...a(n)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,r){return this._refinement((a,n)=>e(a)?!0:(n.addIssue(typeof r=="function"?r(a,n):r),!1))}_refinement(e){return new Sr({schema:this,typeName:V.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Ur.create(this,this._def)}nullable(){return yn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Hn.create(this)}promise(){return ka.create(this,this._def)}or(e){return ws.create([this,e],this._def)}and(e){return bs.create(this,e,this._def)}transform(e){return new Sr({...Ce(this._def),schema:this,typeName:V.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new Ts({...Ce(this._def),innerType:this,defaultValue:r,typeName:V.ZodDefault})}brand(){return new Ac({typeName:V.ZodBranded,type:this,...Ce(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new xs({...Ce(this._def),innerType:this,catchValue:r,typeName:V.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ks.create(this,e)}readonly(){return Is.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const O$=/^c[^\s-]{8,}$/i,A$=/^[0-9a-z]+$/,N$=/^[0-9A-HJKMNP-TV-Z]{26}$/i,M$=/^[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,j$=/^[a-z0-9_-]{21}$/i,D$=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,L$=/^[-+]?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)?)??$/,z$=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,U$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Rc;const q$=/^(?:(?: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])$/,F$=/^(?:(?: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])$/,Z$=/^(([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]))$/,V$=/^(([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])$/,H$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,B$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Wp="((\\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])))",J$=new RegExp(`^${Wp}$`);function Qp(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function G$(t){return new RegExp(`^${Qp(t)}$`)}function Yp(t){let e=`${Wp}T${Qp(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function K$(t,e){return!!((e==="v4"||!e)&&q$.test(t)||(e==="v6"||!e)&&Z$.test(t))}function W$(t,e){if(!D$.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));return!(typeof n!="object"||n===null||"typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Q$(t,e){return!!((e==="v4"||!e)&&F$.test(t)||(e==="v6"||!e)&&V$.test(t))}let Sa=class xo extends Oe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==oe.string){const s=this._getOrReturnCtx(e);return ae(s,{code:Y.invalid_type,expected:oe.string,received:s.parsedType}),be}const a=new Dt;let n;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="max")e.data.length>s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),a.dirty());else if(s.kind==="length"){const o=e.data.length>s.value,i=e.data.length<s.value;(o||i)&&(n=this._getOrReturnCtx(e,n),o?ae(n,{code:Y.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):i&&ae(n,{code:Y.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),a.dirty())}else if(s.kind==="email")z$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"email",code:Y.invalid_string,message:s.message}),a.dirty());else if(s.kind==="emoji")Rc||(Rc=new RegExp(U$,"u")),Rc.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"emoji",code:Y.invalid_string,message:s.message}),a.dirty());else if(s.kind==="uuid")M$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"uuid",code:Y.invalid_string,message:s.message}),a.dirty());else if(s.kind==="nanoid")j$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"nanoid",code:Y.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid")O$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"cuid",code:Y.invalid_string,message:s.message}),a.dirty());else if(s.kind==="cuid2")A$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"cuid2",code:Y.invalid_string,message:s.message}),a.dirty());else if(s.kind==="ulid")N$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"ulid",code:Y.invalid_string,message:s.message}),a.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),ae(n,{validation:"url",code:Y.invalid_string,message:s.message}),a.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"regex",code:Y.invalid_string,message:s.message}),a.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),a.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.invalid_string,validation:{startsWith:s.value},message:s.message}),a.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.invalid_string,validation:{endsWith:s.value},message:s.message}),a.dirty()):s.kind==="datetime"?Yp(s).test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.invalid_string,validation:"datetime",message:s.message}),a.dirty()):s.kind==="date"?J$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.invalid_string,validation:"date",message:s.message}),a.dirty()):s.kind==="time"?G$(s).test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.invalid_string,validation:"time",message:s.message}),a.dirty()):s.kind==="duration"?L$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"duration",code:Y.invalid_string,message:s.message}),a.dirty()):s.kind==="ip"?K$(e.data,s.version)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"ip",code:Y.invalid_string,message:s.message}),a.dirty()):s.kind==="jwt"?W$(e.data,s.alg)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"jwt",code:Y.invalid_string,message:s.message}),a.dirty()):s.kind==="cidr"?Q$(e.data,s.version)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"cidr",code:Y.invalid_string,message:s.message}),a.dirty()):s.kind==="base64"?H$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"base64",code:Y.invalid_string,message:s.message}),a.dirty()):s.kind==="base64url"?B$.test(e.data)||(n=this._getOrReturnCtx(e,n),ae(n,{validation:"base64url",code:Y.invalid_string,message:s.message}),a.dirty()):Ue.assertNever(s);return{status:a.value,value:e.data}}_regex(e,r,a){return this.refinement(n=>e.test(n),{validation:r,code:Y.invalid_string,...fe.errToObj(a)})}_addCheck(e){return new xo({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...fe.errToObj(e)})}url(e){return this._addCheck({kind:"url",...fe.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...fe.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...fe.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...fe.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...fe.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...fe.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...fe.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...fe.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...fe.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...fe.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...fe.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...fe.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...fe.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...fe.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...fe.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...fe.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...fe.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...fe.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...fe.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...fe.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...fe.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...fe.errToObj(r)})}nonempty(e){return this.min(1,fe.errToObj(e))}trim(){return new xo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new xo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new xo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Sa.create=t=>new Sa({checks:[],typeName:V.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...Ce(t)});function Y$(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}let vs=class Ef extends Oe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==oe.number){const s=this._getOrReturnCtx(e);return ae(s,{code:Y.invalid_type,expected:oe.number,received:s.parsedType}),be}let a;const n=new Dt;for(const s of this._def.checks)s.kind==="int"?Ue.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),ae(a,{code:Y.invalid_type,expected:"integer",received:"float",message:s.message}),n.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:Y.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:Y.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),n.dirty()):s.kind==="multipleOf"?Y$(e.data,s.value)!==0&&(a=this._getOrReturnCtx(e,a),ae(a,{code:Y.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),ae(a,{code:Y.not_finite,message:s.message}),n.dirty()):Ue.assertNever(s);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,fe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,fe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,fe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,fe.toString(r))}setLimit(e,r,a,n){return new Ef({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:fe.toString(n)}]})}_addCheck(e){return new Ef({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:fe.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:fe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:fe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:fe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:fe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:fe.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:fe.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:fe.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:fe.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Ue.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(r)&&Number.isFinite(e)}};vs.create=t=>new vs({checks:[],typeName:V.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ce(t)});class gn extends Oe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==oe.bigint)return this._getInvalidInput(e);let a;const n=new Dt;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:Y.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:Y.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),n.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),ae(a,{code:Y.not_multiple_of,multipleOf:s.value,message:s.message}),n.dirty()):Ue.assertNever(s);return{status:n.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return ae(r,{code:Y.invalid_type,expected:oe.bigint,received:r.parsedType}),be}gte(e,r){return this.setLimit("min",e,!0,fe.toString(r))}gt(e,r){return this.setLimit("min",e,!1,fe.toString(r))}lte(e,r){return this.setLimit("max",e,!0,fe.toString(r))}lt(e,r){return this.setLimit("max",e,!1,fe.toString(r))}setLimit(e,r,a,n){return new gn({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:fe.toString(n)}]})}_addCheck(e){return new gn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:fe.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:fe.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:fe.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:fe.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:fe.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}gn.create=t=>new gn({checks:[],typeName:V.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...Ce(t)});let gs=class extends Oe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==oe.boolean){const a=this._getOrReturnCtx(e);return ae(a,{code:Y.invalid_type,expected:oe.boolean,received:a.parsedType}),be}return qt(e.data)}};gs.create=t=>new gs({typeName:V.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ce(t)});class Zn extends Oe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==oe.date){const s=this._getOrReturnCtx(e);return ae(s,{code:Y.invalid_type,expected:oe.date,received:s.parsedType}),be}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return ae(s,{code:Y.invalid_date}),be}const a=new Dt;let n;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),a.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(n=this._getOrReturnCtx(e,n),ae(n,{code:Y.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),a.dirty()):Ue.assertNever(s);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Zn({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:fe.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:fe.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}Zn.create=t=>new Zn({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:V.ZodDate,...Ce(t)});class Yo extends Oe{_parse(e){if(this._getType(e)!==oe.symbol){const a=this._getOrReturnCtx(e);return ae(a,{code:Y.invalid_type,expected:oe.symbol,received:a.parsedType}),be}return qt(e.data)}}Yo.create=t=>new Yo({typeName:V.ZodSymbol,...Ce(t)});class ys extends Oe{_parse(e){if(this._getType(e)!==oe.undefined){const a=this._getOrReturnCtx(e);return ae(a,{code:Y.invalid_type,expected:oe.undefined,received:a.parsedType}),be}return qt(e.data)}}ys.create=t=>new ys({typeName:V.ZodUndefined,...Ce(t)});let _s=class extends Oe{_parse(e){if(this._getType(e)!==oe.null){const a=this._getOrReturnCtx(e);return ae(a,{code:Y.invalid_type,expected:oe.null,received:a.parsedType}),be}return qt(e.data)}};_s.create=t=>new _s({typeName:V.ZodNull,...Ce(t)});let Pa=class extends Oe{constructor(){super(...arguments),this._any=!0}_parse(e){return qt(e.data)}};Pa.create=t=>new Pa({typeName:V.ZodAny,...Ce(t)});let Vn=class extends Oe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return qt(e.data)}};Vn.create=t=>new Vn({typeName:V.ZodUnknown,...Ce(t)});let sn=class extends Oe{_parse(e){const r=this._getOrReturnCtx(e);return ae(r,{code:Y.invalid_type,expected:oe.never,received:r.parsedType}),be}};sn.create=t=>new sn({typeName:V.ZodNever,...Ce(t)});class Xo extends Oe{_parse(e){if(this._getType(e)!==oe.undefined){const a=this._getOrReturnCtx(e);return ae(a,{code:Y.invalid_type,expected:oe.void,received:a.parsedType}),be}return qt(e.data)}}Xo.create=t=>new Xo({typeName:V.ZodVoid,...Ce(t)});let Hn=class $l extends Oe{_parse(e){const{ctx:r,status:a}=this._processInputParams(e),n=this._def;if(r.parsedType!==oe.array)return ae(r,{code:Y.invalid_type,expected:oe.array,received:r.parsedType}),be;if(n.exactLength!==null){const o=r.data.length>n.exactLength.value,i=r.data.length<n.exactLength.value;(o||i)&&(ae(r,{code:o?Y.too_big:Y.too_small,minimum:i?n.exactLength.value:void 0,maximum:o?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),a.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(ae(r,{code:Y.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),a.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(ae(r,{code:Y.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((o,i)=>n.type._parseAsync(new Lr(r,o,r.path,i)))).then(o=>Dt.mergeArray(a,o));const s=[...r.data].map((o,i)=>n.type._parseSync(new Lr(r,o,r.path,i)));return Dt.mergeArray(a,s)}get element(){return this._def.type}min(e,r){return new $l({...this._def,minLength:{value:e,message:fe.toString(r)}})}max(e,r){return new $l({...this._def,maxLength:{value:e,message:fe.toString(r)}})}length(e,r){return new $l({...this._def,exactLength:{value:e,message:fe.toString(r)}})}nonempty(e){return this.min(1,e)}};Hn.create=(t,e)=>new Hn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:V.ZodArray,...Ce(e)});function Ta(t){if(t instanceof cr){const e={};for(const r in t.shape){const a=t.shape[r];e[r]=Ur.create(Ta(a))}return new cr({...t._def,shape:()=>e})}else return t instanceof Hn?new Hn({...t._def,type:Ta(t.element)}):t instanceof Ur?Ur.create(Ta(t.unwrap())):t instanceof yn?yn.create(Ta(t.unwrap())):t instanceof zr?zr.create(t.items.map(e=>Ta(e))):t}let cr=class Ar extends Oe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=Ue.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==oe.object){const c=this._getOrReturnCtx(e);return ae(c,{code:Y.invalid_type,expected:oe.object,received:c.parsedType}),be}const{status:a,ctx:n}=this._processInputParams(e),{shape:s,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof sn&&this._def.unknownKeys==="strip"))for(const c in n.data)o.includes(c)||i.push(c);const l=[];for(const c of o){const u=s[c],h=n.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Lr(n,h,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof sn){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of i)l.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(c==="strict")i.length>0&&(ae(n,{code:Y.unrecognized_keys,keys:i}),a.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 h=n.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Lr(n,h,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,g=await u.value;c.push({key:h,value:g,alwaysSet:u.alwaysSet})}return c}).then(c=>Dt.mergeObjectSync(a,c)):Dt.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return fe.errToObj,new Ar({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,a)=>{var s,o;const n=((o=(s=this._def).errorMap)==null?void 0:o.call(s,r,a).message)??a.defaultError;return r.code==="unrecognized_keys"?{message:fe.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new Ar({...this._def,unknownKeys:"strip"})}passthrough(){return new Ar({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ar({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ar({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:V.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new Ar({...this._def,catchall:e})}pick(e){const r={};for(const a of Ue.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new Ar({...this._def,shape:()=>r})}omit(e){const r={};for(const a of Ue.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new Ar({...this._def,shape:()=>r})}deepPartial(){return Ta(this)}partial(e){const r={};for(const a of Ue.objectKeys(this.shape)){const n=this.shape[a];e&&!e[a]?r[a]=n:r[a]=n.optional()}return new Ar({...this._def,shape:()=>r})}required(e){const r={};for(const a of Ue.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let s=this.shape[a];for(;s instanceof Ur;)s=s._def.innerType;r[a]=s}return new Ar({...this._def,shape:()=>r})}keyof(){return th(Ue.objectKeys(this.shape))}};cr.create=(t,e)=>new cr({shape:()=>t,unknownKeys:"strip",catchall:sn.create(),typeName:V.ZodObject,...Ce(e)}),cr.strictCreate=(t,e)=>new cr({shape:()=>t,unknownKeys:"strict",catchall:sn.create(),typeName:V.ZodObject,...Ce(e)}),cr.lazycreate=(t,e)=>new cr({shape:t,unknownKeys:"strip",catchall:sn.create(),typeName:V.ZodObject,...Ce(e)});let ws=class extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a=this._def.options;function n(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 o=s.map(i=>new tr(i.ctx.common.issues));return ae(r,{code:Y.invalid_union,unionErrors:o}),be}if(r.common.async)return Promise.all(a.map(async s=>{const o={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(n);{let s;const o=[];for(const l of a){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&&o.push(c.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const i=o.map(l=>new tr(l));return ae(r,{code:Y.invalid_union,unionErrors:i}),be}}get options(){return this._def.options}};ws.create=(t,e)=>new ws({options:t,typeName:V.ZodUnion,...Ce(e)});const on=t=>t instanceof Es?on(t.schema):t instanceof Sr?on(t.innerType()):t instanceof $s?[t.value]:t instanceof Ss?t.options:t instanceof Ps?Ue.objectValues(t.enum):t instanceof Ts?on(t._def.innerType):t instanceof ys?[void 0]:t instanceof _s?[null]:t instanceof Ur?[void 0,...on(t.unwrap())]:t instanceof yn?[null,...on(t.unwrap())]:t instanceof Ac||t instanceof Is?on(t.unwrap()):t instanceof xs?on(t._def.innerType):[];let Xp=class hw extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.object)return ae(r,{code:Y.invalid_type,expected:oe.object,received:r.parsedType}),be;const a=this.discriminator,n=r.data[a],s=this.optionsMap.get(n);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}):(ae(r,{code:Y.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),be)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,a){const n=new Map;for(const s of r){const o=on(s.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const i of o){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,s)}}return new hw({typeName:V.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...Ce(a)})}};function Oc(t,e){const r=an(t),a=an(e);if(t===e)return{valid:!0,data:t};if(r===oe.object&&a===oe.object){const n=Ue.objectKeys(e),s=Ue.objectKeys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(const i of s){const l=Oc(t[i],e[i]);if(!l.valid)return{valid:!1};o[i]=l.data}return{valid:!0,data:o}}else if(r===oe.array&&a===oe.array){if(t.length!==e.length)return{valid:!1};const n=[];for(let s=0;s<t.length;s++){const o=t[s],i=e[s],l=Oc(o,i);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return r===oe.date&&a===oe.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let bs=class extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=(s,o)=>{if(Ic(s)||Ic(o))return be;const i=Oc(s.value,o.value);return i.valid?((Cc(s)||Cc(o))&&r.dirty(),{status:r.value,value:i.data}):(ae(a,{code:Y.invalid_intersection_types}),be)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([s,o])=>n(s,o)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};bs.create=(t,e,r)=>new bs({left:t,right:e,typeName:V.ZodIntersection,...Ce(r)});class zr extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==oe.array)return ae(a,{code:Y.invalid_type,expected:oe.array,received:a.parsedType}),be;if(a.data.length<this._def.items.length)return ae(a,{code:Y.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),be;!this._def.rest&&a.data.length>this._def.items.length&&(ae(a,{code:Y.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...a.data].map((o,i)=>{const l=this._def.items[i]||this._def.rest;return l?l._parse(new Lr(a,o,a.path,i)):null}).filter(o=>!!o);return a.common.async?Promise.all(s).then(o=>Dt.mergeArray(r,o)):Dt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new zr({...this._def,rest:e})}}zr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new zr({items:t,typeName:V.ZodTuple,rest:null,...Ce(e)})};let eh=class $f extends Oe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==oe.object)return ae(a,{code:Y.invalid_type,expected:oe.object,received:a.parsedType}),be;const n=[],s=this._def.keyType,o=this._def.valueType;for(const i in a.data)n.push({key:s._parse(new Lr(a,i,a.path,i)),value:o._parse(new Lr(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?Dt.mergeObjectAsync(r,n):Dt.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,a){return r instanceof Oe?new $f({keyType:e,valueType:r,typeName:V.ZodRecord,...Ce(a)}):new $f({keyType:Sa.create(),valueType:e,typeName:V.ZodRecord,...Ce(r)})}};class ei extends Oe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==oe.map)return ae(a,{code:Y.invalid_type,expected:oe.map,received:a.parsedType}),be;const n=this._def.keyType,s=this._def.valueType,o=[...a.data.entries()].map(([i,l],c)=>({key:n._parse(new Lr(a,i,a.path,[c,"key"])),value:s._parse(new Lr(a,l,a.path,[c,"value"]))}));if(a.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return be;(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 o){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return be;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),i.set(c.value,u.value)}return{status:r.value,value:i}}}}ei.create=(t,e,r)=>new ei({valueType:e,keyType:t,typeName:V.ZodMap,...Ce(r)});class Bn extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==oe.set)return ae(a,{code:Y.invalid_type,expected:oe.set,received:a.parsedType}),be;const n=this._def;n.minSize!==null&&a.data.size<n.minSize.value&&(ae(a,{code:Y.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&a.data.size>n.maxSize.value&&(ae(a,{code:Y.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());const s=this._def.valueType;function o(l){const c=new Set;for(const u of l){if(u.status==="aborted")return be;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const i=[...a.data.values()].map((l,c)=>s._parse(new Lr(a,l,a.path,c)));return a.common.async?Promise.all(i).then(l=>o(l)):o(i)}min(e,r){return new Bn({...this._def,minSize:{value:e,message:fe.toString(r)}})}max(e,r){return new Bn({...this._def,maxSize:{value:e,message:fe.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Bn.create=(t,e)=>new Bn({valueType:t,minSize:null,maxSize:null,typeName:V.ZodSet,...Ce(e)});class xa extends Oe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.function)return ae(r,{code:Y.invalid_type,expected:oe.function,received:r.parsedType}),be;function a(i,l){return Qo({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Wo(),Ea].filter(c=>!!c),issueData:{code:Y.invalid_arguments,argumentsError:l}})}function n(i,l){return Qo({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Wo(),Ea].filter(c=>!!c),issueData:{code:Y.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof ka){const i=this;return qt(async function(...l){const c=new tr([]),u=await i._def.args.parseAsync(l,s).catch(d=>{throw c.addIssue(a(l,d)),c}),h=await Reflect.apply(o,this,u);return await i._def.returns._def.type.parseAsync(h,s).catch(d=>{throw c.addIssue(n(h,d)),c})})}else{const i=this;return qt(function(...l){const c=i._def.args.safeParse(l,s);if(!c.success)throw new tr([a(l,c.error)]);const u=Reflect.apply(o,this,c.data),h=i._def.returns.safeParse(u,s);if(!h.success)throw new tr([n(u,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new xa({...this._def,args:zr.create(e).rest(Vn.create())})}returns(e){return new xa({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,a){return new xa({args:e||zr.create([]).rest(Vn.create()),returns:r||Vn.create(),typeName:V.ZodFunction,...Ce(a)})}}let Es=class extends Oe{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Es.create=(t,e)=>new Es({getter:t,typeName:V.ZodLazy,...Ce(e)});let $s=class extends Oe{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return ae(r,{received:r.data,code:Y.invalid_literal,expected:this._def.value}),be}return{status:"valid",value:e.data}}get value(){return this._def.value}};$s.create=(t,e)=>new $s({value:t,typeName:V.ZodLiteral,...Ce(e)});function th(t,e){return new Ss({values:t,typeName:V.ZodEnum,...Ce(e)})}let Ss=class Sf extends Oe{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),a=this._def.values;return ae(r,{expected:Ue.joinValues(a),received:r.parsedType,code:Y.invalid_type}),be}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),a=this._def.values;return ae(r,{received:r.data,code:Y.invalid_enum_value,options:a}),be}return qt(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Sf.create(e,{...this._def,...r})}exclude(e,r=this._def){return Sf.create(this.options.filter(a=>!e.includes(a)),{...this._def,...r})}};Ss.create=th;class Ps extends Oe{_parse(e){const r=Ue.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==oe.string&&a.parsedType!==oe.number){const n=Ue.objectValues(r);return ae(a,{expected:Ue.joinValues(n),received:a.parsedType,code:Y.invalid_type}),be}if(this._cache||(this._cache=new Set(Ue.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=Ue.objectValues(r);return ae(a,{received:a.data,code:Y.invalid_enum_value,options:n}),be}return qt(e.data)}get enum(){return this._def.values}}Ps.create=(t,e)=>new Ps({values:t,typeName:V.ZodNativeEnum,...Ce(e)});class ka extends Oe{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==oe.promise&&r.common.async===!1)return ae(r,{code:Y.invalid_type,expected:oe.promise,received:r.parsedType}),be;const a=r.parsedType===oe.promise?r.data:Promise.resolve(r.data);return qt(a.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}}ka.create=(t,e)=>new ka({type:t,typeName:V.ZodPromise,...Ce(e)});class Sr extends Oe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===V.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:a}=this._processInputParams(e),n=this._def.effect||null,s={addIssue:o=>{ae(a,o),o.fatal?r.abort():r.dirty()},get path(){return a.path}};if(s.addIssue=s.addIssue.bind(s),n.type==="preprocess"){const o=n.transform(a.data,s);if(a.common.async)return Promise.resolve(o).then(async i=>{if(r.value==="aborted")return be;const l=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return l.status==="aborted"?be:l.status==="dirty"||r.value==="dirty"?$a(l.value):l});{if(r.value==="aborted")return be;const i=this._def.schema._parseSync({data:o,path:a.path,parent:a});return i.status==="aborted"?be:i.status==="dirty"||r.value==="dirty"?$a(i.value):i}}if(n.type==="refinement"){const o=i=>{const l=n.refinement(i,s);if(a.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(a.common.async===!1){const i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?be:(i.status==="dirty"&&r.dirty(),o(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?be:(i.status==="dirty"&&r.dirty(),o(i.value).then(()=>({status:r.value,value:i.value}))))}if(n.type==="transform")if(a.common.async===!1){const o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!Fn(o))return be;const i=n.transform(o.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:a.data,path:a.path,parent:a}).then(o=>Fn(o)?Promise.resolve(n.transform(o.value,s)).then(i=>({status:r.value,value:i})):be);Ue.assertNever(n)}}Sr.create=(t,e,r)=>new Sr({schema:t,typeName:V.ZodEffects,effect:e,...Ce(r)}),Sr.createWithPreprocess=(t,e,r)=>new Sr({schema:e,effect:{type:"preprocess",transform:t},typeName:V.ZodEffects,...Ce(r)});let Ur=class extends Oe{_parse(e){return this._getType(e)===oe.undefined?qt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ur.create=(t,e)=>new Ur({innerType:t,typeName:V.ZodOptional,...Ce(e)});let yn=class extends Oe{_parse(e){return this._getType(e)===oe.null?qt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yn.create=(t,e)=>new yn({innerType:t,typeName:V.ZodNullable,...Ce(e)});let Ts=class extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e);let a=r.data;return r.parsedType===oe.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ts.create=(t,e)=>new Ts({innerType:t,typeName:V.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ce(e)});let xs=class extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return ms(n)?n.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new tr(a.common.issues)},input:a.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new tr(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};xs.create=(t,e)=>new xs({innerType:t,typeName:V.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ce(e)});class ti extends Oe{_parse(e){if(this._getType(e)!==oe.nan){const a=this._getOrReturnCtx(e);return ae(a,{code:Y.invalid_type,expected:oe.nan,received:a.parsedType}),be}return{status:"valid",value:e.data}}}ti.create=t=>new ti({typeName:V.ZodNaN,...Ce(t)});const X$=Symbol("zod_brand");class Ac extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}}class ks extends Oe{_parse(e){const{status:r,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return s.status==="aborted"?be:s.status==="dirty"?(r.dirty(),$a(s.value)):this._def.out._parseAsync({data:s.value,path:a.path,parent:a})})();{const n=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?be:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:a.path,parent:a})}}static create(e,r){return new ks({in:e,out:r,typeName:V.ZodPipeline})}}let Is=class extends Oe{_parse(e){const r=this._def.innerType._parse(e),a=n=>(Fn(n)&&(n.value=Object.freeze(n.value)),n);return ms(r)?r.then(n=>a(n)):a(r)}unwrap(){return this._def.innerType}};Is.create=(t,e)=>new Is({innerType:t,typeName:V.ZodReadonly,...Ce(e)});function rh(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function nh(t,e={},r){return t?Pa.create().superRefine((a,n)=>{const s=t(a);if(s instanceof Promise)return s.then(o=>{if(!o){const i=rh(e,a),l=i.fatal??r??!0;n.addIssue({code:"custom",...i,fatal:l})}});if(!s){const o=rh(e,a),i=o.fatal??r??!0;n.addIssue({code:"custom",...o,fatal:i})}}):Pa.create()}const eS={object:cr.lazycreate};var V;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(V||(V={}));const tS=(t,e={message:`Input not instance of ${t.name}`})=>nh(r=>r instanceof t,e),j=Sa.create,bt=vs.create,rS=ti.create,nS=gn.create,gt=gs.create,aS=Zn.create,sS=Yo.create,oS=ys.create,iS=_s.create,ah=Pa.create,Ia=Vn.create,lS=sn.create,cS=Xo.create,ue=Hn.create,ee=cr.create,uS=cr.strictCreate,Lt=ws.create,sh=Xp.create,dS=bs.create,fS=zr.create,Ca=eh.create,pS=ei.create,hS=Bn.create,mS=xa.create,vS=Es.create,ke=$s.create,qr=Ss.create,gS=Ps.create,yS=ka.create,oh=Sr.create,Q=Ur.create,_S=yn.create,wS=Sr.createWithPreprocess,bS=ks.create,ES=Object.freeze(Object.defineProperty({__proto__:null,BRAND:X$,DIRTY:$a,EMPTY_PATH:R$,INVALID:be,NEVER:be,OK:qt,ParseStatus:Dt,Schema:Oe,ZodAny:Pa,ZodArray:Hn,ZodBigInt:gn,ZodBoolean:gs,ZodBranded:Ac,ZodCatch:xs,ZodDate:Zn,ZodDefault:Ts,ZodDiscriminatedUnion:Xp,ZodEffects:Sr,ZodEnum:Ss,ZodError:tr,get ZodFirstPartyTypeKind(){return V},ZodFunction:xa,ZodIntersection:bs,ZodIssueCode:Y,ZodLazy:Es,ZodLiteral:$s,ZodMap:ei,ZodNaN:ti,ZodNativeEnum:Ps,ZodNever:sn,ZodNull:_s,ZodNullable:yn,ZodNumber:vs,ZodObject:cr,ZodOptional:Ur,ZodParsedType:oe,ZodPipeline:ks,ZodPromise:ka,ZodReadonly:Is,ZodRecord:eh,ZodSchema:Oe,ZodSet:Bn,ZodString:Sa,ZodSymbol:Yo,ZodTransformer:Sr,ZodTuple:zr,ZodType:Oe,ZodUndefined:ys,ZodUnion:ws,ZodUnknown:Vn,ZodVoid:Xo,addIssueToContext:ae,any:ah,array:ue,bigint:nS,boolean:gt,coerce:{string:t=>Sa.create({...t,coerce:!0}),number:t=>vs.create({...t,coerce:!0}),boolean:t=>gs.create({...t,coerce:!0}),bigint:t=>gn.create({...t,coerce:!0}),date:t=>Zn.create({...t,coerce:!0})},custom:nh,date:aS,datetimeRegex:Yp,defaultErrorMap:Ea,discriminatedUnion:sh,effect:oh,enum:qr,function:mS,getErrorMap:Wo,getParsedType:an,instanceof:tS,intersection:dS,isAborted:Ic,isAsync:ms,isDirty:Cc,isValid:Fn,late:eS,lazy:vS,literal:ke,makeIssue:Qo,map:pS,nan:rS,nativeEnum:gS,never:lS,null:iS,nullable:_S,number:bt,object:ee,get objectUtil(){return kc},oboolean:()=>gt().optional(),onumber:()=>bt().optional(),optional:Q,ostring:()=>j().optional(),pipeline:bS,preprocess:wS,promise:yS,quotelessJson:I$,record:Ca,set:hS,setErrorMap:C$,strictObject:uS,string:j,symbol:sS,transformer:oh,tuple:fS,undefined:oS,union:Lt,unknown:Ia,get util(){return Ue},void:cS},Symbol.toStringTag,{value:"Module"})),Cs="2025-06-18",ih=[Cs,"2025-03-26","2024-11-05","2024-10-07"],ri="2.0",lh=Lt([j(),bt().int()]),ch=j(),$S=ee({progressToken:Q(lh)}).passthrough(),ur=ee({_meta:Q($S)}).passthrough(),Bt=ee({method:j(),params:Q(ur)}),Rs=ee({_meta:Q(ee({}).passthrough())}).passthrough(),Fr=ee({method:j(),params:Q(Rs)}),dr=ee({_meta:Q(ee({}).passthrough())}).passthrough(),ni=Lt([j(),bt().int()]),uh=ee({jsonrpc:ke(ri),id:ni}).merge(Bt).strict(),dh=t=>uh.safeParse(t).success,fh=ee({jsonrpc:ke(ri)}).merge(Fr).strict(),SS=t=>fh.safeParse(t).success,ph=ee({jsonrpc:ke(ri),id:ni,result:dr}).strict(),Nc=t=>ph.safeParse(t).success;var rt;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(rt||(rt={}));const hh=ee({jsonrpc:ke(ri),id:ni,error:ee({code:bt().int(),message:j(),data:Q(Ia())})}).strict(),PS=t=>hh.safeParse(t).success,ln=Lt([uh,fh,ph,hh]),_n=dr.strict(),Mc=Fr.extend({method:ke("notifications/cancelled"),params:Rs.extend({requestId:ni,reason:j().optional()})}),Os=ee({name:j(),title:Q(j())}).passthrough(),mh=Os.extend({version:j()}),TS=ee({experimental:Q(ee({}).passthrough()),sampling:Q(ee({}).passthrough()),elicitation:Q(ee({}).passthrough()),roots:Q(ee({listChanged:Q(gt())}).passthrough())}).passthrough(),vh=Bt.extend({method:ke("initialize"),params:ur.extend({protocolVersion:j(),capabilities:TS,clientInfo:mh})}),xS=ee({experimental:Q(ee({}).passthrough()),logging:Q(ee({}).passthrough()),completions:Q(ee({}).passthrough()),prompts:Q(ee({listChanged:Q(gt())}).passthrough()),resources:Q(ee({subscribe:Q(gt()),listChanged:Q(gt())}).passthrough()),tools:Q(ee({listChanged:Q(gt())}).passthrough())}).passthrough(),gh=dr.extend({protocolVersion:j(),capabilities:xS,serverInfo:mh,instructions:Q(j())}),jc=Fr.extend({method:ke("notifications/initialized")}),kS=t=>jc.safeParse(t).success,Dc=Bt.extend({method:ke("ping")}),IS=ee({progress:bt(),total:Q(bt()),message:Q(j())}).passthrough(),Lc=Fr.extend({method:ke("notifications/progress"),params:Rs.merge(IS).extend({progressToken:lh})}),ai=Bt.extend({params:ur.extend({cursor:Q(ch)}).optional()}),si=dr.extend({nextCursor:Q(ch)}),yh=ee({uri:j(),mimeType:Q(j()),_meta:Q(ee({}).passthrough())}).passthrough(),_h=yh.extend({text:j()}),zc=j().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),wh=yh.extend({blob:zc}),bh=Os.extend({uri:j(),description:Q(j()),mimeType:Q(j()),_meta:Q(ee({}).passthrough())}),CS=Os.extend({uriTemplate:j(),description:Q(j()),mimeType:Q(j()),_meta:Q(ee({}).passthrough())}),oi=ai.extend({method:ke("resources/list")}),Eh=si.extend({resources:ue(bh)}),Uc=ai.extend({method:ke("resources/templates/list")}),$h=si.extend({resourceTemplates:ue(CS)}),qc=Bt.extend({method:ke("resources/read"),params:ur.extend({uri:j()})}),Sh=dr.extend({contents:ue(Lt([_h,wh]))}),Ph=Fr.extend({method:ke("notifications/resources/list_changed")}),Th=Bt.extend({method:ke("resources/subscribe"),params:ur.extend({uri:j()})}),xh=Bt.extend({method:ke("resources/unsubscribe"),params:ur.extend({uri:j()})}),kh=Fr.extend({method:ke("notifications/resources/updated"),params:Rs.extend({uri:j()})}),RS=ee({name:j(),description:Q(j()),required:Q(gt())}).passthrough(),OS=Os.extend({description:Q(j()),arguments:Q(ue(RS)),_meta:Q(ee({}).passthrough())}),Fc=ai.extend({method:ke("prompts/list")}),Ih=si.extend({prompts:ue(OS)}),Zc=Bt.extend({method:ke("prompts/get"),params:ur.extend({name:j(),arguments:Q(Ca(j()))})}),Vc=ee({type:ke("text"),text:j(),_meta:Q(ee({}).passthrough())}).passthrough(),Hc=ee({type:ke("image"),data:zc,mimeType:j(),_meta:Q(ee({}).passthrough())}).passthrough(),Bc=ee({type:ke("audio"),data:zc,mimeType:j(),_meta:Q(ee({}).passthrough())}).passthrough(),AS=ee({type:ke("resource"),resource:Lt([_h,wh]),_meta:Q(ee({}).passthrough())}).passthrough(),NS=bh.extend({type:ke("resource_link")}),Ch=Lt([Vc,Hc,Bc,NS,AS]),MS=ee({role:qr(["user","assistant"]),content:Ch}).passthrough(),Rh=dr.extend({description:Q(j()),messages:ue(MS)}),Oh=Fr.extend({method:ke("notifications/prompts/list_changed")}),jS=ee({title:Q(j()),readOnlyHint:Q(gt()),destructiveHint:Q(gt()),idempotentHint:Q(gt()),openWorldHint:Q(gt())}).passthrough(),DS=Os.extend({description:Q(j()),inputSchema:ee({type:ke("object"),properties:Q(ee({}).passthrough()),required:Q(ue(j()))}).passthrough(),outputSchema:Q(ee({type:ke("object"),properties:Q(ee({}).passthrough()),required:Q(ue(j()))}).passthrough()),annotations:Q(jS),_meta:Q(ee({}).passthrough())}),Jc=ai.extend({method:ke("tools/list")}),Ah=si.extend({tools:ue(DS)}),ii=dr.extend({content:ue(Ch).default([]),structuredContent:ee({}).passthrough().optional(),isError:Q(gt())});ii.or(dr.extend({toolResult:Ia()}));const Gc=Bt.extend({method:ke("tools/call"),params:ur.extend({name:j(),arguments:Q(Ca(Ia()))})}),Nh=Fr.extend({method:ke("notifications/tools/list_changed")}),Mh=qr(["debug","info","notice","warning","error","critical","alert","emergency"]),Kc=Bt.extend({method:ke("logging/setLevel"),params:ur.extend({level:Mh})}),jh=Fr.extend({method:ke("notifications/message"),params:Rs.extend({level:Mh,logger:Q(j()),data:Ia()})}),LS=ee({name:j().optional()}).passthrough(),zS=ee({hints:Q(ue(LS)),costPriority:Q(bt().min(0).max(1)),speedPriority:Q(bt().min(0).max(1)),intelligencePriority:Q(bt().min(0).max(1))}).passthrough(),US=ee({role:qr(["user","assistant"]),content:Lt([Vc,Hc,Bc])}).passthrough(),Dh=Bt.extend({method:ke("sampling/createMessage"),params:ur.extend({messages:ue(US),systemPrompt:Q(j()),includeContext:Q(qr(["none","thisServer","allServers"])),temperature:Q(bt()),maxTokens:bt().int(),stopSequences:Q(ue(j())),metadata:Q(ee({}).passthrough()),modelPreferences:Q(zS)})}),Wc=dr.extend({model:j(),stopReason:Q(qr(["endTurn","stopSequence","maxTokens"]).or(j())),role:qr(["user","assistant"]),content:sh("type",[Vc,Hc,Bc])}),qS=ee({type:ke("boolean"),title:Q(j()),description:Q(j()),default:Q(gt())}).passthrough(),FS=ee({type:ke("string"),title:Q(j()),description:Q(j()),minLength:Q(bt()),maxLength:Q(bt()),format:Q(qr(["email","uri","date","date-time"]))}).passthrough(),ZS=ee({type:qr(["number","integer"]),title:Q(j()),description:Q(j()),minimum:Q(bt()),maximum:Q(bt())}).passthrough(),VS=ee({type:ke("string"),title:Q(j()),description:Q(j()),enum:ue(j()),enumNames:Q(ue(j()))}).passthrough(),HS=Lt([qS,FS,ZS,VS]),Lh=Bt.extend({method:ke("elicitation/create"),params:ur.extend({message:j(),requestedSchema:ee({type:ke("object"),properties:Ca(j(),HS),required:Q(ue(j()))}).passthrough()})}),Qc=dr.extend({action:qr(["accept","decline","cancel"]),content:Q(Ca(j(),Ia()))}),BS=ee({type:ke("ref/resource"),uri:j()}).passthrough(),JS=ee({type:ke("ref/prompt"),name:j()}).passthrough(),Yc=Bt.extend({method:ke("completion/complete"),params:ur.extend({ref:Lt([JS,BS]),argument:ee({name:j(),value:j()}).passthrough(),context:Q(ee({arguments:Q(Ca(j(),j()))}))})}),zh=dr.extend({completion:ee({values:ue(j()).max(100),total:Q(bt().int()),hasMore:Q(gt())}).passthrough()}),GS=ee({uri:j().startsWith("file://"),name:Q(j()),_meta:Q(ee({}).passthrough())}).passthrough(),Uh=Bt.extend({method:ke("roots/list")}),Xc=dr.extend({roots:ue(GS)}),qh=Fr.extend({method:ke("notifications/roots/list_changed")});Lt([Dc,vh,Yc,Kc,Zc,Fc,oi,Uc,qc,Th,xh,Gc,Jc]),Lt([Mc,Lc,jc,qh]),Lt([_n,Wc,Qc,Xc]),Lt([Dc,Dh,Lh,Uh]),Lt([Mc,Lc,jh,kh,Ph,Nh,Oh]),Lt([_n,gh,zh,Rh,Ih,Eh,$h,Sh,ii,Ah]);class st extends Error{constructor(e,r,a){super(`MCP error ${e}: ${r}`),this.code=e,this.data=a,this.name="McpError"}}const KS=6e4;class Fh{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Mc,r=>{const a=this._requestHandlerAbortControllers.get(r.params.requestId);a==null||a.abort(r.params.reason)}),this.setNotificationHandler(Lc,r=>{this._onprogress(r)}),this.setRequestHandler(Dc,r=>({}))}_setupTimeout(e,r,a,n,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,r),startTime:Date.now(),timeout:r,maxTotalTimeout:a,resetTimeoutOnProgress:s,onTimeout:n})}_resetTimeout(e){const r=this._timeoutInfo.get(e);if(!r)return!1;const a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new st(rt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){const r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,a,n;this._transport=e;const s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s==null||s(),this._onclose()};const o=(a=this.transport)===null||a===void 0?void 0:a.onerror;this._transport.onerror=l=>{o==null||o(l),this._onerror(l)};const i=(n=this._transport)===null||n===void 0?void 0:n.onmessage;this._transport.onmessage=(l,c)=>{i==null||i(l,c),Nc(l)||PS(l)?this._onresponse(l):dh(l)?this._onrequest(l,c):SS(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;const r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);const a=new st(rt.ConnectionClosed,"Connection closed");for(const n of r.values())n(a)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;const a=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){var a,n,s,o;const i=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler;if(i===void 0){(n=this._transport)===null||n===void 0||n.send({jsonrpc:"2.0",id:e.id,error:{code:rt.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}const l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);const c={signal:l.signal,sessionId:(s=this._transport)===null||s===void 0?void 0:s.sessionId,_meta:(o=e.params)===null||o===void 0?void 0:o._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,h,g)=>this.request(u,h,{...g,relatedRequestId:e.id}),authInfo:r==null?void 0:r.authInfo,requestId:e.id,requestInfo:r==null?void 0:r.requestInfo};Promise.resolve().then(()=>i(e,c)).then(u=>{var h;if(!l.signal.aborted)return(h=this._transport)===null||h===void 0?void 0:h.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var h,g;if(!l.signal.aborted)return(h=this._transport)===null||h===void 0?void 0:h.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:rt.InternalError,message:(g=u.message)!==null&&g!==void 0?g:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:r,...a}=e.params,n=Number(r),s=this._progressHandlers.get(n);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const o=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(l){o(l);return}s(a)}_onresponse(e){const r=Number(e.id),a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Nc(e))a(e);else{const n=new st(e.error.code,e.error.message,e.error.data);a(n)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,a){const{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}=a??{};return new Promise((i,l)=>{var c,u,h,g,d,f;if(!this._transport){l(new Error("Not connected"));return}((c=this._options)===null||c===void 0?void 0:c.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(u=a==null?void 0:a.signal)===null||u===void 0||u.throwIfAborted();const v=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:v};a!=null&&a.onprogress&&(this._progressHandlers.set(v,a.onprogress),m.params={...e.params,_meta:{...((h=e.params)===null||h===void 0?void 0:h._meta)||{},progressToken:v}});const p=w=>{var E;this._responseHandlers.delete(v),this._progressHandlers.delete(v),this._cleanupTimeout(v),(E=this._transport)===null||E===void 0||E.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:v,reason:String(w)}},{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`))),l(w)};this._responseHandlers.set(v,w=>{var E;if(!(!((E=a==null?void 0:a.signal)===null||E===void 0)&&E.aborted)){if(w instanceof Error)return l(w);try{const P=r.parse(w.result);i(P)}catch(P){l(P)}}}),(g=a==null?void 0:a.signal)===null||g===void 0||g.addEventListener("abort",()=>{var w;p((w=a==null?void 0:a.signal)===null||w===void 0?void 0:w.reason)});const y=(d=a==null?void 0:a.timeout)!==null&&d!==void 0?d:KS,_=()=>p(new st(rt.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(v,y,a==null?void 0:a.maxTotalTimeout,_,(f=a==null?void 0:a.resetTimeoutOnProgress)!==null&&f!==void 0?f:!1),this._transport.send(m,{relatedRequestId:n,resumptionToken:s,onresumptiontoken:o}).catch(w=>{this._cleanupTimeout(v),l(w)})})}async notification(e,r){var a,n;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((n=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&n!==void 0?n:[]).includes(e.method)&&!e.params&&!(r!=null&&r.relatedRequestId)){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;const c={...e,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(c,r).catch(u=>this._onerror(u))});return}const i={...e,jsonrpc:"2.0"};await this._transport.send(i,r)}setRequestHandler(e,r){const a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(n,s)=>Promise.resolve(r(e.parse(n),s)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(r(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}function Zh(t,e){return Object.entries(e).reduce((r,[a,n])=>(n&&typeof n=="object"?r[a]=r[a]?{...r[a],...n}:n:r[a]=n,r),{...t})}var eu={exports:{}};/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */(function(t,e){(function(r,a){a(e)})(es,function(r){function a(){for(var k=arguments.length,$=Array(k),I=0;I<k;I++)$[I]=arguments[I];if($.length>1){$[0]=$[0].slice(0,-1);for(var U=$.length-1,q=1;q<U;++q)$[q]=$[q].slice(1,-1);return $[U]=$[U].slice(1),$.join("")}else return $[0]}function n(k){return"(?:"+k+")"}function s(k){return k===void 0?"undefined":k===null?"null":Object.prototype.toString.call(k).split(" ").pop().split("]").shift().toLowerCase()}function o(k){return k.toUpperCase()}function i(k){return k!=null?k instanceof Array?k:typeof k.length!="number"||k.split||k.setInterval||k.call?[k]:Array.prototype.slice.call(k):[]}function l(k,$){var I=k;if($)for(var U in $)I[U]=$[U];return I}function c(k){var $="[A-Za-z]",I="[0-9]",U=a(I,"[A-Fa-f]"),q=n(n("%[EFef]"+U+"%"+U+U+"%"+U+U)+"|"+n("%[89A-Fa-f]"+U+"%"+U+U)+"|"+n("%"+U+U)),ye="[\\:\\/\\?\\#\\[\\]\\@]",_e="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",qe=a(ye,_e),it=k?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",_t=k?"[\\uE000-\\uF8FF]":"[]",ze=a($,I,"[\\-\\.\\_\\~]",it);n($+a($,I,"[\\+\\-\\.]")+"*"),n(n(q+"|"+a(ze,_e,"[\\:]"))+"*");var nt=n(n("25[0-5]")+"|"+n("2[0-4]"+I)+"|"+n("1"+I+I)+"|"+n("0?[1-9]"+I)+"|0?0?"+I),wt=n(nt+"\\."+nt+"\\."+nt+"\\."+nt),xe=n(U+"{1,4}"),dt=n(n(xe+"\\:"+xe)+"|"+wt),Pt=n(n(xe+"\\:")+"{6}"+dt),ft=n("\\:\\:"+n(xe+"\\:")+"{5}"+dt),Mn=n(n(xe)+"?\\:\\:"+n(xe+"\\:")+"{4}"+dt),Yr=n(n(n(xe+"\\:")+"{0,1}"+xe)+"?\\:\\:"+n(xe+"\\:")+"{3}"+dt),Xr=n(n(n(xe+"\\:")+"{0,2}"+xe)+"?\\:\\:"+n(xe+"\\:")+"{2}"+dt),Xa=n(n(n(xe+"\\:")+"{0,3}"+xe)+"?\\:\\:"+xe+"\\:"+dt),ua=n(n(n(xe+"\\:")+"{0,4}"+xe)+"?\\:\\:"+dt),_r=n(n(n(xe+"\\:")+"{0,5}"+xe)+"?\\:\\:"+xe),en=n(n(n(xe+"\\:")+"{0,6}"+xe)+"?\\:\\:"),da=n([Pt,ft,Mn,Yr,Xr,Xa,ua,_r,en].join("|")),fn=n(n(ze+"|"+q)+"+");n("[vV]"+U+"+\\."+a(ze,_e,"[\\:]")+"+"),n(n(q+"|"+a(ze,_e))+"*");var Po=n(q+"|"+a(ze,_e,"[\\:\\@]"));return n(n(q+"|"+a(ze,_e,"[\\@]"))+"+"),n(n(Po+"|"+a("[\\/\\?]",_t))+"*"),{NOT_SCHEME:new RegExp(a("[^]",$,I,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(a("[^\\%\\:]",ze,_e),"g"),NOT_HOST:new RegExp(a("[^\\%\\[\\]\\:]",ze,_e),"g"),NOT_PATH:new RegExp(a("[^\\%\\/\\:\\@]",ze,_e),"g"),NOT_PATH_NOSCHEME:new RegExp(a("[^\\%\\/\\@]",ze,_e),"g"),NOT_QUERY:new RegExp(a("[^\\%]",ze,_e,"[\\:\\@\\/\\?]",_t),"g"),NOT_FRAGMENT:new RegExp(a("[^\\%]",ze,_e,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(a("[^]",ze,_e),"g"),UNRESERVED:new RegExp(ze,"g"),OTHER_CHARS:new RegExp(a("[^\\%]",ze,qe),"g"),PCT_ENCODED:new RegExp(q,"g"),IPV4ADDRESS:new RegExp("^("+wt+")$"),IPV6ADDRESS:new RegExp("^\\[?("+da+")"+n(n("\\%25|\\%(?!"+U+"{2})")+"("+fn+")")+"?\\]?$")}}var u=c(!1),h=c(!0),g=function(){function k($,I){var U=[],q=!0,ye=!1,_e=void 0;try{for(var qe=$[Symbol.iterator](),it;!(q=(it=qe.next()).done)&&(U.push(it.value),!(I&&U.length===I));q=!0);}catch(_t){ye=!0,_e=_t}finally{try{!q&&qe.return&&qe.return()}finally{if(ye)throw _e}}return U}return function($,I){if(Array.isArray($))return $;if(Symbol.iterator in Object($))return k($,I);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),d=function(k){if(Array.isArray(k)){for(var $=0,I=Array(k.length);$<k.length;$++)I[$]=k[$];return I}else return Array.from(k)},f=2147483647,v=36,m=1,p=26,y=38,_=700,w=72,E=128,P="-",T=/^xn--/,O=/[^\0-\x7E]/,M=/[\x2E\u3002\uFF0E\uFF61]/g,J={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},H=v-m,G=Math.floor,F=String.fromCharCode;function Z(k){throw new RangeError(J[k])}function te(k,$){for(var I=[],U=k.length;U--;)I[U]=$(k[U]);return I}function pe(k,$){var I=k.split("@"),U="";I.length>1&&(U=I[0]+"@",k=I[1]),k=k.replace(M,".");var q=k.split("."),ye=te(q,$).join(".");return U+ye}function ve(k){for(var $=[],I=0,U=k.length;I<U;){var q=k.charCodeAt(I++);if(q>=55296&&q<=56319&&I<U){var ye=k.charCodeAt(I++);(ye&64512)==56320?$.push(((q&1023)<<10)+(ye&1023)+65536):($.push(q),I--)}else $.push(q)}return $}var N=function($){return String.fromCodePoint.apply(String,d($))},ie=function($){return $-48<10?$-22:$-65<26?$-65:$-97<26?$-97:v},D=function($,I){return $+22+75*($<26)-((I!=0)<<5)},C=function($,I,U){var q=0;for($=U?G($/_):$>>1,$+=G($/I);$>H*p>>1;q+=v)$=G($/H);return G(q+(H+1)*$/($+y))},z=function($){var I=[],U=$.length,q=0,ye=E,_e=w,qe=$.lastIndexOf(P);qe<0&&(qe=0);for(var it=0;it<qe;++it)$.charCodeAt(it)>=128&&Z("not-basic"),I.push($.charCodeAt(it));for(var _t=qe>0?qe+1:0;_t<U;){for(var ze=q,nt=1,wt=v;;wt+=v){_t>=U&&Z("invalid-input");var xe=ie($.charCodeAt(_t++));(xe>=v||xe>G((f-q)/nt))&&Z("overflow"),q+=xe*nt;var dt=wt<=_e?m:wt>=_e+p?p:wt-_e;if(xe<dt)break;var Pt=v-dt;nt>G(f/Pt)&&Z("overflow"),nt*=Pt}var ft=I.length+1;_e=C(q-ze,ft,ze==0),G(q/ft)>f-ye&&Z("overflow"),ye+=G(q/ft),q%=ft,I.splice(q++,0,ye)}return String.fromCodePoint.apply(String,I)},A=function($){var I=[];$=ve($);var U=$.length,q=E,ye=0,_e=w,qe=!0,it=!1,_t=void 0;try{for(var ze=$[Symbol.iterator](),nt;!(qe=(nt=ze.next()).done);qe=!0){var wt=nt.value;wt<128&&I.push(F(wt))}}catch(To){it=!0,_t=To}finally{try{!qe&&ze.return&&ze.return()}finally{if(it)throw _t}}var xe=I.length,dt=xe;for(xe&&I.push(P);dt<U;){var Pt=f,ft=!0,Mn=!1,Yr=void 0;try{for(var Xr=$[Symbol.iterator](),Xa;!(ft=(Xa=Xr.next()).done);ft=!0){var ua=Xa.value;ua>=q&&ua<Pt&&(Pt=ua)}}catch(To){Mn=!0,Yr=To}finally{try{!ft&&Xr.return&&Xr.return()}finally{if(Mn)throw Yr}}var _r=dt+1;Pt-q>G((f-ye)/_r)&&Z("overflow"),ye+=(Pt-q)*_r,q=Pt;var en=!0,da=!1,fn=void 0;try{for(var Po=$[Symbol.iterator](),uw;!(en=(uw=Po.next()).done);en=!0){var dw=uw.value;if(dw<q&&++ye>f&&Z("overflow"),dw==q){for(var wl=ye,bl=v;;bl+=v){var El=bl<=_e?m:bl>=_e+p?p:bl-_e;if(wl<El)break;var fw=wl-El,pw=v-El;I.push(F(D(El+fw%pw,0))),wl=G(fw/pw)}I.push(F(D(wl,0))),_e=C(ye,_r,dt==xe),ye=0,++dt}}}catch(To){da=!0,fn=To}finally{try{!en&&Po.return&&Po.return()}finally{if(da)throw fn}}++ye,++q}return I.join("")},b=function($){return pe($,function(I){return T.test(I)?z(I.slice(4).toLowerCase()):I})},x=function($){return pe($,function(I){return O.test(I)?"xn--"+A(I):I})},L={version:"2.1.0",ucs2:{decode:ve,encode:N},decode:z,encode:A,toASCII:x,toUnicode:b},W={};function X(k){var $=k.charCodeAt(0),I=void 0;return $<16?I="%0"+$.toString(16).toUpperCase():$<128?I="%"+$.toString(16).toUpperCase():$<2048?I="%"+($>>6|192).toString(16).toUpperCase()+"%"+($&63|128).toString(16).toUpperCase():I="%"+($>>12|224).toString(16).toUpperCase()+"%"+($>>6&63|128).toString(16).toUpperCase()+"%"+($&63|128).toString(16).toUpperCase(),I}function $e(k){for(var $="",I=0,U=k.length;I<U;){var q=parseInt(k.substr(I+1,2),16);if(q<128)$+=String.fromCharCode(q),I+=3;else if(q>=194&&q<224){if(U-I>=6){var ye=parseInt(k.substr(I+4,2),16);$+=String.fromCharCode((q&31)<<6|ye&63)}else $+=k.substr(I,6);I+=6}else if(q>=224){if(U-I>=9){var _e=parseInt(k.substr(I+4,2),16),qe=parseInt(k.substr(I+7,2),16);$+=String.fromCharCode((q&15)<<12|(_e&63)<<6|qe&63)}else $+=k.substr(I,9);I+=9}else $+=k.substr(I,3),I+=3}return $}function le(k,$){function I(U){var q=$e(U);return q.match($.UNRESERVED)?q:U}return k.scheme&&(k.scheme=String(k.scheme).replace($.PCT_ENCODED,I).toLowerCase().replace($.NOT_SCHEME,"")),k.userinfo!==void 0&&(k.userinfo=String(k.userinfo).replace($.PCT_ENCODED,I).replace($.NOT_USERINFO,X).replace($.PCT_ENCODED,o)),k.host!==void 0&&(k.host=String(k.host).replace($.PCT_ENCODED,I).toLowerCase().replace($.NOT_HOST,X).replace($.PCT_ENCODED,o)),k.path!==void 0&&(k.path=String(k.path).replace($.PCT_ENCODED,I).replace(k.scheme?$.NOT_PATH:$.NOT_PATH_NOSCHEME,X).replace($.PCT_ENCODED,o)),k.query!==void 0&&(k.query=String(k.query).replace($.PCT_ENCODED,I).replace($.NOT_QUERY,X).replace($.PCT_ENCODED,o)),k.fragment!==void 0&&(k.fragment=String(k.fragment).replace($.PCT_ENCODED,I).replace($.NOT_FRAGMENT,X).replace($.PCT_ENCODED,o)),k}function ge(k){return k.replace(/^0*(.*)/,"$1")||"0"}function mt(k,$){var I=k.match($.IPV4ADDRESS)||[],U=g(I,2),q=U[1];return q?q.split(".").map(ge).join("."):k}function Ie(k,$){var I=k.match($.IPV6ADDRESS)||[],U=g(I,3),q=U[1],ye=U[2];if(q){for(var _e=q.toLowerCase().split("::").reverse(),qe=g(_e,2),it=qe[0],_t=qe[1],ze=_t?_t.split(":").map(ge):[],nt=it.split(":").map(ge),wt=$.IPV4ADDRESS.test(nt[nt.length-1]),xe=wt?7:8,dt=nt.length-xe,Pt=Array(xe),ft=0;ft<xe;++ft)Pt[ft]=ze[ft]||nt[dt+ft]||"";wt&&(Pt[xe-1]=mt(Pt[xe-1],$));var Mn=Pt.reduce(function(_r,en,da){if(!en||en==="0"){var fn=_r[_r.length-1];fn&&fn.index+fn.length===da?fn.length++:_r.push({index:da,length:1})}return _r},[]),Yr=Mn.sort(function(_r,en){return en.length-_r.length})[0],Xr=void 0;if(Yr&&Yr.length>1){var Xa=Pt.slice(0,Yr.index),ua=Pt.slice(Yr.index+Yr.length);Xr=Xa.join(":")+"::"+ua.join(":")}else Xr=Pt.join(":");return ye&&(Xr+="%"+ye),Xr}else return k}var he=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Ae="".match(/(){0}/)[1]===void 0;function Ne(k){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},I={},U=$.iri!==!1?h:u;$.reference==="suffix"&&(k=($.scheme?$.scheme+":":"")+"//"+k);var q=k.match(he);if(q){Ae?(I.scheme=q[1],I.userinfo=q[3],I.host=q[4],I.port=parseInt(q[5],10),I.path=q[6]||"",I.query=q[7],I.fragment=q[8],isNaN(I.port)&&(I.port=q[5])):(I.scheme=q[1]||void 0,I.userinfo=k.indexOf("@")!==-1?q[3]:void 0,I.host=k.indexOf("//")!==-1?q[4]:void 0,I.port=parseInt(q[5],10),I.path=q[6]||"",I.query=k.indexOf("?")!==-1?q[7]:void 0,I.fragment=k.indexOf("#")!==-1?q[8]:void 0,isNaN(I.port)&&(I.port=k.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?q[4]:void 0)),I.host&&(I.host=Ie(mt(I.host,U),U)),I.scheme===void 0&&I.userinfo===void 0&&I.host===void 0&&I.port===void 0&&!I.path&&I.query===void 0?I.reference="same-document":I.scheme===void 0?I.reference="relative":I.fragment===void 0?I.reference="absolute":I.reference="uri",$.reference&&$.reference!=="suffix"&&$.reference!==I.reference&&(I.error=I.error||"URI is not a "+$.reference+" reference.");var ye=W[($.scheme||I.scheme||"").toLowerCase()];if(!$.unicodeSupport&&(!ye||!ye.unicodeSupport)){if(I.host&&($.domainHost||ye&&ye.domainHost))try{I.host=L.toASCII(I.host.replace(U.PCT_ENCODED,$e).toLowerCase())}catch(_e){I.error=I.error||"Host's domain name can not be converted to ASCII via punycode: "+_e}le(I,u)}else le(I,U);ye&&ye.parse&&ye.parse(I,$)}else I.error=I.error||"URI can not be parsed.";return I}function Te(k,$){var I=$.iri!==!1?h:u,U=[];return k.userinfo!==void 0&&(U.push(k.userinfo),U.push("@")),k.host!==void 0&&U.push(Ie(mt(String(k.host),I),I).replace(I.IPV6ADDRESS,function(q,ye,_e){return"["+ye+(_e?"%25"+_e:"")+"]"})),(typeof k.port=="number"||typeof k.port=="string")&&(U.push(":"),U.push(String(k.port))),U.length?U.join(""):void 0}var tt=/^\.\.?\//,Ze=/^\/\.(\/|$)/,re=/^\/\.\.(\/|$)/,Le=/^\/?(?:.|\n)*?(?=\/|$)/;function He(k){for(var $=[];k.length;)if(k.match(tt))k=k.replace(tt,"");else if(k.match(Ze))k=k.replace(Ze,"/");else if(k.match(re))k=k.replace(re,"/"),$.pop();else if(k==="."||k==="..")k="";else{var I=k.match(Le);if(I){var U=I[0];k=k.slice(U.length),$.push(U)}else throw new Error("Unexpected dot segment condition")}return $.join("")}function Ee(k){var $=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},I=$.iri?h:u,U=[],q=W[($.scheme||k.scheme||"").toLowerCase()];if(q&&q.serialize&&q.serialize(k,$),k.host&&!I.IPV6ADDRESS.test(k.host)){if($.domainHost||q&&q.domainHost)try{k.host=$.iri?L.toUnicode(k.host):L.toASCII(k.host.replace(I.PCT_ENCODED,$e).toLowerCase())}catch(qe){k.error=k.error||"Host's domain name can not be converted to "+($.iri?"Unicode":"ASCII")+" via punycode: "+qe}}le(k,I),$.reference!=="suffix"&&k.scheme&&(U.push(k.scheme),U.push(":"));var ye=Te(k,$);if(ye!==void 0&&($.reference!=="suffix"&&U.push("//"),U.push(ye),k.path&&k.path.charAt(0)!=="/"&&U.push("/")),k.path!==void 0){var _e=k.path;!$.absolutePath&&(!q||!q.absolutePath)&&(_e=He(_e)),ye===void 0&&(_e=_e.replace(/^\/\//,"/%2F")),U.push(_e)}return k.query!==void 0&&(U.push("?"),U.push(k.query)),k.fragment!==void 0&&(U.push("#"),U.push(k.fragment)),U.join("")}function We(k,$){var I=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},U=arguments[3],q={};return U||(k=Ne(Ee(k,I),I),$=Ne(Ee($,I),I)),I=I||{},!I.tolerant&&$.scheme?(q.scheme=$.scheme,q.userinfo=$.userinfo,q.host=$.host,q.port=$.port,q.path=He($.path||""),q.query=$.query):($.userinfo!==void 0||$.host!==void 0||$.port!==void 0?(q.userinfo=$.userinfo,q.host=$.host,q.port=$.port,q.path=He($.path||""),q.query=$.query):($.path?($.path.charAt(0)==="/"?q.path=He($.path):((k.userinfo!==void 0||k.host!==void 0||k.port!==void 0)&&!k.path?q.path="/"+$.path:k.path?q.path=k.path.slice(0,k.path.lastIndexOf("/")+1)+$.path:q.path=$.path,q.path=He(q.path)),q.query=$.query):(q.path=k.path,$.query!==void 0?q.query=$.query:q.query=k.query),q.userinfo=k.userinfo,q.host=k.host,q.port=k.port),q.scheme=k.scheme),q.fragment=$.fragment,q}function Yt(k,$,I){var U=l({scheme:"null"},I);return Ee(We(Ne(k,U),Ne($,U),U,!0),U)}function Ct(k,$){return typeof k=="string"?k=Ee(Ne(k,$),$):s(k)==="object"&&(k=Ne(Ee(k,$),$)),k}function yt(k,$,I){return typeof k=="string"?k=Ee(Ne(k,I),I):s(k)==="object"&&(k=Ee(k,I)),typeof $=="string"?$=Ee(Ne($,I),I):s($)==="object"&&($=Ee($,I)),k===$}function Xt(k,$){return k&&k.toString().replace(!$||!$.iri?u.ESCAPE:h.ESCAPE,X)}function Rt(k,$){return k&&k.toString().replace(!$||!$.iri?u.PCT_ENCODED:h.PCT_ENCODED,$e)}var er={scheme:"http",domainHost:!0,parse:function($,I){return $.host||($.error=$.error||"HTTP URIs must have a host."),$},serialize:function($,I){var U=String($.scheme).toLowerCase()==="https";return($.port===(U?443:80)||$.port==="")&&($.port=void 0),$.path||($.path="/"),$}},dn={scheme:"https",domainHost:er.domainHost,parse:er.parse,serialize:er.serialize};function ia(k){return typeof k.secure=="boolean"?k.secure:String(k.scheme).toLowerCase()==="wss"}var ut={scheme:"ws",domainHost:!0,parse:function($,I){var U=$;return U.secure=ia(U),U.resourceName=(U.path||"/")+(U.query?"?"+U.query:""),U.path=void 0,U.query=void 0,U},serialize:function($,I){if(($.port===(ia($)?443:80)||$.port==="")&&($.port=void 0),typeof $.secure=="boolean"&&($.scheme=$.secure?"wss":"ws",$.secure=void 0),$.resourceName){var U=$.resourceName.split("?"),q=g(U,2),ye=q[0],_e=q[1];$.path=ye&&ye!=="/"?ye:void 0,$.query=_e,$.resourceName=void 0}return $.fragment=void 0,$}},vr={scheme:"wss",domainHost:ut.domainHost,parse:ut.parse,serialize:ut.serialize},Or={},_o="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",gr="[0-9A-Fa-f]",bf=n(n("%[EFef]"+gr+"%"+gr+gr+"%"+gr+gr)+"|"+n("%[89A-Fa-f]"+gr+"%"+gr+gr)+"|"+n("%"+gr+gr)),Qa="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",wo="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",bo=a(wo,'[\\"\\\\]'),Eo="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",An=new RegExp(_o,"g"),Ot=new RegExp(bf,"g"),$o=new RegExp(a("[^]",Qa,"[\\.]",'[\\"]',bo),"g"),So=new RegExp(a("[^]",_o,Eo),"g"),yr=So;function Ya(k){var $=$e(k);return $.match(An)?$:k}var we={scheme:"mailto",parse:function($,I){var U=$,q=U.to=U.path?U.path.split(","):[];if(U.path=void 0,U.query){for(var ye=!1,_e={},qe=U.query.split("&"),it=0,_t=qe.length;it<_t;++it){var ze=qe[it].split("=");switch(ze[0]){case"to":for(var nt=ze[1].split(","),wt=0,xe=nt.length;wt<xe;++wt)q.push(nt[wt]);break;case"subject":U.subject=Rt(ze[1],I);break;case"body":U.body=Rt(ze[1],I);break;default:ye=!0,_e[Rt(ze[0],I)]=Rt(ze[1],I);break}}ye&&(U.headers=_e)}U.query=void 0;for(var dt=0,Pt=q.length;dt<Pt;++dt){var ft=q[dt].split("@");if(ft[0]=Rt(ft[0]),I.unicodeSupport)ft[1]=Rt(ft[1],I).toLowerCase();else try{ft[1]=L.toASCII(Rt(ft[1],I).toLowerCase())}catch(Mn){U.error=U.error||"Email address's domain name can not be converted to ASCII via punycode: "+Mn}q[dt]=ft.join("@")}return U},serialize:function($,I){var U=$,q=i($.to);if(q){for(var ye=0,_e=q.length;ye<_e;++ye){var qe=String(q[ye]),it=qe.lastIndexOf("@"),_t=qe.slice(0,it).replace(Ot,Ya).replace(Ot,o).replace($o,X),ze=qe.slice(it+1);try{ze=I.iri?L.toUnicode(ze):L.toASCII(Rt(ze,I).toLowerCase())}catch(dt){U.error=U.error||"Email address's domain name can not be converted to "+(I.iri?"Unicode":"ASCII")+" via punycode: "+dt}q[ye]=_t+"@"+ze}U.path=q.join(",")}var nt=$.headers=$.headers||{};$.subject&&(nt.subject=$.subject),$.body&&(nt.body=$.body);var wt=[];for(var xe in nt)nt[xe]!==Or[xe]&&wt.push(xe.replace(Ot,Ya).replace(Ot,o).replace(So,X)+"="+nt[xe].replace(Ot,Ya).replace(Ot,o).replace(yr,X));return wt.length&&(U.query=wt.join("&")),U}},It=/^([^\:]+)\:(.*)/,Nn={scheme:"urn",parse:function($,I){var U=$.path&&$.path.match(It),q=$;if(U){var ye=I.scheme||q.scheme||"urn",_e=U[1].toLowerCase(),qe=U[2],it=ye+":"+(I.nid||_e),_t=W[it];q.nid=_e,q.nss=qe,q.path=void 0,_t&&(q=_t.parse(q,I))}else q.error=q.error||"URN can not be parsed.";return q},serialize:function($,I){var U=I.scheme||$.scheme||"urn",q=$.nid,ye=U+":"+(I.nid||q),_e=W[ye];_e&&($=_e.serialize($,I));var qe=$,it=$.nss;return qe.path=(q||I.nid)+":"+it,qe}},la=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ca={scheme:"urn:uuid",parse:function($,I){var U=$;return U.uuid=U.nss,U.nss=void 0,!I.tolerant&&(!U.uuid||!U.uuid.match(la))&&(U.error=U.error||"UUID is not valid."),U},serialize:function($,I){var U=$;return U.nss=($.uuid||"").toLowerCase(),U}};W[er.scheme]=er,W[dn.scheme]=dn,W[ut.scheme]=ut,W[vr.scheme]=vr,W[we.scheme]=we,W[Nn.scheme]=Nn,W[ca.scheme]=ca,r.SCHEMES=W,r.pctEncChar=X,r.pctDecChars=$e,r.parse=Ne,r.removeDotSegments=He,r.serialize=Ee,r.resolveComponents=We,r.resolve=Yt,r.normalize=Ct,r.equal=yt,r.escapeComponent=Xt,r.unescapeComponent=Rt,Object.defineProperty(r,"__esModule",{value:!0})})})(eu,eu.exports);var WS=eu.exports,QS=function(e){for(var r=0,a=e.length,n=0,s;n<a;)r++,s=e.charCodeAt(n++),s>=55296&&s<=56319&&n<a&&(s=e.charCodeAt(n),(s&64512)==56320&&n++);return r},Ra={copy:YS,checkDataType:tu,checkDataTypes:XS,coerceToTypes:eP,toHash:ru,getProperty:nu,escapeQuotes:au,equal:ns,ucs2length:QS,varOccurences:nP,varReplace:aP,schemaHasRules:sP,schemaHasRulesExcept:oP,schemaUnknownRules:iP,toQuotedString:su,getPathExpr:lP,getPath:cP,getData:fP,unescapeFragment:pP,unescapeJsonPointer:iu,escapeFragment:hP,escapeJsonPointer:ou};function YS(t,e){e=e||{};for(var r in t)e[r]=t[r];return e}function tu(t,e,r,a){var n=a?" !== ":" === ",s=a?" || ":" && ",o=a?"!":"",i=a?"":"!";switch(t){case"null":return e+n+"null";case"array":return o+"Array.isArray("+e+")";case"object":return"("+o+e+s+"typeof "+e+n+'"object"'+s+i+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+n+'"number"'+s+i+"("+e+" % 1)"+s+e+n+e+(r?s+o+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+n+'"'+t+'"'+(r?s+o+"isFinite("+e+")":"")+")";default:return"typeof "+e+n+'"'+t+'"'}}function XS(t,e,r){switch(t.length){case 1:return tu(t[0],e,r,!0);default:var a="",n=ru(t);n.array&&n.object&&(a=n.null?"(":"(!"+e+" || ",a+="typeof "+e+' !== "object")',delete n.null,delete n.array,delete n.object),n.number&&delete n.integer;for(var s in n)a+=(a?" && ":"")+tu(s,e,r,!0);return a}}var Vh=ru(["string","number","integer","boolean","null"]);function eP(t,e){if(Array.isArray(e)){for(var r=[],a=0;a<e.length;a++){var n=e[a];(Vh[n]||t==="array"&&n==="array")&&(r[r.length]=n)}if(r.length)return r}else{if(Vh[e])return[e];if(t==="array"&&e==="array")return["array"]}}function ru(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!0;return e}var tP=/^[a-z$_][a-z$_0-9]*$/i,rP=/'|\\/g;function nu(t){return typeof t=="number"?"["+t+"]":tP.test(t)?"."+t:"['"+au(t)+"']"}function au(t){return t.replace(rP,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function nP(t,e){e+="[^0-9]";var r=t.match(new RegExp(e,"g"));return r?r.length:0}function aP(t,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),t.replace(new RegExp(e,"g"),r+"$1")}function sP(t,e){if(typeof t=="boolean")return!t;for(var r in t)if(e[r])return!0}function oP(t,e,r){if(typeof t=="boolean")return!t&&r!="not";for(var a in t)if(a!=r&&e[a])return!0}function iP(t,e){if(typeof t!="boolean"){for(var r in t)if(!e[r])return r}}function su(t){return"'"+au(t)+"'"}function lP(t,e,r,a){var n=r?"'/' + "+e+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return Hh(t,n)}function cP(t,e,r){var a=su(r?"/"+ou(e):nu(e));return Hh(t,a)}var uP=/^\/(?:[^~]|~0|~1)*$/,dP=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fP(t,e,r){var a,n,s,o;if(t==="")return"rootData";if(t[0]=="/"){if(!uP.test(t))throw new Error("Invalid JSON-pointer: "+t);n=t,s="rootData"}else{if(o=t.match(dP),!o)throw new Error("Invalid JSON-pointer: "+t);if(a=+o[1],n=o[2],n=="#"){if(a>=e)throw new Error("Cannot access property/index "+a+" levels up, current level is "+e);return r[e-a]}if(a>e)throw new Error("Cannot access data "+a+" levels up, current level is "+e);if(s="data"+(e-a||""),!n)return s}for(var i=s,l=n.split("/"),c=0;c<l.length;c++){var u=l[c];u&&(s+=nu(iu(u)),i+=" && "+s)}return i}function Hh(t,e){return t=='""'?e:(t+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function pP(t){return iu(decodeURIComponent(t))}function hP(t){return encodeURIComponent(ou(t))}function ou(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function iu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}var mP=Ra,Bh=vP;function vP(t){mP.copy(t,this)}var Jh={exports:{}},wn=Jh.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},n=r.post||function(){};li(e,a,n,t,"",t)};wn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},wn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},wn.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},wn.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 li(t,e,r,a,n,s,o,i,l,c){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,n,s,o,i,l,c);for(var u in a){var h=a[u];if(Array.isArray(h)){if(u in wn.arrayKeywords)for(var g=0;g<h.length;g++)li(t,e,r,h[g],n+"/"+u+"/"+g,s,n,u,a,g)}else if(u in wn.propsKeywords){if(h&&typeof h=="object")for(var d in h)li(t,e,r,h[d],n+"/"+u+"/"+gP(d),s,n,u,a,d)}else(u in wn.keywords||t.allKeys&&!(u in wn.skipKeywords))&&li(t,e,r,h,n+"/"+u,s,n,u,a)}r(a,n,s,o,i,l,c)}}function gP(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var yP=Jh.exports,As=WS,Gh=ns,ci=Ra,ui=Bh,_P=yP,lu=bn;bn.normalizeId=En,bn.fullPath=fi,bn.url=pi,bn.ids=SP,bn.inlineRef=cu,bn.schema=di;function bn(t,e,r){var a=this._refs[r];if(typeof a=="string")if(this._refs[a])a=this._refs[a];else return bn.call(this,t,e,a);if(a=a||this._schemas[r],a instanceof ui)return cu(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var n=di.call(this,e,r),s,o,i;return n&&(s=n.schema,e=n.root,i=n.baseId),s instanceof ui?o=s.validate||t.call(this,s.schema,e,void 0,i):s!==void 0&&(o=cu(s,this._opts.inlineRefs)?s:t.call(this,s,e,void 0,i)),o}function di(t,e){var r=As.parse(e),a=Wh(r),n=fi(this._getId(t.schema));if(Object.keys(t.schema).length===0||a!==n){var s=En(a),o=this._refs[s];if(typeof o=="string")return wP.call(this,t,o,r);if(o instanceof ui)o.validate||this._compile(o),t=o;else if(o=this._schemas[s],o instanceof ui){if(o.validate||this._compile(o),s==En(e))return{schema:o,root:t,baseId:n};t=o}else return;if(!t.schema)return;n=fi(this._getId(t.schema))}return Kh.call(this,r,n,t.schema,t)}function wP(t,e,r){var a=di.call(this,t,e);if(a){var n=a.schema,s=a.baseId;t=a.root;var o=this._getId(n);return o&&(s=pi(s,o)),Kh.call(this,r,s,n,t)}}var bP=ci.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function Kh(t,e,r,a){if(t.fragment=t.fragment||"",t.fragment.slice(0,1)=="/"){for(var n=t.fragment.split("/"),s=1;s<n.length;s++){var o=n[s];if(o){if(o=ci.unescapeFragment(o),r=r[o],r===void 0)break;var i;if(!bP[o]&&(i=this._getId(r),i&&(e=pi(e,i)),r.$ref)){var l=pi(e,r.$ref),c=di.call(this,a,l);c&&(r=c.schema,a=c.root,e=c.baseId)}}}if(r!==void 0&&r!==a.schema)return{schema:r,root:a,baseId:e}}}var EP=ci.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function cu(t,e){if(e===!1)return!1;if(e===void 0||e===!0)return uu(t);if(e)return du(t)<=e}function uu(t){var e;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if(e=t[r],typeof e=="object"&&!uu(e))return!1}else for(var a in t)if(a=="$ref"||(e=t[a],typeof e=="object"&&!uu(e)))return!1;return!0}function du(t){var e=0,r;if(Array.isArray(t)){for(var a=0;a<t.length;a++)if(r=t[a],typeof r=="object"&&(e+=du(r)),e==1/0)return 1/0}else for(var n in t){if(n=="$ref")return 1/0;if(EP[n])e++;else if(r=t[n],typeof r=="object"&&(e+=du(r)+1),e==1/0)return 1/0}return e}function fi(t,e){e!==!1&&(t=En(t));var r=As.parse(t);return Wh(r)}function Wh(t){return As.serialize(t).split("#")[0]+"#"}var $P=/#\/?$/;function En(t){return t?t.replace($P,""):""}function pi(t,e){return e=En(e),As.resolve(t,e)}function SP(t){var e=En(this._getId(t)),r={"":e},a={"":fi(e,!1)},n={},s=this;return _P(t,{allKeys:!0},function(o,i,l,c,u,h,g){if(i!==""){var d=s._getId(o),f=r[c],v=a[c]+"/"+u;if(g!==void 0&&(v+="/"+(typeof g=="number"?g:ci.escapeFragment(g))),typeof d=="string"){d=f=En(f?As.resolve(f,d):d);var m=s._refs[d];if(typeof m=="string"&&(m=s._refs[m]),m&&m.schema){if(!Gh(o,m.schema))throw new Error('id "'+d+'" resolves to more than one schema')}else if(d!=En(v))if(d[0]=="#"){if(n[d]&&!Gh(o,n[d]))throw new Error('id "'+d+'" resolves to more than one schema');n[d]=o}else s._refs[d]=v}r[i]=f,a[i]=v}}),n}var fu=lu,pu={Validation:Qh(PP),MissingRef:Qh(hu)};function PP(t){this.message="validation failed",this.errors=t,this.ajv=this.validation=!0}hu.message=function(t,e){return"can't resolve reference "+e+" from id "+t};function hu(t,e,r){this.message=r||hu.message(t,e),this.missingRef=fu.url(t,e),this.missingSchema=fu.normalizeId(fu.fullPath(this.missingRef))}function Qh(t){return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Yh=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,a=e.cmp&&function(s){return function(o){return function(i,l){var c={key:i,value:o[i]},u={key:l,value:o[l]};return s(c,u)}}}(e.cmp),n=[];return function s(o){if(o&&o.toJSON&&typeof o.toJSON=="function"&&(o=o.toJSON()),o!==void 0){if(typeof o=="number")return isFinite(o)?""+o:"null";if(typeof o!="object")return JSON.stringify(o);var i,l;if(Array.isArray(o)){for(l="[",i=0;i<o.length;i++)i&&(l+=","),l+=s(o[i])||"null";return l+"]"}if(o===null)return"null";if(n.indexOf(o)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var c=n.push(o)-1,u=Object.keys(o).sort(a&&a(o));for(l="",i=0;i<u.length;i++){var h=u[i],g=s(o[h]);g&&(l&&(l+=","),l+=JSON.stringify(h)+":"+g)}return n.splice(c,1),"{"+l+"}"}}(t)},Xh=function(e,r,a){var n="",s=e.schema.$async===!0,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),i=e.self._getId(e.schema);if(e.opts.strictKeywords){var l=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(l){var c="unknown keyword: "+l;if(e.opts.strictKeywords==="log")e.logger.warn(c);else throw new Error(c)}}if(e.isTop&&(n+=" var validate = ",s&&(e.async=!0,n+="async "),n+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",i&&(e.opts.sourceCode||e.opts.processCode)&&(n+=" "+("/*# sourceURL="+i+" */")+" ")),typeof e.schema=="boolean"||!(o||e.schema.$ref)){var r="false schema",u=e.level,h=e.dataLevel,g=e.schema[r],d=e.schemaPath+e.util.getProperty(r),f=e.errSchemaPath+"/"+r,E=!e.opts.allErrors,O,v="data"+(h||""),w="valid"+u;if(e.schema===!1){e.isTop?E=!0:n+=" var "+w+" = false; ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(O||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(f)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'boolean schema is false' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?s?n+=" return data; ":n+=" validate.errors = null; return true; ":n+=" var "+w+" = true; ";return e.isTop&&(n+=" }; return validate; "),n}if(e.isTop){var y=e.isTop,u=e.level=0,h=e.dataLevel=0,v="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var _="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(_);else throw new Error(_)}n+=" var vErrors = null; ",n+=" var errors = 0; ",n+=" if (rootData === undefined) rootData = data; "}else{var u=e.level,h=e.dataLevel,v="data"+(h||"");if(i&&(e.baseId=e.resolve.url(e.baseId,i)),s&&!e.async)throw new Error("async schema in sync schema");n+=" var errs_"+u+" = errors;"}var w="valid"+u,E=!e.opts.allErrors,P="",T="",O,M=e.schema.type,J=Array.isArray(M);if(M&&e.opts.nullable&&e.schema.nullable===!0&&(J?M.indexOf("null")==-1&&(M=M.concat("null")):M!="null"&&(M=[M,"null"],J=!0)),J&&M.length==1&&(M=M[0],J=!1),e.schema.$ref&&o){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(n+=" "+e.RULES.all.$comment.code(e,"$comment")),M){if(e.opts.coerceTypes)var H=e.util.coerceToTypes(e.opts.coerceTypes,M);var G=e.RULES.types[M];if(H||J||G===!0||G&&!Ze(G)){var d=e.schemaPath+".type",f=e.errSchemaPath+"/type",d=e.schemaPath+".type",f=e.errSchemaPath+"/type",F=J?"checkDataTypes":"checkDataType";if(n+=" if ("+e.util[F](M,v,e.opts.strictNumbers,!0)+") { ",H){var Z="dataType"+u,te="coerced"+u;n+=" var "+Z+" = typeof "+v+"; var "+te+" = undefined; ",e.opts.coerceTypes=="array"&&(n+=" if ("+Z+" == 'object' && Array.isArray("+v+") && "+v+".length == 1) { "+v+" = "+v+"[0]; "+Z+" = typeof "+v+"; if ("+e.util.checkDataType(e.schema.type,v,e.opts.strictNumbers)+") "+te+" = "+v+"; } "),n+=" if ("+te+" !== undefined) ; ";var pe=H;if(pe)for(var ve,N=-1,ie=pe.length-1;N<ie;)ve=pe[N+=1],ve=="string"?n+=" else if ("+Z+" == 'number' || "+Z+" == 'boolean') "+te+" = '' + "+v+"; else if ("+v+" === null) "+te+" = ''; ":ve=="number"||ve=="integer"?(n+=" else if ("+Z+" == 'boolean' || "+v+" === null || ("+Z+" == 'string' && "+v+" && "+v+" == +"+v+" ",ve=="integer"&&(n+=" && !("+v+" % 1)"),n+=")) "+te+" = +"+v+"; "):ve=="boolean"?n+=" else if ("+v+" === 'false' || "+v+" === 0 || "+v+" === null) "+te+" = false; else if ("+v+" === 'true' || "+v+" === 1) "+te+" = true; ":ve=="null"?n+=" else if ("+v+" === '' || "+v+" === 0 || "+v+" === false) "+te+" = null; ":e.opts.coerceTypes=="array"&&ve=="array"&&(n+=" else if ("+Z+" == 'string' || "+Z+" == 'number' || "+Z+" == 'boolean' || "+v+" == null) "+te+" = ["+v+"]; ");n+=" else { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(O||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(f)+" , params: { type: '",J?n+=""+M.join(","):n+=""+M,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",J?n+=""+M.join(","):n+=""+M,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } if ("+te+" !== undefined) { ";var D=h?"data"+(h-1||""):"parentData",C=h?e.dataPathArr[h]:"parentDataProperty";n+=" "+v+" = "+te+"; ",h||(n+="if ("+D+" !== undefined)"),n+=" "+D+"["+C+"] = "+te+"; } "}else{var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(O||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(f)+" , params: { type: '",J?n+=""+M.join(","):n+=""+M,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",J?n+=""+M.join(","):n+=""+M,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}n+=" } "}}if(e.schema.$ref&&!o)n+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",E&&(n+=" } if (errors === ",y?n+="0":n+="errs_"+u,n+=") { ",T+="}");else{var z=e.RULES;if(z){for(var G,A=-1,b=z.length-1;A<b;)if(G=z[A+=1],Ze(G)){if(G.type&&(n+=" if ("+e.util.checkDataType(G.type,v,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(G.type=="object"&&e.schema.properties){var g=e.schema.properties,x=Object.keys(g),L=x;if(L)for(var W,X=-1,$e=L.length-1;X<$e;){W=L[X+=1];var le=g[W];if(le.default!==void 0){var ge=v+e.util.getProperty(W);if(e.compositeRule){if(e.opts.strictDefaults){var _="default is ignored for: "+ge;if(e.opts.strictDefaults==="log")e.logger.warn(_);else throw new Error(_)}}else n+=" if ("+ge+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+ge+" === null || "+ge+" === '' "),n+=" ) "+ge+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(le.default)+" ":n+=" "+JSON.stringify(le.default)+" ",n+="; "}}}else if(G.type=="array"&&Array.isArray(e.schema.items)){var mt=e.schema.items;if(mt){for(var le,N=-1,Ie=mt.length-1;N<Ie;)if(le=mt[N+=1],le.default!==void 0){var ge=v+"["+N+"]";if(e.compositeRule){if(e.opts.strictDefaults){var _="default is ignored for: "+ge;if(e.opts.strictDefaults==="log")e.logger.warn(_);else throw new Error(_)}}else n+=" if ("+ge+" === undefined ",e.opts.useDefaults=="empty"&&(n+=" || "+ge+" === null || "+ge+" === '' "),n+=" ) "+ge+" = ",e.opts.useDefaults=="shared"?n+=" "+e.useDefault(le.default)+" ":n+=" "+JSON.stringify(le.default)+" ",n+="; "}}}}var he=G.rules;if(he){for(var Ae,Ne=-1,Te=he.length-1;Ne<Te;)if(Ae=he[Ne+=1],re(Ae)){var tt=Ae.code(e,Ae.keyword,G.type);tt&&(n+=" "+tt+" ",E&&(P+="}"))}}if(E&&(n+=" "+P+" ",P=""),G.type&&(n+=" } ",M&&M===G.type&&!H)){n+=" else { ";var d=e.schemaPath+".type",f=e.errSchemaPath+"/type",m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(O||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(f)+" , params: { type: '",J?n+=""+M.join(","):n+=""+M,n+="' } ",e.opts.messages!==!1&&(n+=" , message: 'should be ",J?n+=""+M.join(","):n+=""+M,n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+v+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&E?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } "}E&&(n+=" if (errors === ",y?n+="0":n+="errs_"+u,n+=") { ",T+="}")}}}E&&(n+=" "+T+" "),y?(s?(n+=" if (errors === 0) return data; ",n+=" else throw new ValidationError(vErrors); "):(n+=" validate.errors = vErrors; ",n+=" return errors === 0; "),n+=" }; return validate;"):n+=" var "+w+" = errors === errs_"+u+";";function Ze(He){for(var Ee=He.rules,We=0;We<Ee.length;We++)if(re(Ee[We]))return!0}function re(He){return e.schema[He.keyword]!==void 0||He.implements&&Le(He)}function Le(He){for(var Ee=He.implements,We=0;We<Ee.length;We++)if(e.schema[Ee[We]]!==void 0)return!0}return n},hi=lu,mi=Ra,em=pu,TP=Yh,tm=Xh,xP=mi.ucs2length,kP=ns,IP=em.Validation,CP=mu;function mu(t,e,r,a){var n=this,s=this._opts,o=[void 0],i={},l=[],c={},u=[],h={},g=[];e=e||{schema:t,refVal:o,refs:i};var d=RP.call(this,t,e,a),f=this._compilations[d.index];if(d.compiling)return f.callValidate=_;var v=this._formats,m=this.RULES;try{var p=w(t,e,r,a);f.validate=p;var y=f.callValidate;return y&&(y.schema=p.schema,y.errors=null,y.refs=p.refs,y.refVal=p.refVal,y.root=p.root,y.$async=p.$async,s.sourceCode&&(y.source=p.source)),p}finally{OP.call(this,t,e,a)}function _(){var F=f.validate,Z=F.apply(this,arguments);return _.errors=F.errors,Z}function w(F,Z,te,pe){var ve=!Z||Z&&Z.schema==F;if(Z.schema!=e.schema)return mu.call(n,F,Z,te,pe);var N=F.$async===!0,ie=tm({isTop:!0,schema:F,isRoot:ve,baseId:pe,root:Z,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:em.MissingRef,RULES:m,validate:tm,util:mi,resolve:hi,resolveRef:E,usePattern:J,useDefault:H,useCustomRule:G,opts:s,formats:v,logger:n.logger,self:n});ie=vi(o,MP)+vi(l,AP)+vi(u,NP)+vi(g,jP)+ie,s.processCode&&(ie=s.processCode(ie,F));var D;try{var C=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",ie);D=C(n,m,v,e,o,u,g,kP,xP,IP),o[0]=D}catch(z){throw n.logger.error("Error compiling schema, function code:",ie),z}return D.schema=F,D.errors=null,D.refs=i,D.refVal=o,D.root=ve?D:Z,N&&(D.$async=!0),s.sourceCode===!0&&(D.source={code:ie,patterns:l,defaults:u}),D}function E(F,Z,te){Z=hi.url(F,Z);var pe=i[Z],ve,N;if(pe!==void 0)return ve=o[pe],N="refVal["+pe+"]",M(ve,N);if(!te&&e.refs){var ie=e.refs[Z];if(ie!==void 0)return ve=e.refVal[ie],N=P(Z,ve),M(ve,N)}N=P(Z);var D=hi.call(n,w,e,Z);if(D===void 0){var C=r&&r[Z];C&&(D=hi.inlineRef(C,s.inlineRefs)?C:mu.call(n,C,e,r,F))}if(D===void 0)T(Z);else return O(Z,D),M(D,N)}function P(F,Z){var te=o.length;return o[te]=Z,i[F]=te,"refVal"+te}function T(F){delete i[F]}function O(F,Z){var te=i[F];o[te]=Z}function M(F,Z){return typeof F=="object"||typeof F=="boolean"?{code:Z,schema:F,inline:!0}:{code:Z,$async:F&&!!F.$async}}function J(F){var Z=c[F];return Z===void 0&&(Z=c[F]=l.length,l[Z]=F),"pattern"+Z}function H(F){switch(typeof F){case"boolean":case"number":return""+F;case"string":return mi.toQuotedString(F);case"object":if(F===null)return"null";var Z=TP(F),te=h[Z];return te===void 0&&(te=h[Z]=u.length,u[te]=F),"default"+te}}function G(F,Z,te,pe){if(n._opts.validateSchema!==!1){var ve=F.definition.dependencies;if(ve&&!ve.every(function(L){return Object.prototype.hasOwnProperty.call(te,L)}))throw new Error("parent schema must have all required keywords: "+ve.join(","));var N=F.definition.validateSchema;if(N){var ie=N(Z);if(!ie){var D="keyword schema is invalid: "+n.errorsText(N.errors);if(n._opts.validateSchema=="log")n.logger.error(D);else throw new Error(D)}}}var C=F.definition.compile,z=F.definition.inline,A=F.definition.macro,b;if(C)b=C.call(n,Z,te,pe);else if(A)b=A.call(n,Z,te,pe),s.validateSchema!==!1&&n.validateSchema(b,!0);else if(z)b=z.call(n,pe,F.keyword,Z,te);else if(b=F.definition.validate,!b)return;if(b===void 0)throw new Error('custom keyword "'+F.keyword+'"failed to compile');var x=g.length;return g[x]=b,{code:"customRule"+x,validate:b}}}function RP(t,e,r){var a=rm.call(this,t,e,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:t,root:e,baseId:r},{index:a,compiling:!1})}function OP(t,e,r){var a=rm.call(this,t,e,r);a>=0&&this._compilations.splice(a,1)}function rm(t,e,r){for(var a=0;a<this._compilations.length;a++){var n=this._compilations[a];if(n.schema==t&&n.root==e&&n.baseId==r)return a}return-1}function AP(t,e){return"var pattern"+t+" = new RegExp("+mi.toQuotedString(e[t])+");"}function NP(t){return"var default"+t+" = defaults["+t+"];"}function MP(t,e){return e[t]===void 0?"":"var refVal"+t+" = refVal["+t+"];"}function jP(t){return"var customRule"+t+" = customRules["+t+"];"}function vi(t,e){if(!t.length)return"";for(var r="",a=0;a<t.length;a++)r+=e(a,t);return r}var nm={exports:{}},gi=nm.exports=function(){this._cache={}};gi.prototype.put=function(e,r){this._cache[e]=r},gi.prototype.get=function(e){return this._cache[e]},gi.prototype.del=function(e){delete this._cache[e]},gi.prototype.clear=function(){this._cache={}};var DP=nm.exports,LP=Ra,zP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,UP=[0,31,28,31,30,31,30,31,31,30,31,30,31],qP=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,am=/^(?=.{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,FP=/^(?:[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,ZP=/^(?:[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,sm=/^(?:(?:[^\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,om=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,im=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,lm=/^(?:\/(?:[^~/]|~0|~1)*)*$/,cm=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,um=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,VP=yi;function yi(t){return t=t=="full"?"full":"fast",LP.copy(yi[t])}yi.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":sm,url:om,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,hostname:am,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:pm,uuid:im,"json-pointer":lm,"json-pointer-uri-fragment":cm,"relative-json-pointer":um},yi.full={date:dm,time:fm,"date-time":JP,uri:KP,"uri-reference":ZP,"uri-template":sm,url:om,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:am,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:pm,uuid:im,"json-pointer":lm,"json-pointer-uri-fragment":cm,"relative-json-pointer":um};function HP(t){return t%4===0&&(t%100!==0||t%400===0)}function dm(t){var e=t.match(zP);if(!e)return!1;var r=+e[1],a=+e[2],n=+e[3];return a>=1&&a<=12&&n>=1&&n<=(a==2&&HP(r)?29:UP[a])}function fm(t,e){var r=t.match(qP);if(!r)return!1;var a=r[1],n=r[2],s=r[3],o=r[5];return(a<=23&&n<=59&&s<=59||a==23&&n==59&&s==60)&&(!e||o)}var BP=/t|\s/i;function JP(t){var e=t.split(BP);return e.length==2&&dm(e[0])&&fm(e[1],!0)}var GP=/\/|:/;function KP(t){return GP.test(t)&&FP.test(t)}var WP=/[^\\]\\Z/;function pm(t){if(WP.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}var QP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,u="data"+(o||""),h="valid"+s,g,d;if(i=="#"||i=="#/")e.isRoot?(g=e.async,d="validate"):(g=e.root.schema.$async===!0,d="root.refVal[0]");else{var f=e.resolveRef(e.baseId,i,e.isRoot);if(f===void 0){var v=e.MissingRefError.message(e.baseId,i);if(e.opts.missingRefs=="fail"){e.logger.error(v);var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(i)+"' } ",e.opts.messages!==!1&&(n+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(i)+"' "),e.opts.verbose&&(n+=" , schema: "+e.util.toQuotedString(i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),n+=" } "):n+=" {} ";var p=n;n=m.pop(),!e.compositeRule&&c?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c&&(n+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(v),c&&(n+=" if (true) { ");else throw new e.MissingRefError(e.baseId,i,v)}else if(f.inline){var y=e.util.copy(e);y.level++;var _="valid"+y.level;y.schema=f.schema,y.schemaPath="",y.errSchemaPath=i;var w=e.validate(y).replace(/validate\.schema/g,f.code);n+=" "+w+" ",c&&(n+=" if ("+_+") { ")}else g=f.$async===!0||e.async&&f.$async!==!1,d=f.code}if(d){var m=m||[];m.push(n),n="",e.opts.passContext?n+=" "+d+".call(this, ":n+=" "+d+"( ",n+=" "+u+", (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var E=o?"data"+(o-1||""):"parentData",P=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+E+" , "+P+", rootData) ";var T=n;if(n=m.pop(),g){if(!e.async)throw new Error("async schema referenced by sync schema");c&&(n+=" var "+h+"; "),n+=" try { await "+T+"; ",c&&(n+=" "+h+" = true; "),n+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",c&&(n+=" "+h+" = false; "),n+=" } ",c&&(n+=" if ("+h+") { ")}else n+=" if (!"+T+") { if (vErrors === null) vErrors = "+d+".errors; else vErrors = vErrors.concat("+d+".errors); errors = vErrors.length; } ",c&&(n+=" else { ")}return n},YP=function(e,r,a){var n=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c=e.util.copy(e),u="";c.level++;var h="valid"+c.level,g=c.baseId,d=!0,f=s;if(f)for(var v,m=-1,p=f.length-1;m<p;)v=f[m+=1],(e.opts.strictKeywords?typeof v=="object"&&Object.keys(v).length>0||v===!1:e.util.schemaHasRules(v,e.RULES.all))&&(d=!1,c.schema=v,c.schemaPath=o+"["+m+"]",c.errSchemaPath=i+"/"+m,n+=" "+e.validate(c)+" ",c.baseId=g,l&&(n+=" if ("+h+") { ",u+="}"));return l&&(d?n+=" if (true) { ":n+=" "+u.slice(0,-1)+" "),n},XP=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,d="errs__"+s,f=e.util.copy(e),v="";f.level++;var m="valid"+f.level,p=i.every(function(O){return e.opts.strictKeywords?typeof O=="object"&&Object.keys(O).length>0||O===!1:e.util.schemaHasRules(O,e.RULES.all)});if(p){var y=f.baseId;n+=" var "+d+" = errors; var "+g+" = false; ";var _=e.compositeRule;e.compositeRule=f.compositeRule=!0;var w=i;if(w)for(var E,P=-1,T=w.length-1;P<T;)E=w[P+=1],f.schema=E,f.schemaPath=l+"["+P+"]",f.errSchemaPath=c+"/"+P,n+=" "+e.validate(f)+" ",f.baseId=y,n+=" "+g+" = "+g+" || "+m+"; if (!"+g+") { ",v+="}";e.compositeRule=f.compositeRule=_,n+=" "+v+" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else u&&(n+=" if (true) { ");return n},eT=function(e,r,a){var n=" ",s=e.schema[r],o=e.errSchemaPath+"/"+r;e.opts.allErrors;var i=e.util.toQuotedString(s);return e.opts.$comment===!0?n+=" console.log("+i+");":typeof e.opts.$comment=="function"&&(n+=" self._opts.$comment("+i+", "+e.util.toQuotedString(o)+", validate.root.schema);"),n},tT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data;d&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; "),d||(n+=" var schema"+s+" = validate.schema"+l+";"),n+="var "+g+" = equal("+h+", schema"+s+"); if (!"+g+") { ";var f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValue: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to constant' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=f.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",u&&(n+=" else { "),n},rT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,d="errs__"+s,f=e.util.copy(e),v="";f.level++;var m="valid"+f.level,p="i"+s,y=f.dataLevel=e.dataLevel+1,_="data"+y,w=e.baseId,E=e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all);if(n+="var "+d+" = errors;var "+g+";",E){var P=e.compositeRule;e.compositeRule=f.compositeRule=!0,f.schema=i,f.schemaPath=l,f.errSchemaPath=c,n+=" var "+m+" = false; for (var "+p+" = 0; "+p+" < "+h+".length; "+p+"++) { ",f.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var T=h+"["+p+"]";f.dataPathArr[y]=p;var O=e.validate(f);f.baseId=w,e.util.varOccurences(O,_)<2?n+=" "+e.util.varReplace(O,_,T)+" ":n+=" var "+_+" = "+T+"; "+O+" ",n+=" if ("+m+") break; } ",e.compositeRule=f.compositeRule=P,n+=" "+v+" if (!"+m+") {"}else n+=" if ("+h+".length == 0) {";var M=M||[];M.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should contain a valid item' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var J=n;return n=M.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+J+"]); ":n+=" validate.errors = ["+J+"]; return false; ":n+=" var err = "+J+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { ",E&&(n+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } "),e.opts.allErrors&&(n+=" } "),n},nT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,d=e.util.copy(e),f="";d.level++;var v="valid"+d.level,m={},p={},y=e.opts.ownProperties;for(P in i)if(P!="__proto__"){var _=i[P],w=Array.isArray(_)?p:m;w[P]=_}n+="var "+g+" = errors;";var E=e.errorPath;n+="var missing"+s+";";for(var P in p)if(w=p[P],w.length){if(n+=" if ( "+h+e.util.getProperty(P)+" !== undefined ",y&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(P)+"') "),u){n+=" && ( ";var T=w;if(T)for(var O,M=-1,J=T.length-1;M<J;){O=T[M+=1],M&&(n+=" || ");var H=e.util.getProperty(O),G=h+H;n+=" ( ( "+G+" === undefined ",y&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(O)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?O:H)+") ) "}n+=")) { ";var F="missing"+s,Z="' + "+F+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(E,F,!0):E+" + "+F);var te=te||[];te.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(P)+"', missingProperty: '"+Z+"', depsCount: "+w.length+", deps: '"+e.util.escapeQuotes(w.length==1?w[0]:w.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",w.length==1?n+="property "+e.util.escapeQuotes(w[0]):n+="properties "+e.util.escapeQuotes(w.join(", ")),n+=" when property "+e.util.escapeQuotes(P)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var pe=n;n=te.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+pe+"]); ":n+=" validate.errors = ["+pe+"]; return false; ":n+=" var err = "+pe+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{n+=" ) { ";var ve=w;if(ve)for(var O,N=-1,ie=ve.length-1;N<ie;){O=ve[N+=1];var H=e.util.getProperty(O),Z=e.util.escapeQuotes(O),G=h+H;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(E,O,e.opts.jsonPointers)),n+=" if ( "+G+" === undefined ",y&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(O)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(P)+"', missingProperty: '"+Z+"', depsCount: "+w.length+", deps: '"+e.util.escapeQuotes(w.length==1?w[0]:w.join(", "))+"' } ",e.opts.messages!==!1&&(n+=" , message: 'should have ",w.length==1?n+="property "+e.util.escapeQuotes(w[0]):n+="properties "+e.util.escapeQuotes(w.join(", ")),n+=" when property "+e.util.escapeQuotes(P)+" is present' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}n+=" } ",u&&(f+="}",n+=" else { ")}e.errorPath=E;var D=d.baseId;for(var P in m){var _=m[P];(e.opts.strictKeywords?typeof _=="object"&&Object.keys(_).length>0||_===!1:e.util.schemaHasRules(_,e.RULES.all))&&(n+=" "+v+" = true; if ( "+h+e.util.getProperty(P)+" !== undefined ",y&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(P)+"') "),n+=") { ",d.schema=_,d.schemaPath=l+e.util.getProperty(P),d.errSchemaPath=c+"/"+e.util.escapeFragment(P),n+=" "+e.validate(d)+" ",d.baseId=D,n+=" } ",u&&(n+=" if ("+v+") { ",f+="}"))}return u&&(n+=" "+f+" if ("+g+" == errors) {"),n},aT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data;d&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var f="i"+s,v="schema"+s;d||(n+=" var "+v+" = validate.schema"+l+";"),n+="var "+g+";",d&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=""+g+" = false;for (var "+f+"=0; "+f+"<"+v+".length; "+f+"++) if (equal("+h+", "+v+"["+f+"])) { "+g+" = true; break; }",d&&(n+=" } "),n+=" if (!"+g+") { ";var m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { allowedValues: schema"+s+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var p=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" }",u&&(n+=" else { "),n},sT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||"");if(e.opts.format===!1)return u&&(n+=" if (true) { "),n;var g=e.opts.$data&&i&&i.$data,d;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i;var f=e.opts.unknownFormats,v=Array.isArray(f);if(g){var m="format"+s,p="isObject"+s,y="formatType"+s;n+=" var "+m+" = formats["+d+"]; var "+p+" = typeof "+m+" == 'object' && !("+m+" instanceof RegExp) && "+m+".validate; var "+y+" = "+p+" && "+m+".type || 'string'; if ("+p+") { ",e.async&&(n+=" var async"+s+" = "+m+".async; "),n+=" "+m+" = "+m+".validate; } if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),n+=" (",f!="ignore"&&(n+=" ("+d+" && !"+m+" ",v&&(n+=" && self._opts.unknownFormats.indexOf("+d+") == -1 "),n+=") || "),n+=" ("+m+" && "+y+" == '"+a+"' && !(typeof "+m+" == 'function' ? ",e.async?n+=" (async"+s+" ? await "+m+"("+h+") : "+m+"("+h+")) ":n+=" "+m+"("+h+") ",n+=" : "+m+".test("+h+"))))) {"}else{var m=e.formats[i];if(!m){if(f=="ignore")return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),u&&(n+=" if (true) { "),n;if(v&&f.indexOf(i)>=0)return u&&(n+=" if (true) { "),n;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var p=typeof m=="object"&&!(m instanceof RegExp)&&m.validate,y=p&&m.type||"string";if(p){var _=m.async===!0;m=m.validate}if(y!=a)return u&&(n+=" if (true) { "),n;if(_){if(!e.async)throw new Error("async format in sync schema");var w="formats"+e.util.getProperty(i)+".validate";n+=" if (!(await "+w+"("+h+"))) { "}else{n+=" if (! ";var w="formats"+e.util.getProperty(i);p&&(w+=".validate"),typeof m=="function"?n+=" "+w+"("+h+") ":n+=" "+w+".test("+h+") ",n+=") { "}}var E=E||[];E.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { format: ",g?n+=""+d:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match format "`,g?n+="' + "+d+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var P=n;return n=E.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+P+"]); ":n+=" validate.errors = ["+P+"]; return false; ":n+=" var err = "+P+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { "),n},oT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,d="errs__"+s,f=e.util.copy(e);f.level++;var v="valid"+f.level,m=e.schema.then,p=e.schema.else,y=m!==void 0&&(e.opts.strictKeywords?typeof m=="object"&&Object.keys(m).length>0||m===!1:e.util.schemaHasRules(m,e.RULES.all)),_=p!==void 0&&(e.opts.strictKeywords?typeof p=="object"&&Object.keys(p).length>0||p===!1:e.util.schemaHasRules(p,e.RULES.all)),w=f.baseId;if(y||_){var E;f.createErrors=!1,f.schema=i,f.schemaPath=l,f.errSchemaPath=c,n+=" var "+d+" = errors; var "+g+" = true; ";var P=e.compositeRule;e.compositeRule=f.compositeRule=!0,n+=" "+e.validate(f)+" ",f.baseId=w,f.createErrors=!0,n+=" errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; } ",e.compositeRule=f.compositeRule=P,y?(n+=" if ("+v+") { ",f.schema=e.schema.then,f.schemaPath=e.schemaPath+".then",f.errSchemaPath=e.errSchemaPath+"/then",n+=" "+e.validate(f)+" ",f.baseId=w,n+=" "+g+" = "+v+"; ",y&&_?(E="ifClause"+s,n+=" var "+E+" = 'then'; "):E="'then'",n+=" } ",_&&(n+=" else { ")):n+=" if (!"+v+") { ",_&&(f.schema=e.schema.else,f.schemaPath=e.schemaPath+".else",f.errSchemaPath=e.errSchemaPath+"/else",n+=" "+e.validate(f)+" ",f.baseId=w,n+=" "+g+" = "+v+"; ",y&&_?(E="ifClause"+s,n+=" var "+E+" = 'else'; "):E="'else'",n+=" } "),n+=" if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { failingKeyword: "+E+" } ",e.opts.messages!==!1&&(n+=` , message: 'should match "' + `+E+` + '" schema' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+=" } ",u&&(n+=" else { ")}else u&&(n+=" if (true) { ");return n},iT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,d="errs__"+s,f=e.util.copy(e),v="";f.level++;var m="valid"+f.level,p="i"+s,y=f.dataLevel=e.dataLevel+1,_="data"+y,w=e.baseId;if(n+="var "+d+" = errors;var "+g+";",Array.isArray(i)){var E=e.schema.additionalItems;if(E===!1){n+=" "+g+" = "+h+".length <= "+i.length+"; ";var P=c;c=e.errSchemaPath+"/additionalItems",n+=" if (!"+g+") { ";var T=T||[];T.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+i.length+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var O=n;n=T.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+O+"]); ":n+=" validate.errors = ["+O+"]; return false; ":n+=" var err = "+O+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",c=P,u&&(v+="}",n+=" else { ")}var M=i;if(M){for(var J,H=-1,G=M.length-1;H<G;)if(J=M[H+=1],e.opts.strictKeywords?typeof J=="object"&&Object.keys(J).length>0||J===!1:e.util.schemaHasRules(J,e.RULES.all)){n+=" "+m+" = true; if ("+h+".length > "+H+") { ";var F=h+"["+H+"]";f.schema=J,f.schemaPath=l+"["+H+"]",f.errSchemaPath=c+"/"+H,f.errorPath=e.util.getPathExpr(e.errorPath,H,e.opts.jsonPointers,!0),f.dataPathArr[y]=H;var Z=e.validate(f);f.baseId=w,e.util.varOccurences(Z,_)<2?n+=" "+e.util.varReplace(Z,_,F)+" ":n+=" var "+_+" = "+F+"; "+Z+" ",n+=" } ",u&&(n+=" if ("+m+") { ",v+="}")}}if(typeof E=="object"&&(e.opts.strictKeywords?typeof E=="object"&&Object.keys(E).length>0||E===!1:e.util.schemaHasRules(E,e.RULES.all))){f.schema=E,f.schemaPath=e.schemaPath+".additionalItems",f.errSchemaPath=e.errSchemaPath+"/additionalItems",n+=" "+m+" = true; if ("+h+".length > "+i.length+") { for (var "+p+" = "+i.length+"; "+p+" < "+h+".length; "+p+"++) { ",f.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var F=h+"["+p+"]";f.dataPathArr[y]=p;var Z=e.validate(f);f.baseId=w,e.util.varOccurences(Z,_)<2?n+=" "+e.util.varReplace(Z,_,F)+" ":n+=" var "+_+" = "+F+"; "+Z+" ",u&&(n+=" if (!"+m+") break; "),n+=" } } ",u&&(n+=" if ("+m+") { ",v+="}")}}else if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){f.schema=i,f.schemaPath=l,f.errSchemaPath=c,n+=" for (var "+p+" = 0; "+p+" < "+h+".length; "+p+"++) { ",f.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers,!0);var F=h+"["+p+"]";f.dataPathArr[y]=p;var Z=e.validate(f);f.baseId=w,e.util.varOccurences(Z,_)<2?n+=" "+e.util.varReplace(Z,_,F)+" ":n+=" var "+_+" = "+F+"; "+Z+" ",u&&(n+=" if (!"+m+") break; "),n+=" }"}return u&&(n+=" "+v+" if ("+d+" == errors) {"),n},hm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,w,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i;var f=r=="maximum",v=f?"exclusiveMaximum":"exclusiveMinimum",m=e.schema[v],p=e.opts.$data&&m&&m.$data,y=f?"<":">",_=f?">":"<",w=void 0;if(!(g||typeof i=="number"||i===void 0))throw new Error(r+" must be number");if(!(p||m===void 0||typeof m=="number"||typeof m=="boolean"))throw new Error(v+" must be number or boolean");if(p){var E=e.util.getData(m.$data,o,e.dataPathArr),P="exclusive"+s,T="exclType"+s,O="exclIsNumber"+s,M="op"+s,J="' + "+M+" + '";n+=" var schemaExcl"+s+" = "+E+"; ",E="schemaExcl"+s,n+=" var "+P+"; var "+T+" = typeof "+E+"; if ("+T+" != 'boolean' && "+T+" != 'undefined' && "+T+" != 'number') { ";var w=v,H=H||[];H.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(w||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: '"+v+" should be boolean' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var G=n;n=H.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+G+"]); ":n+=" validate.errors = ["+G+"]; return false; ":n+=" var err = "+G+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" "+T+" == 'number' ? ( ("+P+" = "+d+" === undefined || "+E+" "+y+"= "+d+") ? "+h+" "+_+"= "+E+" : "+h+" "+_+" "+d+" ) : ( ("+P+" = "+E+" === true) ? "+h+" "+_+"= "+d+" : "+h+" "+_+" "+d+" ) || "+h+" !== "+h+") { var op"+s+" = "+P+" ? '"+y+"' : '"+y+"='; ",i===void 0&&(w=v,c=e.errSchemaPath+"/"+v,d=E,g=p)}else{var O=typeof m=="number",J=y;if(O&&g){var M="'"+J+"'";n+=" if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" ( "+d+" === undefined || "+m+" "+y+"= "+d+" ? "+h+" "+_+"= "+m+" : "+h+" "+_+" "+d+" ) || "+h+" !== "+h+") { "}else{O&&i===void 0?(P=!0,w=v,c=e.errSchemaPath+"/"+v,d=m,_+="="):(O&&(d=Math[f?"min":"max"](m,i)),m===(O?d:!0)?(P=!0,w=v,c=e.errSchemaPath+"/"+v,_+="="):(P=!1,J+="="));var M="'"+J+"'";n+=" if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" "+h+" "+_+" "+d+" || "+h+" !== "+h+") { "}}w=w||r;var H=H||[];H.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(w||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { comparison: "+M+", limit: "+d+", exclusive: "+P+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be "+J+" ",g?n+="' + "+d:n+=""+d+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var G=n;return n=H.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+G+"]); ":n+=" validate.errors = ["+G+"]; return false; ":n+=" var err = "+G+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { "),n},mm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,v,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var f=r=="maxItems"?">":"<";n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" "+h+".length "+f+" "+d+") { ";var v=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxItems"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+d+" + '":n+=""+i,n+=" items' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var p=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},vm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,v,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var f=r=="maxLength"?">":"<";n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),e.opts.unicode===!1?n+=" "+h+".length ":n+=" ucs2length("+h+") ",n+=" "+f+" "+d+") { ";var v=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be ",r=="maxLength"?n+="longer":n+="shorter",n+=" than ",g?n+="' + "+d+" + '":n+=""+i,n+=" characters' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var p=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},gm=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,v,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");var f=r=="maxProperties"?">":"<";n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'number') || "),n+=" Object.keys("+h+").length "+f+" "+d+") { ";var v=r,m=m||[];m.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(v||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have ",r=="maxProperties"?n+="more":n+="fewer",n+=" than ",g?n+="' + "+d+" + '":n+=""+i,n+=" properties' "),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var p=n;return n=m.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+p+"]); ":n+=" validate.errors = ["+p+"]; return false; ":n+=" var err = "+p+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},lT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;if(g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i,!(g||typeof i=="number"))throw new Error(r+" must be number");n+="var division"+s+";if (",g&&(n+=" "+d+" !== undefined && ( typeof "+d+" != 'number' || "),n+=" (division"+s+" = "+h+" / "+d+", ",e.opts.multipleOfPrecision?n+=" Math.abs(Math.round(division"+s+") - division"+s+") > 1e-"+e.opts.multipleOfPrecision+" ":n+=" division"+s+" !== parseInt(division"+s+") ",n+=" ) ",g&&(n+=" ) "),n+=" ) { ";var f=f||[];f.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { multipleOf: "+d+" } ",e.opts.messages!==!1&&(n+=" , message: 'should be multiple of ",g?n+="' + "+d:n+=""+d+"'"),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var v=n;return n=f.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+v+"]); ":n+=" validate.errors = ["+v+"]; return false; ":n+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},cT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,d=e.util.copy(e);d.level++;var f="valid"+d.level;if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=l,d.errSchemaPath=c,n+=" var "+g+" = errors; ";var v=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.createErrors=!1;var m;d.opts.allErrors&&(m=d.opts.allErrors,d.opts.allErrors=!1),n+=" "+e.validate(d)+" ",d.createErrors=!0,m&&(d.opts.allErrors=m),e.compositeRule=d.compositeRule=v,n+=" if ("+f+") { ";var p=p||[];p.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var y=n;n=p.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+y+"]); ":n+=" validate.errors = ["+y+"]; return false; ":n+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { errors = "+g+"; if (vErrors !== null) { if ("+g+") vErrors.length = "+g+"; else vErrors = null; } ",e.opts.allErrors&&(n+=" } ")}else n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: {} ",e.opts.messages!==!1&&(n+=" , message: 'should NOT be valid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(n+=" if (false) { ");return n},uT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,d="errs__"+s,f=e.util.copy(e),v="";f.level++;var m="valid"+f.level,p=f.baseId,y="prevValid"+s,_="passingSchemas"+s;n+="var "+d+" = errors , "+y+" = false , "+g+" = false , "+_+" = null; ";var w=e.compositeRule;e.compositeRule=f.compositeRule=!0;var E=i;if(E)for(var P,T=-1,O=E.length-1;T<O;)P=E[T+=1],(e.opts.strictKeywords?typeof P=="object"&&Object.keys(P).length>0||P===!1:e.util.schemaHasRules(P,e.RULES.all))?(f.schema=P,f.schemaPath=l+"["+T+"]",f.errSchemaPath=c+"/"+T,n+=" "+e.validate(f)+" ",f.baseId=p):n+=" var "+m+" = true; ",T&&(n+=" if ("+m+" && "+y+") { "+g+" = false; "+_+" = ["+_+", "+T+"]; } else { ",v+="}"),n+=" if ("+m+") { "+g+" = "+y+" = true; "+_+" = "+T+"; }";return e.compositeRule=f.compositeRule=w,n+=""+v+"if (!"+g+") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { passingSchemas: "+_+" } ",e.opts.messages!==!1&&(n+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),n+="} else { errors = "+d+"; if (vErrors !== null) { if ("+d+") vErrors.length = "+d+"; else vErrors = null; }",e.opts.allErrors&&(n+=" } "),n},dT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g=e.opts.$data&&i&&i.$data,d;g?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",d="schema"+s):d=i;var f=g?"(new RegExp("+d+"))":e.usePattern(i);n+="if ( ",g&&(n+=" ("+d+" !== undefined && typeof "+d+" != 'string') || "),n+=" !"+f+".test("+h+") ) { ";var v=v||[];v.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { pattern: ",g?n+=""+d:n+=""+e.util.toQuotedString(i),n+=" } ",e.opts.messages!==!1&&(n+=` , message: 'should match pattern "`,g?n+="' + "+d+" + '":n+=""+e.util.escapeQuotes(i),n+=`"' `),e.opts.verbose&&(n+=" , schema: ",g?n+="validate.schema"+l:n+=""+e.util.toQuotedString(i),n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var m=n;return n=v.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+m+"]); ":n+=" validate.errors = ["+m+"]; return false; ":n+=" var err = "+m+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+="} ",u&&(n+=" else { "),n},fT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,d=e.util.copy(e),f="";d.level++;var v="valid"+d.level,m="key"+s,p="idx"+s,y=d.dataLevel=e.dataLevel+1,_="data"+y,w="dataProperties"+s,E=Object.keys(i||{}).filter(N),P=e.schema.patternProperties||{},T=Object.keys(P).filter(N),O=e.schema.additionalProperties,M=E.length||T.length,J=O===!1,H=typeof O=="object"&&Object.keys(O).length,G=e.opts.removeAdditional,F=J||H||G,Z=e.opts.ownProperties,te=e.baseId,pe=e.schema.required;if(pe&&!(e.opts.$data&&pe.$data)&&pe.length<e.opts.loopRequired)var ve=e.util.toHash(pe);function N(yt){return yt!=="__proto__"}if(n+="var "+g+" = errors;var "+v+" = true;",Z&&(n+=" var "+w+" = undefined;"),F){if(Z?n+=" "+w+" = "+w+" || Object.keys("+h+"); for (var "+p+"=0; "+p+"<"+w+".length; "+p+"++) { var "+m+" = "+w+"["+p+"]; ":n+=" for (var "+m+" in "+h+") { ",M){if(n+=" var isAdditional"+s+" = !(false ",E.length)if(E.length>8)n+=" || validate.schema"+l+".hasOwnProperty("+m+") ";else{var ie=E;if(ie)for(var D,C=-1,z=ie.length-1;C<z;)D=ie[C+=1],n+=" || "+m+" == "+e.util.toQuotedString(D)+" "}if(T.length){var A=T;if(A)for(var b,x=-1,L=A.length-1;x<L;)b=A[x+=1],n+=" || "+e.usePattern(b)+".test("+m+") "}n+=" ); if (isAdditional"+s+") { "}if(G=="all")n+=" delete "+h+"["+m+"]; ";else{var W=e.errorPath,X="' + "+m+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers)),J)if(G)n+=" delete "+h+"["+m+"]; ";else{n+=" "+v+" = false; ";var $e=c;c=e.errSchemaPath+"/additionalProperties";var le=le||[];le.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { additionalProperty: '"+X+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is an invalid additional property":n+="should NOT have additional properties",n+="' "),e.opts.verbose&&(n+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var ge=n;n=le.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+ge+"]); ":n+=" validate.errors = ["+ge+"]; return false; ":n+=" var err = "+ge+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=$e,u&&(n+=" break; ")}else if(H)if(G=="failing"){n+=" var "+g+" = errors; ";var mt=e.compositeRule;e.compositeRule=d.compositeRule=!0,d.schema=O,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var Ie=h+"["+m+"]";d.dataPathArr[y]=m;var he=e.validate(d);d.baseId=te,e.util.varOccurences(he,_)<2?n+=" "+e.util.varReplace(he,_,Ie)+" ":n+=" var "+_+" = "+Ie+"; "+he+" ",n+=" if (!"+v+") { errors = "+g+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+h+"["+m+"]; } ",e.compositeRule=d.compositeRule=mt}else{d.schema=O,d.schemaPath=e.schemaPath+".additionalProperties",d.errSchemaPath=e.errSchemaPath+"/additionalProperties",d.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var Ie=h+"["+m+"]";d.dataPathArr[y]=m;var he=e.validate(d);d.baseId=te,e.util.varOccurences(he,_)<2?n+=" "+e.util.varReplace(he,_,Ie)+" ":n+=" var "+_+" = "+Ie+"; "+he+" ",u&&(n+=" if (!"+v+") break; ")}e.errorPath=W}M&&(n+=" } "),n+=" } ",u&&(n+=" if ("+v+") { ",f+="}")}var Ae=e.opts.useDefaults&&!e.compositeRule;if(E.length){var Ne=E;if(Ne)for(var D,Te=-1,tt=Ne.length-1;Te<tt;){D=Ne[Te+=1];var Ze=i[D];if(e.opts.strictKeywords?typeof Ze=="object"&&Object.keys(Ze).length>0||Ze===!1:e.util.schemaHasRules(Ze,e.RULES.all)){var re=e.util.getProperty(D),Ie=h+re,Le=Ae&&Ze.default!==void 0;d.schema=Ze,d.schemaPath=l+re,d.errSchemaPath=c+"/"+e.util.escapeFragment(D),d.errorPath=e.util.getPath(e.errorPath,D,e.opts.jsonPointers),d.dataPathArr[y]=e.util.toQuotedString(D);var he=e.validate(d);if(d.baseId=te,e.util.varOccurences(he,_)<2){he=e.util.varReplace(he,_,Ie);var He=Ie}else{var He=_;n+=" var "+_+" = "+Ie+"; "}if(Le)n+=" "+he+" ";else{if(ve&&ve[D]){n+=" if ( "+He+" === undefined ",Z&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(D)+"') "),n+=") { "+v+" = false; ";var W=e.errorPath,$e=c,Ee=e.util.escapeQuotes(D);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(W,D,e.opts.jsonPointers)),c=e.errSchemaPath+"/required";var le=le||[];le.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+Ee+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+Ee+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var ge=n;n=le.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+ge+"]); ":n+=" validate.errors = ["+ge+"]; return false; ":n+=" var err = "+ge+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",c=$e,e.errorPath=W,n+=" } else { "}else u?(n+=" if ( "+He+" === undefined ",Z&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(D)+"') "),n+=") { "+v+" = true; } else { "):(n+=" if ("+He+" !== undefined ",Z&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(D)+"') "),n+=" ) { ");n+=" "+he+" } "}}u&&(n+=" if ("+v+") { ",f+="}")}}if(T.length){var We=T;if(We)for(var b,Yt=-1,Ct=We.length-1;Yt<Ct;){b=We[Yt+=1];var Ze=P[b];if(e.opts.strictKeywords?typeof Ze=="object"&&Object.keys(Ze).length>0||Ze===!1:e.util.schemaHasRules(Ze,e.RULES.all)){d.schema=Ze,d.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(b),d.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(b),Z?n+=" "+w+" = "+w+" || Object.keys("+h+"); for (var "+p+"=0; "+p+"<"+w+".length; "+p+"++) { var "+m+" = "+w+"["+p+"]; ":n+=" for (var "+m+" in "+h+") { ",n+=" if ("+e.usePattern(b)+".test("+m+")) { ",d.errorPath=e.util.getPathExpr(e.errorPath,m,e.opts.jsonPointers);var Ie=h+"["+m+"]";d.dataPathArr[y]=m;var he=e.validate(d);d.baseId=te,e.util.varOccurences(he,_)<2?n+=" "+e.util.varReplace(he,_,Ie)+" ":n+=" var "+_+" = "+Ie+"; "+he+" ",u&&(n+=" if (!"+v+") break; "),n+=" } ",u&&(n+=" else "+v+" = true; "),n+=" } ",u&&(n+=" if ("+v+") { ",f+="}")}}}return u&&(n+=" "+f+" if ("+g+" == errors) {"),n},pT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="errs__"+s,d=e.util.copy(e),f="";d.level++;var v="valid"+d.level;if(n+="var "+g+" = errors;",e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){d.schema=i,d.schemaPath=l,d.errSchemaPath=c;var m="key"+s,p="idx"+s,y="i"+s,_="' + "+m+" + '",w=d.dataLevel=e.dataLevel+1,E="data"+w,P="dataProperties"+s,T=e.opts.ownProperties,O=e.baseId;T&&(n+=" var "+P+" = undefined; "),T?n+=" "+P+" = "+P+" || Object.keys("+h+"); for (var "+p+"=0; "+p+"<"+P+".length; "+p+"++) { var "+m+" = "+P+"["+p+"]; ":n+=" for (var "+m+" in "+h+") { ",n+=" var startErrs"+s+" = errors; ";var M=m,J=e.compositeRule;e.compositeRule=d.compositeRule=!0;var H=e.validate(d);d.baseId=O,e.util.varOccurences(H,E)<2?n+=" "+e.util.varReplace(H,E,M)+" ":n+=" var "+E+" = "+M+"; "+H+" ",e.compositeRule=d.compositeRule=J,n+=" if (!"+v+") { for (var "+y+"=startErrs"+s+"; "+y+"<errors; "+y+"++) { vErrors["+y+"].propertyName = "+m+"; } var err = ",e.createErrors!==!1?(n+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { propertyName: '"+_+"' } ",e.opts.messages!==!1&&(n+=" , message: 'property name \\'"+_+"\\' is invalid' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; "),u&&(n+=" break; "),n+=" } }"}return u&&(n+=" "+f+" if ("+g+" == errors) {"),n},hT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data;d&&(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ");var f="schema"+s;if(!d)if(i.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var v=[],m=i;if(m)for(var p,y=-1,_=m.length-1;y<_;){p=m[y+=1];var w=e.schema.properties[p];w&&(e.opts.strictKeywords?typeof w=="object"&&Object.keys(w).length>0||w===!1:e.util.schemaHasRules(w,e.RULES.all))||(v[v.length]=p)}}else var v=i;if(d||v.length){var E=e.errorPath,P=d||v.length>=e.opts.loopRequired,T=e.opts.ownProperties;if(u)if(n+=" var missing"+s+"; ",P){d||(n+=" var "+f+" = validate.schema"+l+"; ");var O="i"+s,M="schema"+s+"["+O+"]",J="' + "+M+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,M,e.opts.jsonPointers)),n+=" var "+g+" = true; ",d&&(n+=" if (schema"+s+" === undefined) "+g+" = true; else if (!Array.isArray(schema"+s+")) "+g+" = false; else {"),n+=" for (var "+O+" = 0; "+O+" < "+f+".length; "+O+"++) { "+g+" = "+h+"["+f+"["+O+"]] !== undefined ",T&&(n+=" && Object.prototype.hasOwnProperty.call("+h+", "+f+"["+O+"]) "),n+="; if (!"+g+") break; } ",d&&(n+=" } "),n+=" if (!"+g+") { ";var H=H||[];H.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+J+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+J+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var G=n;n=H.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+G+"]); ":n+=" validate.errors = ["+G+"]; return false; ":n+=" var err = "+G+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else{n+=" if ( ";var F=v;if(F)for(var Z,O=-1,te=F.length-1;O<te;){Z=F[O+=1],O&&(n+=" || ");var pe=e.util.getProperty(Z),ve=h+pe;n+=" ( ( "+ve+" === undefined ",T&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(Z)+"') "),n+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?Z:pe)+") ) "}n+=") { ";var M="missing"+s,J="' + "+M+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(E,M,!0):E+" + "+M);var H=H||[];H.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+J+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+J+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var G=n;n=H.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+G+"]); ":n+=" validate.errors = ["+G+"]; return false; ":n+=" var err = "+G+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } else { "}else if(P){d||(n+=" var "+f+" = validate.schema"+l+"; ");var O="i"+s,M="schema"+s+"["+O+"]",J="' + "+M+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(E,M,e.opts.jsonPointers)),d&&(n+=" if ("+f+" && !Array.isArray("+f+")) { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+J+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+J+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+f+" !== undefined) { "),n+=" for (var "+O+" = 0; "+O+" < "+f+".length; "+O+"++) { if ("+h+"["+f+"["+O+"]] === undefined ",T&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", "+f+"["+O+"]) "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+J+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+J+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",d&&(n+=" } ")}else{var N=v;if(N)for(var Z,ie=-1,D=N.length-1;ie<D;){Z=N[ie+=1];var pe=e.util.getProperty(Z),J=e.util.escapeQuotes(Z),ve=h+pe;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(E,Z,e.opts.jsonPointers)),n+=" if ( "+ve+" === undefined ",T&&(n+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(Z)+"') "),n+=") { var err = ",e.createErrors!==!1?(n+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { missingProperty: '"+J+"' } ",e.opts.messages!==!1&&(n+=" , message: '",e.opts._errorDataPathProperty?n+="is a required property":n+="should have required property \\'"+J+"\\'",n+="' "),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=E}else u&&(n+=" if (true) {");return n},mT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(o||""),g="valid"+s,d=e.opts.$data&&i&&i.$data,f;if(d?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",f="schema"+s):f=i,(i||d)&&e.opts.uniqueItems!==!1){d&&(n+=" var "+g+"; if ("+f+" === false || "+f+" === undefined) "+g+" = true; else if (typeof "+f+" != 'boolean') "+g+" = false; else { "),n+=" var i = "+h+".length , "+g+" = true , j; if (i > 1) { ";var v=e.schema.items&&e.schema.items.type,m=Array.isArray(v);if(!v||v=="object"||v=="array"||m&&(v.indexOf("object")>=0||v.indexOf("array")>=0))n+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+h+"[i], "+h+"[j])) { "+g+" = false; break outer; } } } ";else{n+=" var itemIndices = {}, item; for (;i--;) { var item = "+h+"[i]; ";var p="checkDataType"+(m?"s":"");n+=" if ("+e.util[p](v,"item",e.opts.strictNumbers,!0)+") continue; ",m&&(n+=` if (typeof item == 'string') item = '"' + item; `),n+=" if (typeof itemIndices[item] == 'number') { "+g+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}n+=" } ",d&&(n+=" } "),n+=" if (!"+g+") { ";var y=y||[];y.push(n),n="",e.createErrors!==!1?(n+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(n+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(n+=" , schema: ",d?n+="validate.schema"+l:n+=""+i,n+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),n+=" } "):n+=" {} ";var _=n;n=y.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+_+"]); ":n+=" validate.errors = ["+_+"]; return false; ":n+=" var err = "+_+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n+=" } ",u&&(n+=" else { ")}else u&&(n+=" if (true) { ");return n},vT={$ref:QP,allOf:YP,anyOf:XP,$comment:eT,const:tT,contains:rT,dependencies:nT,enum:aT,format:sT,if:oT,items:iT,maximum:hm,minimum:hm,maxItems:mm,minItems:mm,maxLength:vm,minLength:vm,maxProperties:gm,minProperties:gm,multipleOf:lT,not:cT,oneOf:uT,pattern:dT,properties:fT,propertyNames:pT,required:hT,uniqueItems:mT,validate:Xh},ym=vT,vu=Ra.toHash,gT=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],r=["type","$comment"],a=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],n=["number","integer","string","array","object","boolean","null"];return e.all=vu(r),e.types=vu(n),e.forEach(function(s){s.rules=s.rules.map(function(o){var i;if(typeof o=="object"){var l=Object.keys(o)[0];i=o[l],o=l,i.forEach(function(u){r.push(u),e.all[u]=!0})}r.push(o);var c=e.all[o]={keyword:o,code:ym[o],implements:i};return c}),e.all.$comment={keyword:"$comment",code:ym.$comment},s.type&&(e.types[s.type]=s)}),e.keywords=vu(r.concat(a)),e.custom={},e},_m=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"],yT=function(t,e){for(var r=0;r<e.length;r++){t=JSON.parse(JSON.stringify(t));var a=e[r].split("/"),n=t,s;for(s=1;s<a.length;s++)n=n[a[s]];for(s=0;s<_m.length;s++){var o=_m[s],i=n[o];i&&(n[o]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return t},_T=pu.MissingRef,wT=wm;function wm(t,e,r){var a=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var n=s(t).then(function(){var i=a._addSchema(t,void 0,e);return i.validate||o(i)});return r&&n.then(function(i){r(null,i)},r),n;function s(i){var l=i.$schema;return l&&!a.getSchema(l)?wm.call(a,{$ref:l},!0):Promise.resolve()}function o(i){try{return a._compile(i)}catch(c){if(c instanceof _T)return l(c);throw c}function l(c){var u=c.missingSchema;if(d(u))throw new Error("Schema "+u+" is loaded but "+c.missingRef+" cannot be resolved");var h=a._loadingSchemas[u];return h||(h=a._loadingSchemas[u]=a._opts.loadSchema(u),h.then(g,g)),h.then(function(f){if(!d(u))return s(f).then(function(){d(u)||a.addSchema(f,u,void 0,e)})}).then(function(){return o(i)});function g(){delete a._loadingSchemas[u]}function d(f){return a._refs[f]||a._schemas[f]}}}}var bT=function(e,r,a){var n=" ",s=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h,g="data"+(o||""),d="valid"+s,f="errs__"+s,v=e.opts.$data&&i&&i.$data,m;v?(n+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",m="schema"+s):m=i;var p=this,y="definition"+s,_=p.definition,w="",E,P,T,O,M;if(v&&_.$data){M="keywordValidate"+s;var J=_.validateSchema;n+=" var "+y+" = RULES.custom['"+r+"'].definition; var "+M+" = "+y+".validate;"}else{if(O=e.useCustomRule(p,i,e.schema,e),!O)return;m="validate.schema"+l,M=O.code,E=_.compile,P=_.inline,T=_.macro}var H=M+".errors",G="i"+s,F="ruleErr"+s,Z=_.async;if(Z&&!e.async)throw new Error("async keyword in sync schema");if(P||T||(n+=""+H+" = null;"),n+="var "+f+" = errors;var "+d+";",v&&_.$data&&(w+="}",n+=" if ("+m+" === undefined) { "+d+" = true; } else { ",J&&(w+="}",n+=" "+d+" = "+y+".validateSchema("+m+"); if ("+d+") { ")),P)_.statements?n+=" "+O.validate+" ":n+=" "+d+" = "+O.validate+"; ";else if(T){var te=e.util.copy(e),w="";te.level++;var pe="valid"+te.level;te.schema=O.validate,te.schemaPath="";var ve=e.compositeRule;e.compositeRule=te.compositeRule=!0;var N=e.validate(te).replace(/validate\.schema/g,M);e.compositeRule=te.compositeRule=ve,n+=" "+N}else{var ie=ie||[];ie.push(n),n="",n+=" "+M+".call( ",e.opts.passContext?n+="this":n+="self",E||_.schema===!1?n+=" , "+g+" ":n+=" , "+m+" , "+g+" , validate.schema"+e.schemaPath+" ",n+=" , (dataPath || '')",e.errorPath!='""'&&(n+=" + "+e.errorPath);var D=o?"data"+(o-1||""):"parentData",C=o?e.dataPathArr[o]:"parentDataProperty";n+=" , "+D+" , "+C+" , rootData ) ";var z=n;n=ie.pop(),_.errors===!1?(n+=" "+d+" = ",Z&&(n+="await "),n+=""+z+"; "):Z?(H="customErrors"+s,n+=" var "+H+" = null; try { "+d+" = await "+z+"; } catch (e) { "+d+" = false; if (e instanceof ValidationError) "+H+" = e.errors; else throw e; } "):n+=" "+H+" = null; "+d+" = "+z+"; "}if(_.modifying&&(n+=" if ("+D+") "+g+" = "+D+"["+C+"];"),n+=""+w,_.valid)u&&(n+=" if (true) { ");else{n+=" if ( ",_.valid===void 0?(n+=" !",T?n+=""+pe:n+=""+d):n+=" "+!_.valid+" ",n+=") { ",h=p.keyword;var ie=ie||[];ie.push(n),n="";var ie=ie||[];ie.push(n),n="",e.createErrors!==!1?(n+=" { keyword: '"+(h||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { keyword: '"+p.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+p.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ";var A=n;n=ie.pop(),!e.compositeRule&&u?e.async?n+=" throw new ValidationError(["+A+"]); ":n+=" validate.errors = ["+A+"]; return false; ":n+=" var err = "+A+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var b=n;n=ie.pop(),P?_.errors?_.errors!="full"&&(n+=" for (var "+G+"="+f+"; "+G+"<errors; "+G+"++) { var "+F+" = vErrors["+G+"]; if ("+F+".dataPath === undefined) "+F+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+F+".schemaPath === undefined) { "+F+'.schemaPath = "'+c+'"; } ',e.opts.verbose&&(n+=" "+F+".schema = "+m+"; "+F+".data = "+g+"; "),n+=" } "):_.errors===!1?n+=" "+b+" ":(n+=" if ("+f+" == errors) { "+b+" } else { for (var "+G+"="+f+"; "+G+"<errors; "+G+"++) { var "+F+" = vErrors["+G+"]; if ("+F+".dataPath === undefined) "+F+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+F+".schemaPath === undefined) { "+F+'.schemaPath = "'+c+'"; } ',e.opts.verbose&&(n+=" "+F+".schema = "+m+"; "+F+".data = "+g+"; "),n+=" } } "):T?(n+=" var err = ",e.createErrors!==!1?(n+=" { keyword: '"+(h||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { keyword: '"+p.keyword+"' } ",e.opts.messages!==!1&&(n+=` , message: 'should pass "`+p.keyword+`" keyword validation' `),e.opts.verbose&&(n+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+g+" "),n+=" } "):n+=" {} ",n+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&u&&(e.async?n+=" throw new ValidationError(vErrors); ":n+=" validate.errors = vErrors; return false; ")):_.errors===!1?n+=" "+b+" ":(n+=" if (Array.isArray("+H+")) { if (vErrors === null) vErrors = "+H+"; else vErrors = vErrors.concat("+H+"); errors = vErrors.length; for (var "+G+"="+f+"; "+G+"<errors; "+G+"++) { var "+F+" = vErrors["+G+"]; if ("+F+".dataPath === undefined) "+F+".dataPath = (dataPath || '') + "+e.errorPath+"; "+F+'.schemaPath = "'+c+'"; ',e.opts.verbose&&(n+=" "+F+".schema = "+m+"; "+F+".data = "+g+"; "),n+=" } } else { "+b+" } "),n+=" } ",u&&(n+=" else { ")}return n};const bm={$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 Em=bm,ET={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:Em.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:Em.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}},$T=/^[a-z_$][a-z0-9_$-]*$/i,ST=bT,PT=ET,TT={add:xT,get:kT,remove:IT,validate:gu};function xT(t,e){var r=this.RULES;if(r.keywords[t])throw new Error("Keyword "+t+" is already defined");if(!$T.test(t))throw new Error("Keyword "+t+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var a=e.type;if(Array.isArray(a))for(var n=0;n<a.length;n++)o(t,a[n],e);else o(t,a,e);var s=e.metaSchema;s&&(e.$data&&this._opts.$data&&(s={anyOf:[s,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(s,!0))}r.keywords[t]=r.all[t]=!0;function o(i,l,c){for(var u,h=0;h<r.length;h++){var g=r[h];if(g.type==l){u=g;break}}u||(u={type:l,rules:[]},r.push(u));var d={keyword:i,definition:c,custom:!0,code:ST,implements:c.implements};u.rules.push(d),r.custom[i]=d}return this}function kT(t){var e=this.RULES.custom[t];return e?e.definition:this.RULES.keywords[t]||!1}function IT(t){var e=this.RULES;delete e.keywords[t],delete e.all[t],delete e.custom[t];for(var r=0;r<e.length;r++)for(var a=e[r].rules,n=0;n<a.length;n++)if(a[n].keyword==t){a.splice(n,1);break}return this}function gu(t,e){gu.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(PT,!0);if(r(t))return!0;if(gu.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}const CT={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1};var $m=CP,Jn=lu,RT=DP,Sm=Bh,OT=Yh,AT=VP,NT=gT,Pm=yT,Tm=Ra,MT=ht;ht.prototype.validate=DT,ht.prototype.compile=LT,ht.prototype.addSchema=zT,ht.prototype.addMetaSchema=UT,ht.prototype.validateSchema=qT,ht.prototype.getSchema=ZT,ht.prototype.removeSchema=HT,ht.prototype.addFormat=XT,ht.prototype.errorsText=YT,ht.prototype._addSchema=BT,ht.prototype._compile=JT,ht.prototype.compileAsync=wT;var _i=TT;ht.prototype.addKeyword=_i.add,ht.prototype.getKeyword=_i.get,ht.prototype.removeKeyword=_i.remove,ht.prototype.validateKeyword=_i.validate;var xm=pu;ht.ValidationError=xm.Validation,ht.MissingRefError=xm.MissingRef,ht.$dataMetaSchema=Pm;var wi="http://json-schema.org/draft-07/schema",km=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],jT=["/properties"];function ht(t){if(!(this instanceof ht))return new ht(t);t=this._opts=Tm.copy(t)||{},sx(this),this._schemas={},this._refs={},this._fragments={},this._formats=AT(t.format),this._cache=t.cache||new RT,this._loadingSchemas={},this._compilations=[],this.RULES=NT(),this._getId=GT(t),t.loopRequired=t.loopRequired||1/0,t.errorDataPath=="property"&&(t._errorDataPathProperty=!0),t.serialize===void 0&&(t.serialize=OT),this._metaOpts=ax(this),t.formats&&rx(this),t.keywords&&nx(this),ex(this),typeof t.meta=="object"&&this.addMetaSchema(t.meta),t.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),tx(this)}function DT(t,e){var r;if(typeof t=="string"){if(r=this.getSchema(t),!r)throw new Error('no schema with key or ref "'+t+'"')}else{var a=this._addSchema(t);r=a.validate||this._compile(a)}var n=r(e);return r.$async!==!0&&(this.errors=r.errors),n}function LT(t,e){var r=this._addSchema(t,void 0,e);return r.validate||this._compile(r)}function zT(t,e,r,a){if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.addSchema(t[n],void 0,r,a);return this}var s=this._getId(t);if(s!==void 0&&typeof s!="string")throw new Error("schema id must be string");return e=Jn.normalizeId(e||s),Cm(this,e),this._schemas[e]=this._addSchema(t,r,a,!0),this}function UT(t,e,r){return this.addSchema(t,e,r,!0),this}function qT(t,e){var r=t.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||FT(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,t);if(!a&&e){var n="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(n);else throw new Error(n)}return a}function FT(t){var e=t._opts.meta;return t._opts.defaultMeta=typeof e=="object"?t._getId(e)||e:t.getSchema(wi)?wi:void 0,t._opts.defaultMeta}function ZT(t){var e=Im(this,t);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return VT(this,t)}}function VT(t,e){var r=Jn.schema.call(t,{schema:{}},e);if(r){var a=r.schema,n=r.root,s=r.baseId,o=$m.call(t,a,n,void 0,s);return t._fragments[e]=new Sm({ref:e,fragment:!0,schema:a,root:n,baseId:s,validate:o}),o}}function Im(t,e){return e=Jn.normalizeId(e),t._schemas[e]||t._refs[e]||t._fragments[e]}function HT(t){if(t instanceof RegExp)return bi(this,this._schemas,t),bi(this,this._refs,t),this;switch(typeof t){case"undefined":return bi(this,this._schemas),bi(this,this._refs),this._cache.clear(),this;case"string":var e=Im(this,t);return e&&this._cache.del(e.cacheKey),delete this._schemas[t],delete this._refs[t],this;case"object":var r=this._opts.serialize,a=r?r(t):t;this._cache.del(a);var n=this._getId(t);n&&(n=Jn.normalizeId(n),delete this._schemas[n],delete this._refs[n])}return this}function bi(t,e,r){for(var a in e){var n=e[a];!n.meta&&(!r||r.test(a))&&(t._cache.del(n.cacheKey),delete e[a])}}function BT(t,e,r,a){if(typeof t!="object"&&typeof t!="boolean")throw new Error("schema should be object or boolean");var n=this._opts.serialize,s=n?n(t):t,o=this._cache.get(s);if(o)return o;a=a||this._opts.addUsedSchema!==!1;var i=Jn.normalizeId(this._getId(t));i&&a&&Cm(this,i);var l=this._opts.validateSchema!==!1&&!e,c;l&&!(c=i&&i==Jn.normalizeId(t.$schema))&&this.validateSchema(t,!0);var u=Jn.ids.call(this,t),h=new Sm({id:i,schema:t,localRefs:u,cacheKey:s,meta:r});return i[0]!="#"&&a&&(this._refs[i]=h),this._cache.put(s,h),l&&c&&this.validateSchema(t,!0),h}function JT(t,e){if(t.compiling)return t.validate=n,n.schema=t.schema,n.errors=null,n.root=e||n,t.schema.$async===!0&&(n.$async=!0),n;t.compiling=!0;var r;t.meta&&(r=this._opts,this._opts=this._metaOpts);var a;try{a=$m.call(this,t.schema,e,t.localRefs)}catch(s){throw delete t.validate,s}finally{t.compiling=!1,t.meta&&(this._opts=r)}return t.validate=a,t.refs=a.refs,t.refVal=a.refVal,t.root=a.root,a;function n(){var s=t.validate,o=s.apply(this,arguments);return n.errors=s.errors,o}}function GT(t){switch(t.schemaId){case"auto":return QT;case"id":return KT;default:return WT}}function KT(t){return t.$id&&this.logger.warn("schema $id ignored",t.$id),t.id}function WT(t){return t.id&&this.logger.warn("schema id ignored",t.id),t.$id}function QT(t){if(t.$id&&t.id&&t.$id!=t.id)throw new Error("schema $id is different from id");return t.$id||t.id}function YT(t,e){if(t=t||this.errors,!t)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,a=e.dataVar===void 0?"data":e.dataVar,n="",s=0;s<t.length;s++){var o=t[s];o&&(n+=a+o.dataPath+" "+o.message+r)}return n.slice(0,-r.length)}function XT(t,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[t]=e,this}function ex(t){var e;if(t._opts.$data&&(e=CT,t.addMetaSchema(e,e.$id,!0)),t._opts.meta!==!1){var r=bm;t._opts.$data&&(r=Pm(r,jT)),t.addMetaSchema(r,wi,!0),t._refs["http://json-schema.org/schema"]=wi}}function tx(t){var e=t._opts.schemas;if(e)if(Array.isArray(e))t.addSchema(e);else for(var r in e)t.addSchema(e[r],r)}function rx(t){for(var e in t._opts.formats){var r=t._opts.formats[e];t.addFormat(e,r)}}function nx(t){for(var e in t._opts.keywords){var r=t._opts.keywords[e];t.addKeyword(e,r)}}function Cm(t,e){if(t._schemas[e]||t._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function ax(t){for(var e=Tm.copy(t._opts),r=0;r<km.length;r++)delete e[km[r]];return e}function sx(t){var e=t._opts.logger;if(e===!1)t.logger={log:yu,warn:yu,error:yu};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");t.logger=e}}function yu(){}const Rm=Tf(MT);class Ns extends Fh{constructor(e,r){var a;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=r==null?void 0:r.capabilities)!==null&&a!==void 0?a:{},this._ajv=new Rm}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Zh(this._capabilities,e)}assertCapability(e,r){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{const a=await this.request({method:"initialize",params:{protocolVersion:Cs,capabilities:this._capabilities,clientInfo:this._clientInfo}},gh,r);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!ih.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(a.protocolVersion),this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,a,n,s,o;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break}}async ping(e){return this.request({method:"ping"},_n,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},zh,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},_n,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Rh,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Ih,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Eh,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},$h,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Sh,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},_n,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},_n,r)}async callTool(e,r=ii,a){const n=await this.request({method:"tools/call",params:e},r,a),s=this.getToolOutputValidator(e.name);if(s){if(!n.structuredContent&&!n.isError)throw new st(rt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{if(!s(n.structuredContent))throw new st(rt.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(o){throw o instanceof st?o:new st(rt.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return n}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(const r of e)if(r.outputSchema)try{const a=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){const a=await this.request({method:"tools/list",params:e},Ah,r);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}let Om=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function _u(t){}function Am(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=_u,onError:r=_u,onRetry:a=_u,onComment:n}=t;let s="",o=!0,i,l="",c="";function u(v){const m=o?v.replace(/^\xEF\xBB\xBF/,""):v,[p,y]=ox(`${s}${m}`);for(const _ of p)h(_);s=y,o=!1}function h(v){if(v===""){d();return}if(v.startsWith(":")){n&&n(v.slice(v.startsWith(": ")?2:1));return}const m=v.indexOf(":");if(m!==-1){const p=v.slice(0,m),y=v[m+1]===" "?2:1,_=v.slice(m+y);g(p,_,v);return}g(v,"",v)}function g(v,m,p){switch(v){case"event":c=m;break;case"data":l=`${l}${m}
9
+ `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?a(parseInt(m,10)):r(new Om(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:p}));break;default:r(new Om(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:m,line:p}));break}}function d(){l.length>0&&e({id:i,event:c||void 0,data:l.endsWith(`
10
+ `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function f(v={}){s&&v.consume&&h(s),o=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:f}}function ox(t){const e=[];let r="",a=0;for(;a<t.length;){const n=t.indexOf("\r",a),s=t.indexOf(`
11
+ `,a);let o=-1;if(n!==-1&&s!==-1?o=Math.min(n,s):n!==-1?o=n:s!==-1&&(o=s),o===-1){r=t.slice(a);break}else{const i=t.slice(a,o);e.push(i),a=o+1,t[a-1]==="\r"&&t[a]===`
12
+ `&&a++}}return[e,r]}class Nm extends Event{constructor(e,r){var a,n;super(e),this.code=(a=r==null?void 0:r.code)!=null?a:void 0,this.message=(n=r==null?void 0:r.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,a){return a(Mm(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(Mm(this),r)}}function ix(t){const e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function wu(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(wu).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${wu(t.cause)}`:t.message:`${t}`}function Mm(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var jm=t=>{throw TypeError(t)},bu=(t,e,r)=>e.has(t)||jm("Cannot "+r),De=(t,e,r)=>(bu(t,e,"read from private field"),r?r.call(t):e.get(t)),xt=(t,e,r)=>e.has(t)?jm("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),lt=(t,e,r,a)=>(bu(t,e,"write to private field"),e.set(t,r),r),cn=(t,e,r)=>(bu(t,e,"access private method"),r),Jt,Gn,Oa,Ei,$i,Ms,Aa,js,$n,Na,Ma,ja,Ds,Pr,Eu,$u,Su,Dm,Pu,Tu,Ls,xu,ku;class Si extends EventTarget{constructor(e,r){var a,n;super(),xt(this,Pr),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,xt(this,Jt),xt(this,Gn),xt(this,Oa),xt(this,Ei),xt(this,$i),xt(this,Ms),xt(this,Aa),xt(this,js,null),xt(this,$n),xt(this,Na),xt(this,Ma,null),xt(this,ja,null),xt(this,Ds,null),xt(this,$u,async s=>{var o;De(this,Na).reset();const{body:i,redirected:l,status:c,headers:u}=s;if(c===204){cn(this,Pr,Ls).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?lt(this,Oa,new URL(s.url)):lt(this,Oa,void 0),c!==200){cn(this,Pr,Ls).call(this,`Non-200 status code (${c})`,c);return}if(!(u.get("content-type")||"").startsWith("text/event-stream")){cn(this,Pr,Ls).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(De(this,Jt)===this.CLOSED)return;lt(this,Jt,this.OPEN);const h=new Event("open");if((o=De(this,Ds))==null||o.call(this,h),this.dispatchEvent(h),typeof i!="object"||!i||!("getReader"in i)){cn(this,Pr,Ls).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const g=new TextDecoder,d=i.getReader();let f=!0;do{const{done:v,value:m}=await d.read();m&&De(this,Na).feed(g.decode(m,{stream:!v})),v&&(f=!1,De(this,Na).reset(),cn(this,Pr,xu).call(this))}while(f)}),xt(this,Su,s=>{lt(this,$n,void 0),!(s.name==="AbortError"||s.type==="aborted")&&cn(this,Pr,xu).call(this,wu(s))}),xt(this,Pu,s=>{typeof s.id=="string"&&lt(this,js,s.id);const o=new MessageEvent(s.event||"message",{data:s.data,origin:De(this,Oa)?De(this,Oa).origin:De(this,Gn).origin,lastEventId:s.id||""});De(this,ja)&&(!s.event||s.event==="message")&&De(this,ja).call(this,o),this.dispatchEvent(o)}),xt(this,Tu,s=>{lt(this,Ms,s)}),xt(this,ku,()=>{lt(this,Aa,void 0),De(this,Jt)===this.CONNECTING&&cn(this,Pr,Eu).call(this)});try{if(e instanceof URL)lt(this,Gn,e);else if(typeof e=="string")lt(this,Gn,new URL(e,lx()));else throw new Error("Invalid URL")}catch{throw ix("An invalid or illegal string was specified")}lt(this,Na,Am({onEvent:De(this,Pu),onRetry:De(this,Tu)})),lt(this,Jt,this.CONNECTING),lt(this,Ms,3e3),lt(this,$i,(a=r==null?void 0:r.fetch)!=null?a:globalThis.fetch),lt(this,Ei,(n=r==null?void 0:r.withCredentials)!=null?n:!1),cn(this,Pr,Eu).call(this)}get readyState(){return De(this,Jt)}get url(){return De(this,Gn).href}get withCredentials(){return De(this,Ei)}get onerror(){return De(this,Ma)}set onerror(e){lt(this,Ma,e)}get onmessage(){return De(this,ja)}set onmessage(e){lt(this,ja,e)}get onopen(){return De(this,Ds)}set onopen(e){lt(this,Ds,e)}addEventListener(e,r,a){const n=r;super.addEventListener(e,n,a)}removeEventListener(e,r,a){const n=r;super.removeEventListener(e,n,a)}close(){De(this,Aa)&&clearTimeout(De(this,Aa)),De(this,Jt)!==this.CLOSED&&(De(this,$n)&&De(this,$n).abort(),lt(this,Jt,this.CLOSED),lt(this,$n,void 0))}}Jt=new WeakMap,Gn=new WeakMap,Oa=new WeakMap,Ei=new WeakMap,$i=new WeakMap,Ms=new WeakMap,Aa=new WeakMap,js=new WeakMap,$n=new WeakMap,Na=new WeakMap,Ma=new WeakMap,ja=new WeakMap,Ds=new WeakMap,Pr=new WeakSet,Eu=function(){lt(this,Jt,this.CONNECTING),lt(this,$n,new AbortController),De(this,$i)(De(this,Gn),cn(this,Pr,Dm).call(this)).then(De(this,$u)).catch(De(this,Su))},$u=new WeakMap,Su=new WeakMap,Dm=function(){var t;const e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...De(this,js)?{"Last-Event-ID":De(this,js)}:void 0},cache:"no-store",signal:(t=De(this,$n))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Pu=new WeakMap,Tu=new WeakMap,Ls=function(t,e){var r;De(this,Jt)!==this.CLOSED&&lt(this,Jt,this.CLOSED);const a=new Nm("error",{code:e,message:t});(r=De(this,Ma))==null||r.call(this,a),this.dispatchEvent(a)},xu=function(t,e){var r;if(De(this,Jt)===this.CLOSED)return;lt(this,Jt,this.CONNECTING);const a=new Nm("error",{code:e,message:t});(r=De(this,Ma))==null||r.call(this,a),this.dispatchEvent(a),lt(this,Aa,setTimeout(De(this,ku),De(this,Ms)))},ku=new WeakMap,Si.CONNECTING=0,Si.OPEN=1,Si.CLOSED=2;function lx(){const t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}let Iu;Iu=globalThis.crypto;async function cx(t){return(await Iu).getRandomValues(new Uint8Array(t))}async function ux(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let r="";const a=await cx(t);for(let n=0;n<t;n++){const s=a[n]%e.length;r+=e[s]}return r}async function dx(t){return await ux(t)}async function fx(t){const e=await(await Iu).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function px(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await dx(t),r=await fx(e);return{code_verifier:e,code_challenge:r}}const hx=ee({resource:j().url(),authorization_servers:ue(j().url()).optional(),jwks_uri:j().url().optional(),scopes_supported:ue(j()).optional(),bearer_methods_supported:ue(j()).optional(),resource_signing_alg_values_supported:ue(j()).optional(),resource_name:j().optional(),resource_documentation:j().optional(),resource_policy_uri:j().url().optional(),resource_tos_uri:j().url().optional(),tls_client_certificate_bound_access_tokens:gt().optional(),authorization_details_types_supported:ue(j()).optional(),dpop_signing_alg_values_supported:ue(j()).optional(),dpop_bound_access_tokens_required:gt().optional()}).passthrough(),Lm=ee({issuer:j(),authorization_endpoint:j(),token_endpoint:j(),registration_endpoint:j().optional(),scopes_supported:ue(j()).optional(),response_types_supported:ue(j()),response_modes_supported:ue(j()).optional(),grant_types_supported:ue(j()).optional(),token_endpoint_auth_methods_supported:ue(j()).optional(),token_endpoint_auth_signing_alg_values_supported:ue(j()).optional(),service_documentation:j().optional(),revocation_endpoint:j().optional(),revocation_endpoint_auth_methods_supported:ue(j()).optional(),revocation_endpoint_auth_signing_alg_values_supported:ue(j()).optional(),introspection_endpoint:j().optional(),introspection_endpoint_auth_methods_supported:ue(j()).optional(),introspection_endpoint_auth_signing_alg_values_supported:ue(j()).optional(),code_challenge_methods_supported:ue(j()).optional()}).passthrough(),mx=ee({issuer:j(),authorization_endpoint:j(),token_endpoint:j(),userinfo_endpoint:j().optional(),jwks_uri:j(),registration_endpoint:j().optional(),scopes_supported:ue(j()).optional(),response_types_supported:ue(j()),response_modes_supported:ue(j()).optional(),grant_types_supported:ue(j()).optional(),acr_values_supported:ue(j()).optional(),subject_types_supported:ue(j()),id_token_signing_alg_values_supported:ue(j()),id_token_encryption_alg_values_supported:ue(j()).optional(),id_token_encryption_enc_values_supported:ue(j()).optional(),userinfo_signing_alg_values_supported:ue(j()).optional(),userinfo_encryption_alg_values_supported:ue(j()).optional(),userinfo_encryption_enc_values_supported:ue(j()).optional(),request_object_signing_alg_values_supported:ue(j()).optional(),request_object_encryption_alg_values_supported:ue(j()).optional(),request_object_encryption_enc_values_supported:ue(j()).optional(),token_endpoint_auth_methods_supported:ue(j()).optional(),token_endpoint_auth_signing_alg_values_supported:ue(j()).optional(),display_values_supported:ue(j()).optional(),claim_types_supported:ue(j()).optional(),claims_supported:ue(j()).optional(),service_documentation:j().optional(),claims_locales_supported:ue(j()).optional(),ui_locales_supported:ue(j()).optional(),claims_parameter_supported:gt().optional(),request_parameter_supported:gt().optional(),request_uri_parameter_supported:gt().optional(),require_request_uri_registration:gt().optional(),op_policy_uri:j().optional(),op_tos_uri:j().optional()}).passthrough().merge(Lm.pick({code_challenge_methods_supported:!0})),zm=ee({access_token:j(),id_token:j().optional(),token_type:j(),expires_in:bt().optional(),scope:j().optional(),refresh_token:j().optional()}).strip(),vx=ee({error:j(),error_description:j().optional(),error_uri:j().optional()}),gx=ee({redirect_uris:ue(j()).refine(t=>t.every(e=>URL.canParse(e)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:j().optional(),grant_types:ue(j()).optional(),response_types:ue(j()).optional(),client_name:j().optional(),client_uri:j().optional(),logo_uri:j().optional(),scope:j().optional(),contacts:ue(j()).optional(),tos_uri:j().optional(),policy_uri:j().optional(),jwks_uri:j().optional(),jwks:ah().optional(),software_id:j().optional(),software_version:j().optional(),software_statement:j().optional()}).strip(),yx=ee({client_id:j(),client_secret:j().optional(),client_id_issued_at:bt().optional(),client_secret_expires_at:bt().optional()}).strip(),_x=gx.merge(yx);ee({error:j(),error_description:j().optional()}).strip(),ee({token:j(),token_type_hint:j().optional()}).strip();function wx(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function bx({requestedResource:t,configuredResource:e}){const r=typeof t=="string"?new URL(t):new URL(t.href),a=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==a.origin||r.pathname.length<a.pathname.length)return!1;const n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return n.startsWith(s)}class Mt extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Cu extends Mt{}Cu.errorCode="invalid_request";class Pi extends Mt{}Pi.errorCode="invalid_client";class Ti extends Mt{}Ti.errorCode="invalid_grant";class xi extends Mt{}xi.errorCode="unauthorized_client";class Ru extends Mt{}Ru.errorCode="unsupported_grant_type";class Ou extends Mt{}Ou.errorCode="invalid_scope";class Au extends Mt{}Au.errorCode="access_denied";class Da extends Mt{}Da.errorCode="server_error";class Nu extends Mt{}Nu.errorCode="temporarily_unavailable";class Mu extends Mt{}Mu.errorCode="unsupported_response_type";class ju extends Mt{}ju.errorCode="unsupported_token_type";class Du extends Mt{}Du.errorCode="invalid_token";class Lu extends Mt{}Lu.errorCode="method_not_allowed";class zu extends Mt{}zu.errorCode="too_many_requests";class Uu extends Mt{}Uu.errorCode="invalid_client_metadata";class qu extends Mt{}qu.errorCode="insufficient_scope";const Ex={[Cu.errorCode]:Cu,[Pi.errorCode]:Pi,[Ti.errorCode]:Ti,[xi.errorCode]:xi,[Ru.errorCode]:Ru,[Ou.errorCode]:Ou,[Au.errorCode]:Au,[Da.errorCode]:Da,[Nu.errorCode]:Nu,[Mu.errorCode]:Mu,[ju.errorCode]:ju,[Du.errorCode]:Du,[Lu.errorCode]:Lu,[zu.errorCode]:zu,[Uu.errorCode]:Uu,[qu.errorCode]:qu};class Tr extends Error{constructor(e){super(e??"Unauthorized")}}function Um(t,e){const r=t.client_secret!==void 0;return e.length===0?r?"client_secret_post":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function qm(t,e,r,a){const{client_id:n,client_secret:s}=e;switch(t){case"client_secret_basic":$x(n,s,r);return;case"client_secret_post":Sx(n,s,a);return;case"none":Px(n,a);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function $x(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const a=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${a}`)}function Sx(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Px(t,e){e.set("client_id",t)}async function Fu(t){const e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{const a=vx.parse(JSON.parse(r)),{error:n,error_description:s,error_uri:o}=a,i=Ex[n]||Da;return new i(s||"",o)}catch(a){const n=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${a}. Raw body: ${r}`;return new Da(n)}}async function La(t,e){var r,a;try{return await Zu(t,e)}catch(n){if(n instanceof Pi||n instanceof xi)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"all")),await Zu(t,e);if(n instanceof Ti)return await((a=t.invalidateCredentials)===null||a===void 0?void 0:a.call(t,"tokens")),await Zu(t,e);throw n}}async function Zu(t,{serverUrl:e,authorizationCode:r,scope:a,resourceMetadataUrl:n,fetchFn:s}){let o,i;try{o=await xx(e,{resourceMetadataUrl:n},s),o.authorization_servers&&o.authorization_servers.length>0&&(i=o.authorization_servers[0])}catch{}i||(i=e);const l=await Tx(e,t,o),c=await Ox(i,{fetchFn:s});let u=await Promise.resolve(t.clientInformation());if(!u){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const v=await jx(i,{metadata:c,clientMetadata:t.clientMetadata});await t.saveClientInformation(v),u=v}if(r!==void 0){const v=await t.codeVerifier(),m=await Nx(i,{metadata:c,clientInformation:u,authorizationCode:r,codeVerifier:v,redirectUri:t.redirectUrl,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(m),"AUTHORIZED"}const h=await t.tokens();if(h!=null&&h.refresh_token)try{const v=await Mx(i,{metadata:c,clientInformation:u,refreshToken:h.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication});return await t.saveTokens(v),"AUTHORIZED"}catch(v){if(!(!(v instanceof Mt)||v instanceof Da))throw v}const g=t.state?await t.state():void 0,{authorizationUrl:d,codeVerifier:f}=await Ax(i,{metadata:c,clientInformation:u,state:g,redirectUrl:t.redirectUrl,scope:a||t.clientMetadata.scope,resource:l});return await t.saveCodeVerifier(f),await t.redirectToAuthorization(d),"REDIRECT"}async function Tx(t,e,r){const a=wx(t);if(e.validateResourceURL)return await e.validateResourceURL(a,r==null?void 0:r.resource);if(r){if(!bx({requestedResource:a,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function Vu(t){const e=t.headers.get("WWW-Authenticate");if(!e)return;const[r,a]=e.split(" ");if(r.toLowerCase()!=="bearer"||!a)return;const s=/resource_metadata="([^"]*)"/.exec(e);if(s)try{return new URL(s[1])}catch{return}}async function xx(t,e,r=fetch){const a=await Cx(t,"oauth-protected-resource",r,{protocolVersion:e==null?void 0:e.protocolVersion,metadataUrl:e==null?void 0:e.resourceMetadataUrl});if(!a||a.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!a.ok)throw new Error(`HTTP ${a.status} trying to load well-known OAuth protected resource metadata.`);return hx.parse(await a.json())}async function Hu(t,e,r=fetch){try{return await r(t,{headers:e})}catch(a){if(a instanceof TypeError)return e?Hu(t,void 0,r):void 0;throw a}}function kx(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Fm(t,e,r=fetch){return await Hu(t,{"MCP-Protocol-Version":e},r)}function Ix(t,e){return!t||t.status===404&&e!=="/"}async function Cx(t,e,r,a){var n,s;const o=new URL(t),i=(n=a==null?void 0:a.protocolVersion)!==null&&n!==void 0?n:Cs;let l;if(a!=null&&a.metadataUrl)l=new URL(a.metadataUrl);else{const u=kx(e,o.pathname);l=new URL(u,(s=a==null?void 0:a.metadataServerUrl)!==null&&s!==void 0?s:o),l.search=o.search}let c=await Fm(l,i,r);if(!(a!=null&&a.metadataUrl)&&Ix(c,o.pathname)){const u=new URL(`/.well-known/${e}`,o);c=await Fm(u,i,r)}return c}function Rx(t){const e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",a=[];if(!r)return a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),a;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),a.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),a.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),a.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),a.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),a}async function Ox(t,{fetchFn:e=fetch,protocolVersion:r=Cs}={}){var a;const n={"MCP-Protocol-Version":r},s=Rx(t);for(const{url:o,type:i}of s){const l=await Hu(o,n,e);if(!l)throw new Error(`CORS error trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${o}`);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 ${o}`)}if(i==="oauth")return Lm.parse(await l.json());{const c=mx.parse(await l.json());if(!(!((a=c.code_challenge_methods_supported)===null||a===void 0)&&a.includes("S256")))throw new Error(`Incompatible OIDC provider at ${o}: does not support S256 code challenge method required by MCP specification`);return c}}}async function Ax(t,{metadata:e,clientInformation:r,redirectUrl:a,scope:n,state:s,resource:o}){const i="code",l="S256";let c;if(e){if(c=new URL(e.authorization_endpoint),!e.response_types_supported.includes(i))throw new Error(`Incompatible auth server: does not support response type ${i}`);if(!e.code_challenge_methods_supported||!e.code_challenge_methods_supported.includes(l))throw new Error(`Incompatible auth server: does not support code challenge method ${l}`)}else c=new URL("/authorize",t);const u=await px(),h=u.code_verifier,g=u.code_challenge;return c.searchParams.set("response_type",i),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",g),c.searchParams.set("code_challenge_method",l),c.searchParams.set("redirect_uri",String(a)),s&&c.searchParams.set("state",s),n&&c.searchParams.set("scope",n),n!=null&&n.includes("offline_access")&&c.searchParams.append("prompt","consent"),o&&c.searchParams.set("resource",o.href),{authorizationUrl:c,codeVerifier:h}}async function Nx(t,{metadata:e,clientInformation:r,authorizationCode:a,codeVerifier:n,redirectUri:s,resource:o,addClientAuthentication:i,fetchFn:l}){var c;const u="authorization_code",h=e!=null&&e.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e!=null&&e.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`);const g=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),d=new URLSearchParams({grant_type:u,code:a,code_verifier:n,redirect_uri:String(s)});if(i)i(g,d,t,e);else{const v=(c=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&c!==void 0?c:[],m=Um(r,v);qm(m,r,g,d)}o&&d.set("resource",o.href);const f=await(l??fetch)(h,{method:"POST",headers:g,body:d});if(!f.ok)throw await Fu(f);return zm.parse(await f.json())}async function Mx(t,{metadata:e,clientInformation:r,refreshToken:a,resource:n,addClientAuthentication:s,fetchFn:o}){var i;const l="refresh_token";let c;if(e){if(c=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(l))throw new Error(`Incompatible auth server: does not support grant type ${l}`)}else c=new URL("/token",t);const u=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:l,refresh_token:a});if(s)s(u,h,t,e);else{const d=(i=e==null?void 0:e.token_endpoint_auth_methods_supported)!==null&&i!==void 0?i:[],f=Um(r,d);qm(f,r,u,h)}n&&h.set("resource",n.href);const g=await(o??fetch)(c,{method:"POST",headers:u,body:h});if(!g.ok)throw await Fu(g);return zm.parse({refresh_token:a,...await g.json()})}async function jx(t,{metadata:e,clientMetadata:r,fetchFn:a}){let n;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");n=new URL(e.registration_endpoint)}else n=new URL("/register",t);const s=await(a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw await Fu(s);return _x.parse(await s.json())}class Dx extends Error{constructor(e,r,a){super(`SSE error: ${r}`),this.code=e,this.event=a}}class zs{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._eventSourceInit=r==null?void 0:r.eventSourceInit,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch}async _authThenStart(){var e;if(!this._authProvider)throw new Tr("No auth provider");let r;try{r=await La(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Tr;return await this._startOrAuth()}async _commonHeaders(){var e;const r={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(r.Authorization=`Bearer ${a.access_token}`)}return this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion),new Headers({...r,...(e=this._requestInit)===null||e===void 0?void 0:e.headers})}_startOrAuth(){var e,r,a;const n=(a=(r=(e=this===null||this===void 0?void 0:this._eventSourceInit)===null||e===void 0?void 0:e.fetch)!==null&&r!==void 0?r:this._fetch)!==null&&a!==void 0?a:fetch;return new Promise((s,o)=>{this._eventSource=new Si(this._url.href,{...this._eventSourceInit,fetch:async(i,l)=>{const c=await this._commonHeaders();c.set("Accept","text/event-stream");const u=await n(i,{...l,headers:c});return u.status===401&&u.headers.has("www-authenticate")&&(this._resourceMetadataUrl=Vu(u)),u}}),this._abortController=new AbortController,this._eventSource.onerror=i=>{var l;if(i.code===401&&this._authProvider){this._authThenStart().then(s,o);return}const c=new Dx(i.code,i.message,i);o(c),(l=this.onerror)===null||l===void 0||l.call(this,c)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",i=>{var l;const c=i;try{if(this._endpoint=new URL(c.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(u){o(u),(l=this.onerror)===null||l===void 0||l.call(this,u),this.close();return}s()}),this._eventSource.onmessage=i=>{var l,c;const u=i;let h;try{h=ln.parse(JSON.parse(u.data))}catch(g){(l=this.onerror)===null||l===void 0||l.call(this,g);return}(c=this.onmessage)===null||c===void 0||c.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Tr("No auth provider");if(await La(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Tr("Failed to authorize")}async close(){var e,r,a;(e=this._abortController)===null||e===void 0||e.abort(),(r=this._eventSource)===null||r===void 0||r.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(e){var r,a,n;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const o={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},i=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,o);if(!i.ok){if(i.status===401&&this._authProvider){if(this._resourceMetadataUrl=Vu(i),await La(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Tr;return this.send(e)}const l=await i.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${i.status}): ${l}`)}}catch(s){throw(n=this.onerror)===null||n===void 0||n.call(this,s),s}}setProtocolVersion(e){this._protocolVersion=e}}let Zm=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:a}={}){let n;super({start(s){n=Am({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:a})},transform(s){n.feed(s)}})}};const Lx={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class Bu extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}}class Us{constructor(e,r){var a;this._url=e,this._resourceMetadataUrl=void 0,this._requestInit=r==null?void 0:r.requestInit,this._authProvider=r==null?void 0:r.authProvider,this._fetch=r==null?void 0:r.fetch,this._sessionId=r==null?void 0:r.sessionId,this._reconnectionOptions=(a=r==null?void 0:r.reconnectionOptions)!==null&&a!==void 0?a:Lx}async _authThenStart(){var e;if(!this._authProvider)throw new Tr("No auth provider");let r;try{r=await La(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(a){throw(e=this.onerror)===null||e===void 0||e.call(this,a),a}if(r!=="AUTHORIZED")throw new Tr;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var e;const r={};if(this._authProvider){const n=await this._authProvider.tokens();n&&(r.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(r["mcp-session-id"]=this._sessionId),this._protocolVersion&&(r["mcp-protocol-version"]=this._protocolVersion);const a=this._normalizeHeaders((e=this._requestInit)===null||e===void 0?void 0:e.headers);return new Headers({...r,...a})}async _startOrAuthSse(e){var r,a,n;const{resumptionToken:s}=e;try{const o=await this._commonHeaders();o.set("Accept","text/event-stream"),s&&o.set("last-event-id",s);const i=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,{method:"GET",headers:o,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!i.ok){if(i.status===401&&this._authProvider)return await this._authThenStart();if(i.status===405)return;throw new Bu(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(o){throw(n=this.onerror)===null||n===void 0||n.call(this,o),o}}_getNextReconnectionDelay(e){const r=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(a,e),n)}_normalizeHeaders(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}_scheduleReconnection(e,r=0){var a;const n=this._reconnectionOptions.maxRetries;if(n>0&&r>=n){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}const s=this._getNextReconnectionDelay(r);setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,r+1)})},s)}_handleSseStream(e,r,a){if(!e)return;const{onresumptiontoken:n,replayMessageId:s}=r;let o;(async()=>{var l,c,u,h;try{const g=e.pipeThrough(new TextDecoderStream).pipeThrough(new Zm).getReader();for(;;){const{value:d,done:f}=await g.read();if(f)break;if(d.id&&(o=d.id,n==null||n(d.id)),!d.event||d.event==="message")try{const v=ln.parse(JSON.parse(d.data));s!==void 0&&Nc(v)&&(v.id=s),(l=this.onmessage)===null||l===void 0||l.call(this,v)}catch(v){(c=this.onerror)===null||c===void 0||c.call(this,v)}}}catch(g){if((u=this.onerror)===null||u===void 0||u.call(this,new Error(`SSE stream disconnected: ${g}`)),a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:n,replayMessageId:s},0)}catch(d){(h=this.onerror)===null||h===void 0||h.call(this,new Error(`Failed to reconnect: ${d instanceof Error?d.message:String(d)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Tr("No auth provider");if(await La(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Tr("Failed to authorize")}async close(){var e,r;(e=this._abortController)===null||e===void 0||e.abort(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(e,r){var a,n,s,o;try{const{resumptionToken:i,onresumptiontoken:l}=r||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:dh(e)?e.id:void 0}).catch(m=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,m)});return}const c=await this._commonHeaders();c.set("content-type","application/json"),c.set("accept","application/json, text/event-stream");const u={...this._requestInit,method:"POST",headers:c,body:JSON.stringify(e),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},h=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,u),g=h.headers.get("mcp-session-id");if(g&&(this._sessionId=g),!h.ok){if(h.status===401&&this._authProvider){if(this._resourceMetadataUrl=Vu(h),await La(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new Tr;return this.send(e)}const m=await h.text().catch(()=>null);throw new Error(`Error POSTing to endpoint (HTTP ${h.status}): ${m}`)}if(h.status===202){kS(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>{var p;return(p=this.onerror)===null||p===void 0?void 0:p.call(this,m)});return}const f=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,v=h.headers.get("content-type");if(f)if(v!=null&&v.includes("text/event-stream"))this._handleSseStream(h.body,{onresumptiontoken:l},!1);else if(v!=null&&v.includes("application/json")){const m=await h.json(),p=Array.isArray(m)?m.map(y=>ln.parse(y)):[ln.parse(m)];for(const y of p)(s=this.onmessage)===null||s===void 0||s.call(this,y)}else throw new Bu(-1,`Unexpected content type: ${v}`)}catch(i){throw(o=this.onerror)===null||o===void 0||o.call(this,i),i}}get sessionId(){return this._sessionId}async terminateSession(){var e,r,a;if(this._sessionId)try{const n=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:n,signal:(e=this._abortController)===null||e===void 0?void 0:e.signal},o=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,s);if(!o.ok&&o.status!==405)throw new Bu(o.status,`Failed to terminate session: ${o.statusText}`);this._sessionId=void 0}catch(n){throw(a=this.onerror)===null||a===void 0||a.call(this,n),n}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}}const zx="mcp";class Vm{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._socket=new WebSocket(this._url,zx),this._socket.onerror=a=>{var n;const s="error"in a?a.error:new Error(`WebSocket error: ${JSON.stringify(a)}`);r(s),(n=this.onerror)===null||n===void 0||n.call(this,s)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{var a;(a=this.onclose)===null||a===void 0||a.call(this)},this._socket.onmessage=a=>{var n,s;let o;try{o=ln.parse(JSON.parse(a.data))}catch(i){(n=this.onerror)===null||n===void 0||n.call(this,i);return}(s=this.onmessage)===null||s===void 0||s.call(this,o)}})}async close(){var e;(e=this._socket)===null||e===void 0||e.close()}send(e){return new Promise((r,a)=>{var n;if(!this._socket){a(new Error("Not connected"));return}(n=this._socket)===null||n===void 0||n.send(JSON.stringify(e)),r()})}}function ki(){const t=["224340fQYLJj","function","onmessage","port2","341XVdnBD","313767JEBgqL","950bpstaX","1354759gUhUbE","wRKyh","onclose","2044SvCTUj","endpoint","24msSkHx","164VuWYGY","mOWMr","EkZCC","addEventListener","postMessage","120705iyGzUz","8878392ivIdKn","close","_listen","3619482FaLQHc","start","_endpoint","kgkem","bzNYT","MessageChannel transport error: ","stringify","onmessageerror","HvyCv","undefined","Jwyua","message","_globalObject","parse","authInfo","thraG","220pGvxgp","_port","EGhzU","onerror","data","MhriV"];return ki=function(){return t},ki()}(function(t,e){const r=Et,a=Et,n=t();for(;;)try{if(parseInt(r(417))/1*(parseInt(r(421))/2)+parseInt(r(433))/3+parseInt(r(424))/4*(-parseInt(a(429))/5)+parseInt(a(423))/6*(-parseInt(a(418))/7)+-parseInt(a(430))/8+-parseInt(r(416))/9*(-parseInt(r(405))/10)+-parseInt(r(415))/11*(-parseInt(r(411))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(ki,650197);const Hm=()=>{const t=Et,e={EGhzU:function(r,a){return r!==a},kIrDB:"undefined",llYQe:function(r,a){return r!==a},PZfJg:function(r,a){return r(a)},Jwyua:"return this"};return typeof globalThis<"u"?globalThis:e[t(407)](typeof window,e.kIrDB)?window:e.llYQe(typeof global,e.kIrDB)?global:typeof self!==t(398)?self:e.PZfJg(Function,e[t(399)])()},Ux=(t,e,r)=>{const a=Et,n=Et,s={};s[a(410)]=n(398),s.dBkaX=function(i,l){return i===l},s[n(393)]="function";const o=s;typeof window!==o[n(410)]?t.postMessage(e,"*",r):n(428)in t&&o.dBkaX(typeof t.postMessage,o[a(393)])&&t.postMessage(e,r)},qx=(t,e)=>{const r=Et,a=Et,n={};n.MbsGh="addEventListener",n.PPniK=function(o,i){return o===i},n[r(419)]=a(412),n[a(404)]="onmessage",n[r(397)]="undefined";const s=n;s.MbsGh in t&&s.PPniK(typeof t[r(427)],s.wRKyh)?t[r(427)](r(400),e):s.thraG in t&&typeof t[a(413)]!==s[a(397)]&&(t.onmessage=e)};class qs{constructor(e){const r=Et;this[r(406)]=e}async start(){const e=Et,r=Et;this[e(406)]&&(this[e(406)][e(413)]=a=>{var n,s;const o=e,i=r;try{const l=ln[o(402)](a.data[o(400)]);(n=this[o(413)])==null||n.call(this,l,a[i(409)].extra)}catch(l){const c=new Error("MessageChannel failed to parse message: "+l);(s=this[i(408)])==null||s.call(this,c)}},this._port[e(396)]=a=>{var n;const s=r,o=r,i=new Error(s(394)+JSON[o(395)](a));(n=this.onerror)==null||n.call(this,i)},this[e(406)][e(434)]())}async send(e,r){const a={lEyuq:function(n){return n()},YihNw:function(n,s){return n(s)}};return new Promise((n,s)=>{var o;const i=Et,l=Et;try{const c={};c[i(403)]=r==null?void 0:r[i(403)];const u={};u[l(400)]=e,u.extra=c,this[l(406)]&&this[i(406)].postMessage(u),a.lEyuq(n)}catch(c){const u=c instanceof Error?c:new Error(a.YihNw(String,c));(o=this[l(408)])==null||o.call(this,u),s(u)}})}async close(){var e,r;const a=Et,n=Et;(e=this._port)==null||e[a(431)](),this._port=void 0,(r=this[n(420)])==null||r.call(this)}}class Ju extends qs{constructor(e,r=Hm()){const a=Et,n=Et,s={EkZCC:function(i,l,c,u){return i(l,c,u)}};super(),this[a(391)]=e,this[n(401)]=r;const o=new MessageChannel;this[n(406)]=o.port1,s[n(426)](Ux,this[a(401)],{endpoint:this[n(391)]},[o[n(414)]])}}class Gu extends qs{constructor(e,r=Hm()){const a=Et,n={mOWMr:function(s,o){return s===o},kgkem:function(s,o,i){return s(o,i)}};super(),this._endpoint=e,this._globalObject=r,this[a(432)]=new Promise(s=>{const o=a,i=a;n[o(392)](qx,this[i(401)],l=>{const c=i,u=i;l.data&&n[c(425)](l.data[u(422)],this[u(391)])&&(this[u(406)]=l.ports[-1*4852+1*1601+3251],s())})})}async listen(){return this[Et(432)]}}function Et(t,e){const r=ki();return Et=function(a,n){return a=a-(17*-491+-669+9407),r[a]},Et(t,e)}const Fx=()=>{const t=new MessageChannel;return[new qs(t.port1),new qs(t.port2)]};(function(t,e){const r=Ye,a=Ye,n=t();for(;;)try{if(parseInt(r(355))/1+-parseInt(r(356))/2*(-parseInt(r(373))/3)+-parseInt(r(337))/4+parseInt(a(357))/5+-parseInt(a(389))/6*(-parseInt(r(396))/7)+parseInt(a(325))/8*(parseInt(r(382))/9)+-parseInt(r(366))/10===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ii,-763475+-52067*10+1724410);const Zx=async(t,e,r)=>{var a;const n=Ye,s=Ye,o={};o[n(345)]="tools/list",o.rqstG="tools/call",o.WqUnk="resources/list",o[n(329)]=s(358),o[n(365)]=n(335),o.ookoz="resources/unsubscribe",o[n(385)]=n(340),o.VTIWq="prompts/list",o.SkoRK=n(376),o.QUtUV=n(388),o.XtowM=s(332);const i=o,{id:l,method:c,params:u}=r;let h={};switch(c){case i[s(345)]:h=await e.listTools(u);break;case i.rqstG:h=await e.callTool(u);break;case i[n(334)]:h=await e[n(350)](u);break;case i[s(329)]:h=await e.listResourceTemplates(u);break;case n(372):h=await e[n(383)](u);break;case i.HgYgW:h=await e.subscribeResource(u);break;case i.ookoz:h=await e.unsubscribeResource(u);break;case i[n(385)]:h=await e.getPrompt(u);break;case i.VTIWq:h=await e.listPrompts(u);break;case i[n(344)]:h=await e[n(376)]();break;case i.QUtUV:h=await e.complete(u);break;case n(390):h=await e[n(336)](u==null?void 0:u.level);break}const g={};g[n(361)]=h,g[n(394)]=i[n(364)],g.id=l,await((a=t==null?void 0:t.transport)==null?void 0:a[n(392)](g))},Vx=async(t,e,r)=>{var a;const n=Ye,s=Ye,o={};o.jQBBS="sampling/createMessage",o.EZqgC="elicitation/create",o[n(370)]=s(376),o.aVeaL=s(332);const i=o,{id:l,method:c,params:u}=r;let h={};switch(c){case n(368):const d={};d.method=c,d[s(367)]=u,h=await e.request(d,Xc);break;case i[s(391)]:const f={};f.method=c,f[s(367)]=u,h=await e[s(381)](f,Wc);break;case i.EZqgC:const v={};v.method=c,v.params=u,h=await e.request(v,Qc);break;case i[s(370)]:const m={};m.method=c,h=await e[s(381)](m,_n);break}const g={};return g[s(361)]=h,g.jsonrpc=i[s(387)],g.id=l,await((a=t==null?void 0:t[n(371)])==null?void 0:a.send(g)),h},Hx=(t,e)=>{const r=Ye,a={gXsjT:function(s,o){return s===o},oegpC:r(351),lZOUC:function(s,o,i,l){return s(o,i,l)},ifIKG:"2.0"},n=t._onrequest;t._onrequest=async(s,o)=>{var i,l,c,u,h;const g=r,d=r,{id:f,method:v}=s;try{a[g(333)](v,a.oegpC)?await n[g(386)](t,s,o):await a.lZOUC(Zx,t,e,s)}catch(m){const{code:p,message:y,data:_}=m;try{if(p){const w={};w.code=p,w.message=y,w.data=_;const E={};E.error=w,E[g(394)]=a[d(331)],E.id=f,await((i=t==null?void 0:t.transport)==null?void 0:i.send(E))}else(c=(l=t==null?void 0:t[d(371)])==null?void 0:l.onerror)==null||c.call(l,m)}catch(w){(h=(u=t==null?void 0:t[g(371)])==null?void 0:u.onerror)==null||h.call(u,w)}}}},Bx=(t,e)=>{const r=Ye,a=Ye,n={};n[r(363)]=function(o,i){return o!==i},n[r(398)]=r(353),n.hzhyg="notifications/cancelled";const s=n;t._onnotification=async o=>{var i,l;const c=r,u=a,{method:h,params:g}=o;if(s[c(363)](h,s[u(398)])&&(s[c(363)](h,s.hzhyg)||g!=null&&g.forward))try{await e.notification(o)}catch(d){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,d)}}},Jx=(t,e)=>async r=>{var a,n,s,o,i;const l=Ye,c=Ye,u={};u.SEmWX=l(332);const h=u;try{return await Vx(t,e,r)}catch(g){const{code:d,message:f,data:v}=g;try{if(d){const m={};m[c(377)]=d,m.message=f,m.data=v;const p={};p[c(348)]=m,p.jsonrpc=h[l(338)],p.id=r.id,await((a=t==null?void 0:t.transport)==null?void 0:a[c(392)](p))}else(s=(n=t==null?void 0:t.transport)==null?void 0:n[c(339)])==null||s.call(n,g)}catch(m){(i=(o=t==null?void 0:t[l(371)])==null?void 0:o[c(339)])==null||i.call(o,m)}}},Gx=(t,e)=>async r=>{var a,n,s;const o=Ye,i=Ye,l={};l.dtUgZ=function(g,d){return g!==d},l.jgCIb=o(353),l.uUjKY="2.0";const c=l,{method:u,params:h}=r;if(c.dtUgZ(u,c.jgCIb)&&(u!==o(400)||h!=null&&h.forward))try{const g={...r};g[o(394)]=c[i(352)],await((a=e==null?void 0:e[o(371)])==null?void 0:a[o(392)](g))}catch(g){(s=(n=t==null?void 0:t[o(371)])==null?void 0:n[i(339)])==null||s.call(n,g)}};function Ye(t,e){const r=Ii();return Ye=function(a,n){return a=a-(9*-113+-1439*-1+-97),r[a]},Ye(t,e)}const Kx=(t,e)=>async r=>{var a,n,s,o,i,l;const c=Ye,u=Ye,h={};h[c(401)]=u(332);const g=h;try{await((a=e==null?void 0:e.transport)==null?void 0:a.send(r))}catch(d){const{code:f,message:v,data:m}=d;try{if(f){const p={};p.code=f,p[c(399)]=v,p.data=m;const y={};y[c(348)]=p,y[c(394)]=g.OhJjz,y.id=r.id,await((n=t==null?void 0:t[c(371)])==null?void 0:n.send(y))}else(o=(s=t==null?void 0:t.transport)==null?void 0:s[u(339)])==null||o.call(s,d)}catch(p){(l=(i=t==null?void 0:t.transport)==null?void 0:i.onerror)==null||l.call(i,p)}}},Ku=()=>{const t=Ye,e=Ye,r={vnkqu:function(c,u){return c!==u},wxDWr:function(c,u){return c(u)},GdkkV:function(c,u){return c===u}},a=[],n=(c,u)=>{const h=Ye,g=Ye;if(u){const d=[];for(const f of a)try{d.push(f(c,u))}catch{}for(const f of d)if(r[h(379)](f,null))return f}else for(const d of a)try{r[g(343)](d,c)}catch{}},s=c=>{const u=Ye;r[u(384)](typeof c,u(369))&&!a.includes(c)&&a.push(c)},o=c=>{const u=a.indexOf(c);u!==-1&&a.splice(u,1*-6854+8*-33+7119)},i=()=>{const c=Ye;a[c(374)]=7102*1+5522+-526*24},l={};return l[t(346)]=n,l[e(330)]=s,l.removeListener=o,l[t(359)]=i,l},Wx=t=>{const e=Ye,r=Ye,a={xwPeb:function(n){return n()},Mfvzm:function(n){return n()}};{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(326)](Ku);t._onresponse=n,t[e(395)]=s,t.removeResponseListener=o,t.clearResponseListener=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[r(326)](Ku);t[r(328)]=n,t.addRequestListener=s,t[r(354)]=o,t[r(341)]=i}{const{handleListener:n,addListener:s,removeListener:o,clearListener:i}=a[e(375)](Ku);t[e(342)]=n,t[e(327)]=s,t.removeNotificationListener=o,t.clearNotificationListener=i}};function Ii(){const t=["uUjKY","notifications/initialized","removeRequestListener","96194JysfjF","36346SGEWAV","1357830AJaOeY","resources/templates/list","clearListener","iQqcJ","result","tqDZP","sSeCz","XtowM","HgYgW","3913230mjiatC","params","roots/list","function","bfmJT","transport","resources/read","27FNuDmk","length","Mfvzm","ping","code","_onresponse","vnkqu","cjSoZ","request","9gIMIPC","readResource","GdkkV","ptMjy","call","aVeaL","completion/complete","5035122lFbpzR","logging/setLevel","jQBBS","send","_requestHandlers","jsonrpc","addResponseListener","7SpcenI","ElOQH","MDIkN","message","notifications/cancelled","OhJjz","clear","672216JzFEyR","xwPeb","addNotificationListener","fallbackRequestHandler","sYzPD","addListener","ifIKG","2.0","gXsjT","WqUnk","resources/subscribe","setLoggingLevel","2491772kFUWFh","SEmWX","onerror","prompts/get","clearRequestListener","fallbackNotificationHandler","wxDWr","SkoRK","uTeHc","handleListener","Zybtx","error","originalOnResponse","listResources","initialize"];return Ii=function(){return t},Ii()}const Qx=(t,{beforeInit:e,afterInit:r}={})=>{const a=Ye,n=Ye,s={tqDZP:function(i,l){return i===l},cjSoZ:"function",iQqcJ:a(378),Zybtx:function(i,l){return i(l)},ElOQH:function(i){return i()}},o=new Map(t._notificationHandlers);t[a(393)][a(402)](),t._notificationHandlers[a(402)](),s.tqDZP(typeof e,s[a(380)])&&e(),s[a(362)](t._onresponse.name,s[a(360)])&&(t[n(349)]=t._onresponse),s[a(347)](Wx,t),t.addResponseListener(i=>{const l=n;t.originalOnResponse[l(386)](t,i)}),s.tqDZP(typeof r,s[n(380)])&&s[a(397)](r),t[n(327)](i=>{const{method:l}=i,c=o.get(l);s.tqDZP(typeof c,s.cjSoZ)&&c(i)})},Yx=Zr,Xx=Zr;(function(t,e){const r=Zr,a=Zr,n=t();for(;;)try{if(-parseInt(r(393))/1+parseInt(r(397))/2*(-parseInt(r(400))/3)+-parseInt(a(398))/4+parseInt(r(390))/5*(parseInt(a(388))/6)+-parseInt(r(389))/7+-parseInt(r(402))/8*(-parseInt(a(395))/9)+parseInt(a(399))/10*(parseInt(a(385))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ci,-1*-881393+2*180895+1*-644809);function Zr(t,e){const r=Ci();return Zr=function(a,n){return a=a-(-1861+-499*4+4241),r[a]},Zr(t,e)}function Ci(){const t=["toString","getRandomValues","2101mUsYMI","EQHzo","padStart","30UvDAkd","1609706yzlqYx","974735GrhZVO","randomUUID","REzPF","562771BvAnoG","dHTfU","2047455boiYXf","randomBytes","14664qHAdbF","3772144jLpQch","52310AkWksx","318MkjaVb","from","40WRwnSc"];return Ci=function(){return t},Ci()}const ek=()=>{const t=Zr,e=Zr,r={};r.REzPF=function(n,s){return n&s},r.suJHI=function(n,s){return n===s},r[t(386)]=function(n,s){return n&s},r[e(394)]="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";const a=r;return a.suJHI(typeof crypto,"object")&&crypto.randomUUID?crypto[e(391)]():a.dHTfU.replace(/[xy]/g,n=>{const s=t,o=t,i=a[s(392)](crypto[s(384)](new Uint8Array(-25*-62+7113+2*-4331))[741*2+-1385*-2+4252*-1],8648+-107*62+-1999);return(a.suJHI(n,"x")?i:a[o(386)](i,-4377+4*1095)|5079+461*-11).toString(9449+4*-461+-7589)})},tk=t=>{const e=Zr,r=Zr,a=new Uint8Array(t);return crypto.getRandomValues(a),Array[e(401)](a,n=>n[r(403)](-3*1739+-6509+2*5871)[e(387)](2,"0")).join("")},Sn={};Sn[Yx(391)]=ek,Sn[Xx(396)]=tk;const rr=Vr;(function(t,e){const r=Vr,a=Vr,n=t();for(;;)try{if(parseInt(r(521))/1*(parseInt(a(499))/2)+parseInt(a(543))/3*(parseInt(a(514))/4)+parseInt(r(502))/5*(parseInt(a(539))/6)+parseInt(r(553))/7+parseInt(r(516))/8*(-parseInt(r(518))/9)+-parseInt(r(531))/10+-parseInt(r(545))/11*(parseInt(r(541))/12)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ri,1472653*1+-2*-897917+-2275789);const rk=(t,e)=>{const r=Vr,a=Vr,n={FyYHt:function(l,c,u){return l(c,u)},Fxtoq:function(l,c,u){return l(c,u)}};Hx(t,e),Bx(t,e);const s=Jx(e,t),o=n[r(510)](Kx,e,t),i=n[a(549)](Gx,e,t);e[a(537)](s),e[r(519)](o),e.addNotificationListener(i),t[a(556)]=()=>{const l=a;e.removeRequestListener(s),e[l(530)](o),e[l(529)](i)}},Wu=(t,e,r)=>{const a=Vr,n={pMiva:function(i,l){return i instanceof l},TeTEy:a(546),fyZbd:function(i,l,c){return i(l,c)}},s=()=>{var i;const l=a;n.pMiva(r,zs)&&((i=r._eventSource)==null||i.addEventListener(n[l(547)],()=>{var c;const u=l;(c=r[u(509)])==null||c[u(546)]()})),rk(t,e)},o={};o.afterInit=s,n.fyZbd(Qx,e,o)},Bm=(t,e=Sn.randomUUID())=>{const r=Vr,a=Vr,n={OfssH:function(u,h,g){return u(h,g)}},s={};s[r(528)]=e;const o=s,i={};i[r(528)]=e;const l={};l[a(558)]=i,l[r(534)]=r(524);const c={requestInit:l,eventSourceInit:{async fetch(u,h){const g=r,d=a,f=new Headers((h==null?void 0:h[g(558)])||{});Object.entries(o)[d(498)](([m,p])=>{f[d(527)](m,p)});const v={...h};return v[d(558)]=f,n.OfssH(fetch,u,v)},withCredentials:!0}};return t&&(c.requestInit[r(558)].Authorization=r(533)+t,o.Authorization="Bearer "+t),c},Jm=(t,e=Sn[rr(517)]())=>{const r=rr,a=rr,n={};n.nwQhY="include";const s=n,o={};o["stream-session-id"]=e;const i={};i.headers=o,i.credentials=s[r(520)];const l={};l[r(544)]=i;const c=l;return t&&(c.requestInit.headers[a(552)]=a(533)+t),c},Qu=async(t,e,r)=>{const a=rr,n=rr,s={CFfFC:function(i){return i()},egwVO:function(i,l,c,u){return i(l,c,u)}},o=s.CFfFC(r);try{return await t[a(538)](o),o}catch(i){if(i instanceof Tr){const l=await e();return await o[n(505)](l),await s[a(525)](Qu,t,e,r)}else throw i}};function Vr(t,e){const r=Ri();return Vr=function(a,n){return a=a-(74*-67+-8341+-73*-189),r[a]},Vr(t,e)}const Gm=(t,e)=>{const r=rr,a=rr,n={};n.RsKXs=function(o,i){return o in i},n.PBhps="waitForOAuthCode",n[r(535)]="function",n[r(507)]="waitForOAuthCode need to be provided when authProvider is provided";const s=n;if(s.RsKXs(s[a(551)],t))return t[a(523)];if(typeof e===s.yTKoP)return e;throw new Error(s.RZhOv)},nk=async t=>{const e=rr,r=rr,a={TFSRn:function(M,J,H){return M(J,H)},HwvVa:"mcp-sse-proxy-client",ufTHS:function(M){return M()},WIVYl:function(M,J,H,G){return M(J,H,G)},jniGY:"sessionId"},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:c,eventSourceInit:u,waitForOAuthCode:h}=t,g={};g.authProvider=l,g.requestInit=c,g.eventSourceInit=u;const d=g,f=i||Sn.randomUUID(),v=a[e(506)](Bm,o,f);if(c){const M={...v.requestInit,...c};M.headers={...v[e(544)].headers,...c.headers},d.requestInit=M}else d[r(544)]=v.requestInit;if(u){const M={...v[e(559)],...u};d.eventSourceInit=M}else d.eventSourceInit=v.eventSourceInit;const m={};m.listChanged=!0;const p={};p.roots=m,p.sampling={},p[e(511)]={};const y=p,_={};_[r(536)]=a.HwvVa,_.version=e(526);const w={};w.capabilities=y;const E=new Ns(_,w),P=()=>new zs(new URL(s),d);let T=a[r(504)](P);if(l){const M=a[e(506)](Gm,l,h);T=await a[r(513)](Qu,E,M,P)}else await E[e(538)](T);a[r(513)](Wu,E,n,T),T[r(557)]=T[r(542)].searchParams[r(532)](a.jniGY);const O={};return O.transport=T,O.sessionId=T[e(557)],O};function Ri(){const t=["ufTHS","finishAuth","TFSRn","RZhOv","Vajmx","_eventSource","FyYHt","elicitation","transport","WIVYl","13320uyrBtN","sampling","8WTwLJD","randomUUID","6438654bkJHij","addResponseListener","nwQhY","11721GVgRMJ","?sessionId=","waitForOAuthCode","include","egwVO","1.0.0","set","sse-session-id","removeNotificationListener","removeResponseListener","11838520fNkjrV","get","Bearer ","credentials","yTKoP","name","addRequestListener","connect","18VhCgQv","mcp-socket-proxy-client","2819364JNqkQZ","_endpoint","699JyrxCR","requestInit","44ofbsvb","close","TeTEy","QgzDy","Fxtoq","roots","PBhps","Authorization","11309130xGCFwl","&token=","version","onclose","sessionId","headers","eventSourceInit","forEach","62FcOkCa","mcp-stream-proxy-client","zXcpO","1794855cQEXDT","biJOc"];return Ri=function(){return t},Ri()}const ak=async t=>{const e=rr,r=rr,a={Vajmx:e(500),biJOc:function(M){return M()},zXcpO:function(M,J,H){return M(J,H)},zDnjZ:function(M,J,H,G){return M(J,H,G)},FQMAh:function(M,J,H,G){return M(J,H,G)}},{client:n,url:s,token:o,sessionId:i,authProvider:l,requestInit:c,reconnectionOptions:u,waitForOAuthCode:h}=t,g={};g.authProvider=l,g.requestInit=c,g.reconnectionOptions=u;const d=g,f=i||Sn.randomUUID(),v=Jm(o,f);if(c){const M={...v.requestInit,...c};M.headers={...v.requestInit.headers,...c.headers},d[e(544)]=M}else d.requestInit=v.requestInit;const m={};m.listChanged=!0;const p={};p[r(550)]=m,p.sampling={},p.elicitation={};const y=p,_={};_[e(536)]=a[r(508)],_[e(555)]="1.0.0";const w={};w.capabilities=y;const E=new Ns(_,w),P=()=>new Us(new URL(s),d);let T=a[e(503)](P);if(l){const M=a[e(501)](Gm,l,h);T=await a.zDnjZ(Qu,E,M,P)}else await E.connect(T);a.FQMAh(Wu,E,n,T);const O={};return O.transport=T,O[r(557)]=T.sessionId,O},sk=async t=>{const e=rr,r=rr,a={QgzDy:e(540),jkaVB:function(p,y,_,w){return p(y,_,w)}},{client:n,url:s,token:o,sessionId:i}=t,l={};l.listChanged=!0;const c={};c[e(550)]=l,c[e(515)]={},c[r(511)]={};const u=c,h={};h.name=a[r(548)],h[r(555)]=r(526);const g={};g.capabilities=u;const d=new Ns(h,g),f=i||Sn[r(517)](),v=new Vm(new URL(s+e(522)+f+r(554)+o));await d.connect(v),a.jkaVB(Wu,d,n,v);const m={};return m[e(512)]=v,m[r(557)]=f,m},Fs=Gt,Oi=Gt;function Gt(t,e){const r=Ai();return Gt=function(a,n){return a=a-(-16761+51*337),r[a]},Gt(t,e)}(function(t,e){const r=Gt,a=Gt,n=t();for(;;)try{if(-parseInt(r(440))/1+-parseInt(r(458))/2*(parseInt(r(448))/3)+-parseInt(r(451))/4*(parseInt(a(449))/5)+-parseInt(a(455))/6+-parseInt(r(427))/7+-parseInt(a(438))/8*(parseInt(a(459))/9)+parseInt(r(430))/10*(parseInt(a(436))/11)===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ai,-220880+1*-333337+-2*-384996);function Ai(){const t=["650XPHLhD","redirectToAuthorization","10856jPvMVb","GET","qcFPW","_redirectUrl","2187414WnlGuZ","resolve","tokens","3976YyOqUl","27ejNHsa","Content-Type","waitForOAuthCode","2903796yvWZFa","_clientMetadata","application/x-www-form-urlencoded","10beEWJk","json","code","_callBackPromise","reject","saveClientInformation","20776349mLNCcF","_codeVerifier","629912aTknXq","_tokens","52074GwcpRo","state","_state","_redirectCallback","_clientInformation","redirect_uris","Failed to redirect: ","clientInformation","381aduWsB"];return Ai=function(){return t},Ai()}const ok=()=>Sn.randomBytes(3485*1+-261+-3184);class ik{constructor(e){const r=Gt,a=Gt;this._callBackPromise={};const{clientMetadata:n,state:s,redirectCallback:o,getAuthCodeByState:i,waitForOAuthCode:l}=e;this[r(428)]=n,this[r(454)]=n[r(445)][0],this._state=s||ok(),this._redirectCallback=o||this.redirectCallbackFunction,this._getAuthCodeByState=i||this.getAuthCodeByStateFunction,this[a(426)]=l||this.waitForOAuthCodeFunction()}async redirectCallbackFunction(e){var r,a,n,s,o,i;const l=Gt,c=Gt,u={qITTp:function(f,v,m){return f(v,m)},qcFPW:l(452)},h=await u.qITTp(fetch,e,{method:u[l(453)]});!h.ok&&((a=(r=this._callBackPromise).reject)==null||a.call(r,c(446)+h.statusText));const g=await this._getAuthCodeByState(this[c(454)],this[l(442)]);if(!g.ok){(s=(n=this[l(433)]).reject)==null||s.call(n,"Failed to fetch auth code: "+g.statusText);return}const d=await g[l(431)]();(i=(o=this[c(433)])[l(456)])==null||i.call(o,d[l(432)])}async getAuthCodeByStateFunction(e,r){const a=Gt,n=Gt,s={};s.tuSmb=a(429);const o=s,i={};i[a(460)]=o.tuSmb;const l={};return l[n(441)]=r,fetch(e,{method:"POST",headers:i,body:new URLSearchParams(l)})}waitForOAuthCodeFunction(){const e=Gt,r=this[e(433)];return()=>new Promise((a,n)=>{const s=e;r.resolve=a,r[s(434)]=n})}get redirectUrl(){return this[Gt(454)]}get clientMetadata(){return this._clientMetadata}state(){return this._state}[Fs(447)](){return this[Fs(444)]}[Oi(435)](e){const r=Fs;this[r(444)]=e}[Oi(457)](){return this[Oi(439)]}saveTokens(e){this._tokens=e}[Oi(450)](e){this[Fs(443)](e)}saveCodeVerifier(e){this._codeVerifier=e}codeVerifier(){if(!this[Fs(437)])throw new Error("No code verifier saved");return this._codeVerifier}}(function(t,e){for(var r=Mi,a=Mi,n=t();;)try{var s=parseInt(r(361))/1*(parseInt(a(363))/2)+-parseInt(r(358))/3+parseInt(r(359))/4*(parseInt(r(357))/5)+parseInt(a(354))/6*(parseInt(r(360))/7)+parseInt(a(362))/8+parseInt(a(364))/9+-parseInt(a(356))/10*(parseInt(r(355))/11);if(s===e)break;n.push(n.shift())}catch{n.push(n.shift())}})(Ni,-73523*-3+1*-407717+530518);function Ni(){var t=["40ecBYYe","1095owKKYD","486870YOVwZy","5752xWiyTO","561484biNVMw","1fWJmxQ","1866064SPnyhb","1109522vMiuMX","1602351pPEGwH","12sVyMLL","2573296LTwOhv"];return Ni=function(){return t},Ni()}function Mi(t,e){var r=Ni();return Mi=function(a,n){a=a-(-1*-642+503*-5+2227);var s=r[a];return s},Mi(t,e)}class lk extends Fh{constructor(e,r){var a;super(r),this._serverInfo=e,this._capabilities=(a=r==null?void 0:r.capabilities)!==null&&a!==void 0?a:{},this._instructions=r==null?void 0:r.instructions,this.setRequestHandler(vh,n=>this._oninitialize(n)),this.setNotificationHandler(jc,()=>{var n;return(n=this.oninitialized)===null||n===void 0?void 0:n.call(this)})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Zh(this._capabilities,e)}assertCapabilityForMethod(e){var r,a,n;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(!((a=this._clientCapabilities)===null||a===void 0)&&a.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break}}async _oninitialize(e){const r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:ih.includes(r)?r:Cs,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(e,r){return this.request({method:"sampling/createMessage",params:e},Wc,r)}async elicitInput(e,r){const a=await this.request({method:"elicitation/create",params:e},Qc,r);if(a.action==="accept"&&a.content)try{const n=new Rm,s=n.compile(e.requestedSchema);if(!s(a.content))throw new st(rt.InvalidParams,`Elicitation response content does not match requested schema: ${n.errorsText(s.errors)}`)}catch(n){throw n instanceof st?n:new st(rt.InternalError,`Error validating elicitation response: ${n}`)}return a}async listRoots(e,r){return this.request({method:"roots/list",params:e},Xc,r)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}const ck=Symbol("Let zodToJsonSchema decide on which parser to use"),Km={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"},uk=t=>typeof t=="string"?{...Km,name:t}:{...Km,...t},dk=t=>{const e=uk(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}};function Wm(t,e,r,a){a!=null&&a.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Ge(t,e,r,a,n){t[e]=r,Wm(t,e,a,n)}const Qm=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Kt(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Qm(e,t.currentPath):e.join("/")}}function fk(t,e){var a,n,s;const r={type:"array"};return(a=t.type)!=null&&a._def&&((s=(n=t.type)==null?void 0:n._def)==null?void 0:s.typeName)!==V.ZodAny&&(r.items=Be(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Ge(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Ge(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Ge(r,"minItems",t.exactLength.value,t.exactLength.message,e),Ge(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function pk(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const a of t.checks)switch(a.kind){case"min":e.target==="jsonSchema7"?a.inclusive?Ge(r,"minimum",a.value,a.message,e):Ge(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),Ge(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?Ge(r,"maximum",a.value,a.message,e):Ge(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),Ge(r,"maximum",a.value,a.message,e));break;case"multipleOf":Ge(r,"multipleOf",a.value,a.message,e);break}return r}function hk(){return{type:"boolean"}}function Ym(t,e){return Be(t.type._def,e)}const mk=(t,e)=>Be(t.innerType._def,e);function Xm(t,e,r){const a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,s)=>Xm(t,e,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return vk(t,e)}}const vk=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const a of t.checks)switch(a.kind){case"min":Ge(r,"minimum",a.value,a.message,e);break;case"max":Ge(r,"maximum",a.value,a.message,e);break}return r};function gk(t,e){return{...Be(t.innerType._def,e),default:t.defaultValue()}}function yk(t,e){return e.effectStrategy==="input"?Be(t.schema._def,e):Kt(e)}function _k(t){return{type:"string",enum:Array.from(t.values)}}const wk=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function bk(t,e){const r=[Be(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Be(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let a=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const n=[];return r.forEach(s=>{if(wk(s))n.push(...s.allOf),s.unevaluatedProperties===void 0&&(a=void 0);else{let o=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:i,...l}=s;o=l}else a=void 0;n.push(o)}}),n.length?{allOf:n,...a}:void 0}function Ek(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let Yu;const xr={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:()=>(Yu===void 0&&(Yu=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Yu),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 ev(t,e){const r={type:"string"};if(t.checks)for(const a of t.checks)switch(a.kind){case"min":Ge(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e);break;case"max":Ge(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"email":switch(e.emailStrategy){case"format:email":kr(r,"email",a.message,e);break;case"format:idn-email":kr(r,"idn-email",a.message,e);break;case"pattern:zod":Ft(r,xr.email,a.message,e);break}break;case"url":kr(r,"uri",a.message,e);break;case"uuid":kr(r,"uuid",a.message,e);break;case"regex":Ft(r,a.regex,a.message,e);break;case"cuid":Ft(r,xr.cuid,a.message,e);break;case"cuid2":Ft(r,xr.cuid2,a.message,e);break;case"startsWith":Ft(r,RegExp(`^${Xu(a.value,e)}`),a.message,e);break;case"endsWith":Ft(r,RegExp(`${Xu(a.value,e)}$`),a.message,e);break;case"datetime":kr(r,"date-time",a.message,e);break;case"date":kr(r,"date",a.message,e);break;case"time":kr(r,"time",a.message,e);break;case"duration":kr(r,"duration",a.message,e);break;case"length":Ge(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e),Ge(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"includes":{Ft(r,RegExp(Xu(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&kr(r,"ipv4",a.message,e),a.version!=="v4"&&kr(r,"ipv6",a.message,e);break}case"base64url":Ft(r,xr.base64url,a.message,e);break;case"jwt":Ft(r,xr.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&Ft(r,xr.ipv4Cidr,a.message,e),a.version!=="v4"&&Ft(r,xr.ipv6Cidr,a.message,e);break}case"emoji":Ft(r,xr.emoji(),a.message,e);break;case"ulid":{Ft(r,xr.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{kr(r,"binary",a.message,e);break}case"contentEncoding:base64":{Ge(r,"contentEncoding","base64",a.message,e);break}case"pattern:zod":{Ft(r,xr.base64,a.message,e);break}}break}case"nanoid":Ft(r,xr.nanoid,a.message,e)}return r}function Xu(t,e){return e.patternStrategy==="escape"?Sk(t):t}const $k=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Sk(t){let e="";for(let r=0;r<t.length;r++)$k.has(t[r])||(e+="\\"),e+=t[r];return e}function kr(t,e,r,a){var n;t.format||(n=t.anyOf)!=null&&n.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&a.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&a.errorMessages&&{errorMessage:{format:r}}})):Ge(t,"format",e,r,a)}function Ft(t,e,r,a){var n;t.pattern||(n=t.allOf)!=null&&n.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&a.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:tv(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):Ge(t,"pattern",tv(e,a),r,a)}function tv(t,e){var l;if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},a=r.i?t.source.toLowerCase():t.source;let n="",s=!1,o=!1,i=!1;for(let c=0;c<a.length;c++){if(s){n+=a[c],s=!1;continue}if(r.i){if(o){if(a[c].match(/[a-z]/)){i?(n+=a[c],n+=`${a[c-2]}-${a[c]}`.toUpperCase(),i=!1):a[c+1]==="-"&&((l=a[c+2])!=null&&l.match(/[a-z]/))?(n+=a[c],i=!0):n+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){n+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(r.m){if(a[c]==="^"){n+=`(^|(?<=[\r
13
13
  ]))`;continue}else if(a[c]==="$"){n+=`($|(?=[\r
14
14
  ]))`;continue}}if(r.s&&a[c]==="."){n+=o?`${a[c]}\r
15
15
  `:`[${a[c]}\r
16
- ]`;continue}n+=a[c],a[c]==="\\"?s=!0:o&&a[c]==="]"?o=!1:!o&&a[c]==="["&&(o=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return n}function tv(t,e){var a,n,s,o,i,l;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((a=t.keyType)==null?void 0:a._def.typeName)===V.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((c,u)=>({...c,[u]:Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",u]})??rr(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(((n=t.keyType)==null?void 0:n._def.typeName)===V.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:c,...u}=Xm(t.keyType._def,e);return{...r,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===V.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(((i=t.keyType)==null?void 0:i._def.typeName)===V.ZodBranded&&t.keyType._def.type._def.typeName===V.ZodString&&((l=t.keyType._def.type._def.checks)!=null&&l.length)){const{type:c,...u}=Qm(t.keyType._def,e);return{...r,propertyNames:u}}}return r}function _x(t,e){if(e.mapStrategy==="record")return tv(t,e);const r=Je(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||rr(e),a=Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||rr(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function wx(t){const e=t.values,a=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(a.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}function bx(t){return t.target==="openAi"?void 0:{not:rr({...t,currentPath:[...t.currentPath,"not"]})}}function Ex(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Bi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Sx(t,e){if(e.target==="openApi3")return rv(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(a=>a._def.typeName in Bi&&(!a._def.checks||!a._def.checks.length))){const a=r.reduce((n,s)=>{const o=Bi[s._def.typeName];return o&&!n.includes(o)?[...n,o]:n},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=r.reduce((n,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...n,o];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(a.length===r.length){const n=a.filter((s,o,i)=>i.indexOf(s)===o);return{type:n.length>1?n:n[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,n)=>[...a,...n._def.values.filter(s=>!a.includes(s))],[])};return rv(t,e)}const rv=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,n)=>Je(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function $x(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Bi[t.innerType._def.typeName],nullable:!0}:{type:[Bi[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const a=Je(t.innerType._def,{...e,currentPath:[...e.currentPath]});return a&&"$ref"in a?{allOf:[a],nullable:!0}:a&&{...a,nullable:!0}}const r=Je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Px(t,e){const r={type:"number"};if(!t.checks)return r;for(const a of t.checks)switch(a.kind){case"int":r.type="integer",Km(r,"type",a.message,e);break;case"min":e.target==="jsonSchema7"?a.inclusive?Ke(r,"minimum",a.value,a.message,e):Ke(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),Ke(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?Ke(r,"maximum",a.value,a.message,e):Ke(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),Ke(r,"maximum",a.value,a.message,e));break;case"multipleOf":Ke(r,"multipleOf",a.value,a.message,e);break}return r}function kx(t,e){const r=e.target==="openAi",a={type:"object",properties:{}},n=[],s=t.shape();for(const i in s){let l=s[i];if(l===void 0||l._def===void 0)continue;let c=xx(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=Je(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});u!==void 0&&(a.properties[i]=u,c||n.push(i))}n.length&&(a.required=n);const o=Ix(t,e);return o!==void 0&&(a.additionalProperties=o),a}function Ix(t,e){if(t.catchall._def.typeName!=="ZodNever")return Je(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function xx(t){try{return t.isOptional()}catch{return!0}}const Tx=(t,e)=>{var a;if(e.currentPath.toString()===((a=e.propertyPath)==null?void 0:a.toString()))return Je(t.innerType._def,e);const r=Je(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:rr(e)},r]}:rr(e)},Cx=(t,e)=>{if(e.pipeStrategy==="input")return Je(t.in._def,e);if(e.pipeStrategy==="output")return Je(t.out._def,e);const r=Je(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=Je(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(n=>n!==void 0)}};function Rx(t,e){return Je(t.type._def,e)}function Ox(t,e){const a={type:"array",uniqueItems:!0,items:Je(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Ke(a,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Ke(a,"maxItems",t.maxSize.value,t.maxSize.message,e),a}function Nx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,a)=>Je(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),additionalItems:Je(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,a)=>Je(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function Ax(t){return{not:rr(t)}}function Mx(t){return rr(t)}const jx=(t,e)=>Je(t.innerType._def,e),Dx=(t,e,r)=>{switch(e){case V.ZodString:return Xm(t,r);case V.ZodNumber:return Px(t,r);case V.ZodObject:return kx(t,r);case V.ZodBigInt:return ix(t,r);case V.ZodBoolean:return lx();case V.ZodDate:return Ym(t,r);case V.ZodUndefined:return Ax(r);case V.ZodNull:return Ex(r);case V.ZodArray:return ox(t,r);case V.ZodUnion:case V.ZodDiscriminatedUnion:return Sx(t,r);case V.ZodIntersection:return mx(t,r);case V.ZodTuple:return Nx(t,r);case V.ZodRecord:return tv(t,r);case V.ZodLiteral:return vx(t,r);case V.ZodEnum:return fx(t);case V.ZodNativeEnum:return wx(t);case V.ZodNullable:return $x(t,r);case V.ZodOptional:return Tx(t,r);case V.ZodMap:return _x(t,r);case V.ZodSet:return Ox(t,r);case V.ZodLazy:return()=>t.getter()._def;case V.ZodPromise:return Rx(t,r);case V.ZodNaN:case V.ZodNever:return bx(r);case V.ZodEffects:return px(t,r);case V.ZodAny:return rr(r);case V.ZodUnknown:return Mx(r);case V.ZodDefault:return dx(t,r);case V.ZodBranded:return Qm(t,r);case V.ZodReadonly:return jx(t,r);case V.ZodCatch:return cx(t,r);case V.ZodPipeline:return Cx(t,r);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return(a=>{})()}};function Je(t,e,r=!1){var i;const a=e.seen.get(t);if(e.override){const l=(i=e.override)==null?void 0:i.call(e,t,e,a,r);if(l!==nx)return l}if(a&&!r){const l=Lx(a,e);if(l!==void 0)return l}const n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);const s=Dx(t,t.typeName,e),o=typeof s=="function"?Je(s(),e):s;if(o&&zx(t,e,o),e.postProcess){const l=e.postProcess(o,t,e);return n.jsonSchema=o,l}return n.jsonSchema=o,o}const Lx=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Wm(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),rr(e)):e.$refStrategy==="seen"?rr(e):void 0}},zx=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),nv=(t,e)=>{const r=sx(e);let a=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,u])=>({...l,[c]:Je(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??rr(r)}),{}):void 0;const n=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,s=Je(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??rr(r),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(s.title=o),r.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[r.openAiAnyTypeName]||(a[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=n===void 0?a?{...s,[r.definitionPath]:a}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]: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};var ud;(function(t){t.Completable="McpCompletable"})(ud||(ud={}));class Ji extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}}Ji.create=(t,e)=>new Ji({type:t,typeName:ud.Completable,complete:e.complete,...qx(e)});function Ux(t,e){return Ji.create(t,{...t._def,complete:e})}function qx(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,i)=>{var l,c;const{message:u}=t;return o.code==="invalid_enum_value"?{message:u??i.defaultError}:typeof i.data>"u"?{message:(l=u??a)!==null&&l!==void 0?l:i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:(c=u??r)!==null&&c!==void 0?c:i.defaultError}},description:n}}const av=1e6,dd=1e6,sv=1e4,Fx=1e6;class _n{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,a){if(e.length>r)throw new Error(`${a} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){_n.validateLength(e,av,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const r=[];let a="",n=0,s=0;for(;n<e.length;)if(e[n]==="{"){a&&(r.push(a),a="");const o=e.indexOf("}",n);if(o===-1)throw new Error("Unclosed template expression");if(s++,s>sv)throw new Error(`Template contains too many expressions (max ${sv})`);const i=e.slice(n+1,o),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),f=u[0];for(const g of u)_n.validateLength(g,dd,"Variable name");r.push({name:f,operator:l,names:u,exploded:c}),n=o+1}else a+=e[n],n++;return a&&r.push(a),r}getOperator(e){return["+","#",".","/","?","&"].find(a=>e.startsWith(a))||""}getNames(e){const r=this.getOperator(e);return e.slice(r.length).split(",").map(a=>a.replace("*","").trim()).filter(a=>a.length>0)}encodeValue(e,r){return _n.validateLength(e,dd,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){const o=e.names.map(l=>{const c=r[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(f=>this.encodeValue(f,e.operator)).join(","):this.encodeValue(c.toString(),e.operator);return`${l}=${u}`}).filter(l=>l.length>0);return o.length===0?"":(e.operator==="?"?"?":"&")+o.join("&")}if(e.names.length>1){const o=e.names.map(i=>r[i]).filter(i=>i!==void 0);return o.length===0?"":o.map(i=>Array.isArray(i)?i[0]:i).join(",")}const a=r[e.name];if(a===void 0)return"";const s=(Array.isArray(a)?a:[a]).map(o=>this.encodeValue(o,e.operator));switch(e.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(e){let r="",a=!1;for(const n of this.parts){if(typeof n=="string"){r+=n;continue}const s=this.expandPart(n,e);s&&((n.operator==="?"||n.operator==="&")&&a?r+=s.replace("?","&"):r+=s,(n.operator==="?"||n.operator==="&")&&(a=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const r=[];for(const s of e.names)_n.validateLength(s,dd,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let s=0;s<e.names.length;s++){const o=e.names[s],i=s===0?"\\"+e.operator:"&";r.push({pattern:i+this.escapeRegExp(o)+"=([^&]+)",name:o})}return r}let a;const n=e.name;switch(e.operator){case"":a=e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)";break;case"+":case"#":a="(.+)";break;case".":a="\\.([^/,]+)";break;case"/":a="/"+(e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)");break;default:a="([^/]+)"}return r.push({pattern:a,name:n}),r}match(e){_n.validateLength(e,av,"URI");let r="^";const a=[];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,a.push({name:u,exploded:i.exploded})}r+="$",_n.validateLength(r,Fx,"Generated regex pattern");const n=new RegExp(r),s=e.match(n);if(!s)return null;const o={};for(let i=0;i<a.length;i++){const{name:l,exploded:c}=a[i],u=s[i+1],f=l.replace("*","");c&&u.includes(",")?o[f]=u.split(","):o[f]=u}return o}}class ov{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new rx(e,r)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ru.shape.method.value),this.server.assertCanSetRequestHandler(nu.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(ru,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{const a={name:e,title:r.title,description:r.description,inputSchema:r.inputSchema?nv(r.inputSchema,{strictUnions:!0}):Vx,annotations:r.annotations,_meta:r._meta};return r.outputSchema&&(a.outputSchema=nv(r.outputSchema,{strictUnions:!0})),a})})),this.server.setRequestHandler(nu,async(e,r)=>{const a=this._registeredTools[e.params.name];if(!a)throw new st(rt.InvalidParams,`Tool ${e.params.name} not found`);if(!a.enabled)throw new st(rt.InvalidParams,`Tool ${e.params.name} disabled`);let n;if(a.inputSchema){const s=await a.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new st(rt.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);const o=s.data,i=a.callback;try{n=await Promise.resolve(i(o,r))}catch(l){n={content:[{type:"text",text:l instanceof Error?l.message:String(l)}],isError:!0}}}else{const s=a.callback;try{n=await Promise.resolve(s(r))}catch(o){n={content:[{type:"text",text:o instanceof Error?o.message:String(o)}],isError:!0}}}if(a.outputSchema&&!n.isError){if(!n.structuredContent)throw new st(rt.InvalidParams,`Tool ${e.params.name} has an output schema but no structured content was provided`);const s=await a.outputSchema.safeParseAsync(n.structuredContent);if(!s.success)throw new st(rt.InvalidParams,`Invalid structured content for tool ${e.params.name}: ${s.error.message}`)}return n}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ou.shape.method.value),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ou,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new st(rt.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const a=this._registeredPrompts[r.name];if(!a)throw new st(rt.InvalidParams,`Prompt ${r.name} not found`);if(!a.enabled)throw new st(rt.InvalidParams,`Prompt ${r.name} disabled`);if(!a.argsSchema)return Gi;const n=a.argsSchema.shape[e.params.argument.name];if(!(n instanceof Ji))return Gi;const o=await n._def.complete(e.params.argument.value,e.params.context);return lv(o)}async handleResourceCompletion(e,r){const a=Object.values(this._registeredResourceTemplates).find(o=>o.resourceTemplate.uriTemplate.toString()===r.uri);if(!a){if(this._registeredResources[r.uri])return Gi;throw new st(rt.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const n=a.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return Gi;const s=await n(e.params.argument.value,e.params.context);return lv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(pi.shape.method.value),this.server.assertCanSetRequestHandler(Kc.shape.method.value),this.server.assertCanSetRequestHandler(Wc.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(pi,async(e,r)=>{const a=Object.entries(this._registeredResources).filter(([s,o])=>o.enabled).map(([s,o])=>({uri:s,name:o.name,...o.metadata})),n=[];for(const s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;const o=await s.resourceTemplate.listCallback(r);for(const i of o.resources)n.push({...s.metadata,...i})}return{resources:[...a,...n]}}),this.server.setRequestHandler(Kc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,a])=>({name:r,uriTemplate:a.resourceTemplate.uriTemplate.toString(),...a.metadata}))})),this.server.setRequestHandler(Wc,async(e,r)=>{const a=new URL(e.params.uri),n=this._registeredResources[a.toString()];if(n){if(!n.enabled)throw new st(rt.InvalidParams,`Resource ${a} disabled`);return n.readCallback(a,r)}for(const s of Object.values(this._registeredResourceTemplates)){const o=s.resourceTemplate.uriTemplate.match(a.toString());if(o)return s.readCallback(a,o,r)}throw new st(rt.InvalidParams,`Resource ${a} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Qc.shape.method.value),this.server.assertCanSetRequestHandler(Yc.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Qc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Bx(r.argsSchema):void 0}))})),this.server.setRequestHandler(Yc,async(e,r)=>{const a=this._registeredPrompts[e.params.name];if(!a)throw new st(rt.InvalidParams,`Prompt ${e.params.name} not found`);if(!a.enabled)throw new st(rt.InvalidParams,`Prompt ${e.params.name} disabled`);if(a.argsSchema){const n=await a.argsSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new st(rt.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${n.error.message}`);const s=n.data,o=a.callback;return await Promise.resolve(o(s,r))}else{const n=a.callback;return await Promise.resolve(n(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,r,...a){let n;typeof a[0]=="object"&&(n=a.shift());const s=a[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const o=this._createRegisteredResource(e,void 0,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const o=this._createRegisteredResourceTemplate(e,void 0,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}registerResource(e,r,a,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(e,a.title,r,a,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const s=this._createRegisteredResourceTemplate(e,a.title,r,a,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,a,n,s){const o={name:e,title:r,metadata:n,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==a&&(delete this._registeredResources[a],i.uri&&(this._registeredResources[i.uri]=o)),typeof i.name<"u"&&(o.name=i.name),typeof i.title<"u"&&(o.title=i.title),typeof i.metadata<"u"&&(o.metadata=i.metadata),typeof i.callback<"u"&&(o.readCallback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[a]=o,o}_createRegisteredResourceTemplate(e,r,a,n,s){const o={resourceTemplate:a,title:r,metadata:n,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=o)),typeof i.title<"u"&&(o.title=i.title),typeof i.template<"u"&&(o.resourceTemplate=i.template),typeof i.metadata<"u"&&(o.metadata=i.metadata),typeof i.callback<"u"&&(o.readCallback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=o,o}_createRegisteredPrompt(e,r,a,n,s){const o={title:r,description:a,argsSchema:n===void 0?void 0:te(n),callback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=o)),typeof i.title<"u"&&(o.title=i.title),typeof i.description<"u"&&(o.description=i.description),typeof i.argsSchema<"u"&&(o.argsSchema=te(i.argsSchema)),typeof i.callback<"u"&&(o.callback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,o}_createRegisteredTool(e,r,a,n,s,o,i,l){const c={title:r,description:a,inputSchema:n===void 0?void 0:te(n),outputSchema:s===void 0?void 0:te(s),annotations:o,_meta:i,callback:l,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredTools[e],u.name&&(this._registeredTools[u.name]=c)),typeof u.title<"u"&&(c.title=u.title),typeof u.description<"u"&&(c.description=u.description),typeof u.paramsSchema<"u"&&(c.inputSchema=te(u.paramsSchema)),typeof u.callback<"u"&&(c.callback=u.callback),typeof u.annotations<"u"&&(c.annotations=u.annotations),typeof u._meta<"u"&&(c._meta=u._meta),typeof u.enabled<"u"&&(c.enabled=u.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let a,n,s,o;if(typeof r[0]=="string"&&(a=r.shift()),r.length>1){const l=r[0];iv(l)?(n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!iv(r[0])&&(o=r.shift())):typeof l=="object"&&l!==null&&(o=r.shift())}const i=r[0];return this._createRegisteredTool(e,void 0,a,n,s,o,void 0,i)}registerTool(e,r,a){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:n,description:s,inputSchema:o,outputSchema:i,annotations:l,_meta:c}=r;return this._createRegisteredTool(e,n,s,o,i,l,c,a)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let a;typeof r[0]=="string"&&(a=r.shift());let n;r.length>1&&(n=r.shift());const s=r[0],o=this._createRegisteredPrompt(e,void 0,a,n,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,r,a){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:n,description:s,argsSchema:o}=r,i=this._createRegisteredPrompt(e,n,s,o,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class Zx{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new _n(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){var r;return(r=this._callbacks.complete)===null||r===void 0?void 0:r[e]}}const Vx={type:"object",properties:{}};function iv(t){return typeof t!="object"||t===null?!1:Object.keys(t).length===0||Object.values(t).some(Hx)}function Hx(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Bx(t){return Object.entries(t.shape).map(([e,r])=>({name:e,description:r.description,required:!r.isOptional()}))}function lv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const Gi={completion:{values:[],hasMore:!1}};function Jx(t){var e;if(t.title!==void 0&&t.title!=="")return t.title;if("annotations"in t){const r=t;if(!((e=r.annotations)===null||e===void 0)&&e.title)return r.annotations.title}return t.name}class Gx{constructor(e,r){const a={name:"web-mcp-server",version:"1.0.0"},n={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new ov(e||a,r||{capabilities:n}),this.server.server.oninitialized=()=>{var s;(s=this.oninitialized)==null||s.call(this)},this.server.server.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.server.server.onerror=s=>{var o;(o=this.onerror)==null||o.call(this,s)},this.server.server.setRequestHandler(mi,async()=>({}))}async connect(e){return typeof e.start=="function"?(this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new ad(e),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(e,r,a){return this.server.registerTool(e,r,a)}registerPrompt(e,r,a){return this.server.registerPrompt(e,r,a)}registerResource(e,r,a,n){return typeof r=="string"?this.server.registerResource(e,r,a,n):this.server.registerResource(e,r,a,n)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(e,r){return await this.server.server.createMessage(e,r)}async elicitInput(e,r){return await this.server.server.elicitInput(e,r)}async listRoots(e,r){return await this.server.server.listRoots(e,r)}async sendLoggingMessage(e){return await this.server.server.sendLoggingMessage(e)}async sendResourceUpdated(e){return await this.server.server.sendResourceUpdated(e)}request(e,r,a){return this.server.server.request(e,r,a)}async notification(e,r){return await this.server.server.notification(e,r)}setRequestHandler(e,r){this.server.server.setRequestHandler(e,r)}removeRequestHandler(e){this.server.server.removeRequestHandler(e)}setNotificationHandler(e,r){this.server.server.setNotificationHandler(e,r)}removeNotificationHandler(e){this.server.server.removeNotificationHandler(e)}onSubscribe(e){this.server.server.setRequestHandler(kh,e)}onUnsubscribe(e){this.server.server.setRequestHandler(Ih,e)}onSetLogLevel(e){this.server.server.setRequestHandler(mi,e)}onListResources(e){this.server.server.setRequestHandler(pi,e)}onRootsListChanged(e){this.server.server.setNotificationHandler(Uh,e)}async onPagehide(e){e.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const Kx=(t,e)=>new ad(t,e),Wx=()=>jI(),Qx=t=>t instanceof ad,Yx=t=>t instanceof ov;class Xx{constructor(e,r){const a={name:"web-mcp-client",version:"1.0.0"},n={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new qs(e||a,r||{capabilities:n}),this.client.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.client.onerror=s=>{var o;(o=this.onerror)==null||o.call(this,s)}}async connect(e){if(typeof e.start=="function")return this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:a,sessionId:n,type:s,agent:o,onError:i}=e;if(o===!0){const u={client:this.client,url:r,token:a,sessionId:n};let f;return await(async()=>{const{transport:d,sessionId:h}=s==="sse"?await QI(u):s==="socket"?await XI(u):await YI(u);d.onerror=async v=>{i==null||i(v)},f={transport:d,sessionId:h}})(),f}const l=new URL(r);let c;if(s==="channel"&&(c=new nd(r),await this.client.connect(c)),s==="sse"){const u=Hm(a,n);c=new Bs(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new Zm(new URL(`${r}?sessionId=${n}&token=${a}`)),c.sessionId=n,await this.client.connect(c)),typeof c>"u"){const u=Bm(a,n);c=new Js(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,fi,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,a){return this.client.request(e,r,a)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler(Dh,e)}onCreateMessage(e){this.client.setRequestHandler(jh,e)}onListRoots(e){this.client.setRequestHandler(zh,e)}onToolListChanged(e){this.client.setNotificationHandler(Ah,e)}onPromptListChanged(e){this.client.setNotificationHandler(Oh,e)}onResourceListChanged(e){this.client.setNotificationHandler(Ph,e)}onResourceUpdated(e){this.client.setNotificationHandler(xh,e)}onLoggingMessage(e){this.client.setNotificationHandler(Mh,e)}async onPagehide(e){e.persisted||(cv(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const eT=(t,e)=>new Bs(t,e),tT=(t,e)=>new Js(t,e),rT=(t,e)=>new nd(t,e),nT=t=>t instanceof Bs,cv=t=>t instanceof Js,aT=t=>t instanceof nd,sT=t=>t instanceof qs,Ha=(t,e,r)=>{window.postMessage({type:t,direction:r,data:e},"*")},uv=(t,e,r)=>{const a=async function(n){n.source===window&&n.data.type===t&&n.data.direction===r&&await e(n.data.data)};return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},pd=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},a=>{a.forEach(n=>{chrome.tabs.sendMessage(n.id,{type:t,data:e,direction:r,tabId:n.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},fd=(t,e,r,a)=>{const n=(s,o,i)=>{if(s.type===t&&s.direction===r&&(!a||a&&s.tabId===a)){const{data:l}=s;e(l,o,i),i(o)}};return chrome.runtime.onMessage.addListener(n),()=>chrome.runtime.onMessage.removeListener(n)};class dv{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=fd("mcp-server-to-client",r=>{var a;try{if(r.sessionId!==this.targetSessionId)return;const n=gn.parse(r.mcpMessage);(a=this.onmessage)==null||a.call(this,n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(e,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const a=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!a,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const n=a.tabIds[a.tabIds.length-1];pd("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const pv=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});class oT{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||pv(),this.tabId=r,this._messageListener1=uv("sidepanel-ready-to-page",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(a=>{console.error("【Page Svr Transport】 notifyRegistration失败:",a)})},"content->page"),this._messageListener2=uv("mcp-client-to-server-to-page",a=>{var o,i,l;if(a.sessionId!==this.sessionId||a.tabId!==this.tabId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",a.mcpMessage);const n=gn.parse(a.mcpMessage);(o=this.onmessage)==null||o.call(this,n),((i=a.mcpMessage.params)==null?void 0:i.name)&&Ha("update-page-app-message",{status:"run",message:(l=a.mcpMessage.params)==null?void 0:l.name},"page->content")},"content->page")}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(e,r){var a;this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),Ha("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:e},"page->content"),"result"in e&&((a=e.result)!=null&&a.content)&&Ha("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(e){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=e;try{Ha("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"page->content")}catch(r){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(r))}}async close(){if(!this._isClosed)try{this._messageListener1&&this._messageListener1(),this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(e))}}}class iT{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||pv(),this.tabId=r,fd("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(a=>{console.log("【Content Svr Transport】 notifyRegistration 失败",a)})},"side->content",this.tabId)}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");fd("mcp-client-to-server",e=>{var r,a,n;if(!(e.sessionId!==this.sessionId||e.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",e.mcpMessage);const s=gn.parse(e.mcpMessage);(r=this.onmessage)==null||r.call(this,s),((a=e.mcpMessage.params)==null?void 0:a.name)&&Ha("update-page-app-message",{status:"run",message:(n=e.mcpMessage.params)==null?void 0:n.name},"page->content")}catch(s){console.log("【Content Svr Transport】 处理消息时发生错误:",s)}},"side->content",this.tabId),this._isStarted=!0}}async send(e,r){var a;this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",e),pd("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:e},"content->side"),"result"in e&&((a=e.result)!=null&&a.content)&&Ha("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(e){this._isStarted&&(this._lastRegistration=e,pd("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"content->side"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(e))}}}var Ba={},lT=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},fv={},pr={};let hd;const cT=[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];pr.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17},pr.getSymbolTotalCodewords=function(e){return cT[e]},pr.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e},pr.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');hd=e},pr.isKanjiModeEnabled=function(){return typeof hd<"u"},pr.toSJIS=function(e){return hd(e)};var Ki={};(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,n){if(t.isValid(a))return a;try{return e(a)}catch{return n}}})(Ki);function hv(){this.buffer=[],this.length=0}hv.prototype={get:function(t){const e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var uT=hv;function Ks(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)}Ks.prototype.set=function(t,e,r,a){const n=t*this.size+e;this.data[n]=r,a&&(this.reservedBit[n]=!0)},Ks.prototype.get=function(t,e){return this.data[t*this.size+e]},Ks.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r},Ks.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};var dT=Ks,mv={};(function(t){const e=pr.getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const n=Math.floor(a/7)+2,s=e(a),o=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let l=1;l<n-1;l++)i[l]=i[l-1]-o;return i.push(6),i.reverse()},t.getPositions=function(a){const n=[],s=t.getRowColCoords(a),o=s.length;for(let i=0;i<o;i++)for(let l=0;l<o;l++)i===0&&l===0||i===0&&l===o-1||i===o-1&&l===0||n.push([s[i],s[l]]);return n}})(mv);var vv={};const pT=pr.getSymbolSize,gv=7;vv.getPositions=function(e){const r=pT(e);return[[0,0],[r-gv,0],[0,r-gv]]};var yv={};(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(n){return n!=null&&n!==""&&!isNaN(n)&&n>=0&&n<=7},t.from=function(n){return t.isValid(n)?parseInt(n,10):void 0},t.getPenaltyN1=function(n){const s=n.size;let o=0,i=0,l=0,c=null,u=null;for(let f=0;f<s;f++){i=l=0,c=u=null;for(let g=0;g<s;g++){let d=n.get(f,g);d===c?i++:(i>=5&&(o+=e.N1+(i-5)),c=d,i=1),d=n.get(g,f),d===u?l++:(l>=5&&(o+=e.N1+(l-5)),u=d,l=1)}i>=5&&(o+=e.N1+(i-5)),l>=5&&(o+=e.N1+(l-5))}return o},t.getPenaltyN2=function(n){const s=n.size;let o=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const c=n.get(i,l)+n.get(i,l+1)+n.get(i+1,l)+n.get(i+1,l+1);(c===4||c===0)&&o++}return o*e.N2},t.getPenaltyN3=function(n){const s=n.size;let o=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|n.get(c,u),u>=10&&(i===1488||i===93)&&o++,l=l<<1&2047|n.get(u,c),u>=10&&(l===1488||l===93)&&o++}return o*e.N3},t.getPenaltyN4=function(n){let s=0;const o=n.data.length;for(let l=0;l<o;l++)s+=n.data[l];return Math.abs(Math.ceil(s*100/o/5)-10)*e.N4};function r(a,n,s){switch(a){case t.Patterns.PATTERN000:return(n+s)%2===0;case t.Patterns.PATTERN001:return n%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(n+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return n*s%2+n*s%3===0;case t.Patterns.PATTERN110:return(n*s%2+n*s%3)%2===0;case t.Patterns.PATTERN111:return(n*s%3+(n+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(n,s){const o=s.size;for(let i=0;i<o;i++)for(let l=0;l<o;l++)s.isReserved(l,i)||s.xor(l,i,r(n,l,i))},t.getBestMask=function(n,s){const o=Object.keys(t.Patterns).length;let i=0,l=1/0;for(let c=0;c<o;c++){s(c),t.applyMask(c,n);const u=t.getPenaltyN1(n)+t.getPenaltyN2(n)+t.getPenaltyN3(n)+t.getPenaltyN4(n);t.applyMask(c,n),u<l&&(l=u,i=c)}return i}})(yv);var Wi={};const Mn=Ki,Qi=[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],Yi=[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];Wi.getBlocksCount=function(e,r){switch(r){case Mn.L:return Qi[(e-1)*4+0];case Mn.M:return Qi[(e-1)*4+1];case Mn.Q:return Qi[(e-1)*4+2];case Mn.H:return Qi[(e-1)*4+3];default:return}},Wi.getTotalCodewordsCount=function(e,r){switch(r){case Mn.L:return Yi[(e-1)*4+0];case Mn.M:return Yi[(e-1)*4+1];case Mn.Q:return Yi[(e-1)*4+2];case Mn.H:return Yi[(e-1)*4+3];default:return}};var _v={},Xi={};const Ws=new Uint8Array(512),el=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Ws[r]=e,el[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Ws[r]=Ws[r-255]})(),Xi.log=function(e){if(e<1)throw new Error("log("+e+")");return el[e]},Xi.exp=function(e){return Ws[e]},Xi.mul=function(e,r){return e===0||r===0?0:Ws[el[e]+el[r]]},function(t){const e=Xi;t.mul=function(a,n){const s=new Uint8Array(a.length+n.length-1);for(let o=0;o<a.length;o++)for(let i=0;i<n.length;i++)s[o+i]^=e.mul(a[o],n[i]);return s},t.mod=function(a,n){let s=new Uint8Array(a);for(;s.length-n.length>=0;){const o=s[0];for(let l=0;l<n.length;l++)s[l]^=e.mul(n[l],o);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},t.generateECPolynomial=function(a){let n=new Uint8Array([1]);for(let s=0;s<a;s++)n=t.mul(n,new Uint8Array([1,e.exp(s)]));return n}}(_v);const wv=_v;function md(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}md.prototype.initialize=function(e){this.degree=e,this.genPoly=wv.generateECPolynomial(this.degree)},md.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");const r=new Uint8Array(e.length+this.degree);r.set(e);const a=wv.mod(r,this.genPoly),n=this.degree-a.length;if(n>0){const s=new Uint8Array(this.degree);return s.set(a,n),s}return a};var fT=md,bv={},jn={},vd={};vd.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40};var en={};const Ev="[0-9]+",hT="[A-Z $%*+\\-./:]+";let Qs="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Qs=Qs.replace(/u/g,"\\u");const mT="(?:(?![A-Z0-9 $%*+\\-./:]|"+Qs+`)(?:.|[\r
17
- ]))+`;en.KANJI=new RegExp(Qs,"g"),en.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),en.BYTE=new RegExp(mT,"g"),en.NUMERIC=new RegExp(Ev,"g"),en.ALPHANUMERIC=new RegExp(hT,"g");const vT=new RegExp("^"+Qs+"$"),gT=new RegExp("^"+Ev+"$"),yT=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");en.testKanji=function(e){return vT.test(e)},en.testNumeric=function(e){return gT.test(e)},en.testAlphanumeric=function(e){return yT.test(e)},function(t){const e=vd,r=en;t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,o){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?s.ccBits[0]:o<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return r.testNumeric(s)?t.NUMERIC:r.testAlphanumeric(s)?t.ALPHANUMERIC:r.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function a(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+n)}}t.from=function(s,o){if(t.isValid(s))return s;try{return a(s)}catch{return o}}}(jn),function(t){const e=pr,r=Wi,a=Ki,n=jn,s=vd,o=7973,i=e.getBCHDigit(o);function l(g,d,h){for(let v=1;v<=40;v++)if(d<=t.getCapacity(v,h,g))return v}function c(g,d){return n.getCharCountIndicator(g,d)+4}function u(g,d){let h=0;return g.forEach(function(v){const m=c(v.mode,d);h+=m+v.getBitsLength()}),h}function f(g,d){for(let h=1;h<=40;h++)if(u(g,h)<=t.getCapacity(h,d,n.MIXED))return h}t.from=function(d,h){return s.isValid(d)?parseInt(d,10):h},t.getCapacity=function(d,h,v){if(!s.isValid(d))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=n.BYTE);const m=e.getSymbolTotalCodewords(d),p=r.getTotalCodewordsCount(d,h),_=(m-p)*8;if(v===n.MIXED)return _;const w=_-c(v,d);switch(v){case n.NUMERIC:return Math.floor(w/10*3);case n.ALPHANUMERIC:return Math.floor(w/11*2);case n.KANJI:return Math.floor(w/13);case n.BYTE:default:return Math.floor(w/8)}},t.getBestVersionForData=function(d,h){let v;const m=a.from(h,a.M);if(Array.isArray(d)){if(d.length>1)return f(d,m);if(d.length===0)return 1;v=d[0]}else v=d;return l(v.mode,v.getLength(),m)},t.getEncodedBits=function(d){if(!s.isValid(d)||d<7)throw new Error("Invalid QR Code version");let h=d<<12;for(;e.getBCHDigit(h)-i>=0;)h^=o<<e.getBCHDigit(h)-i;return d<<12|h}}(bv);var Sv={};const gd=pr,$v=1335,_T=21522,Pv=gd.getBCHDigit($v);Sv.getEncodedBits=function(e,r){const a=e.bit<<3|r;let n=a<<10;for(;gd.getBCHDigit(n)-Pv>=0;)n^=$v<<gd.getBCHDigit(n)-Pv;return(a<<10|n)^_T};var kv={};const wT=jn;function Ja(t){this.mode=wT.NUMERIC,this.data=t.toString()}Ja.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)},Ja.prototype.getLength=function(){return this.data.length},Ja.prototype.getBitsLength=function(){return Ja.getBitsLength(this.data.length)},Ja.prototype.write=function(e){let r,a,n;for(r=0;r+3<=this.data.length;r+=3)a=this.data.substr(r,3),n=parseInt(a,10),e.put(n,10);const s=this.data.length-r;s>0&&(a=this.data.substr(r),n=parseInt(a,10),e.put(n,s*3+1))};var bT=Ja;const ET=jn,yd=["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 Ga(t){this.mode=ET.ALPHANUMERIC,this.data=t}Ga.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)},Ga.prototype.getLength=function(){return this.data.length},Ga.prototype.getBitsLength=function(){return Ga.getBitsLength(this.data.length)},Ga.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let a=yd.indexOf(this.data[r])*45;a+=yd.indexOf(this.data[r+1]),e.put(a,11)}this.data.length%2&&e.put(yd.indexOf(this.data[r]),6)};var ST=Ga;const $T=jn;function Ka(t){this.mode=$T.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Ka.getBitsLength=function(e){return e*8},Ka.prototype.getLength=function(){return this.data.length},Ka.prototype.getBitsLength=function(){return Ka.getBitsLength(this.data.length)},Ka.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};var PT=Ka;const kT=jn,IT=pr;function Wa(t){this.mode=kT.KANJI,this.data=t}Wa.getBitsLength=function(e){return e*13},Wa.prototype.getLength=function(){return this.data.length},Wa.prototype.getBitsLength=function(){return Wa.getBitsLength(this.data.length)},Wa.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=IT.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
18
- Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};var xT=Wa,Iv={exports:{}};(function(t){var e={single_source_shortest_paths:function(r,a,n){var s={},o={};o[a]=0;var i=e.PriorityQueue.make();i.push(a,0);for(var l,c,u,f,g,d,h,v,m;!i.empty();){l=i.pop(),c=l.value,f=l.cost,g=r[c]||{};for(u in g)g.hasOwnProperty(u)&&(d=g[u],h=f+d,v=o[u],m=typeof o[u]>"u",(m||v>h)&&(o[u]=h,i.push(u,h),s[u]=c))}if(typeof n<"u"&&typeof o[n]>"u"){var p=["Could not find a path from ",a," to ",n,"."].join("");throw new Error(p)}return s},extract_shortest_path_from_predecessor_list:function(r,a){for(var n=[],s=a;s;)n.push(s),r[s],s=r[s];return n.reverse(),n},find_path:function(r,a,n){var s=e.single_source_shortest_paths(r,a,n);return e.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(r){var a=e.PriorityQueue,n={},s;r=r||{};for(s in a)a.hasOwnProperty(s)&&(n[s]=a[s]);return n.queue=[],n.sorter=r.sorter||a.default_sorter,n},default_sorter:function(r,a){return r.cost-a.cost},push:function(r,a){var n={value:r,cost:a};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(Iv);var TT=Iv.exports;(function(t){const e=jn,r=bT,a=ST,n=PT,s=xT,o=en,i=pr,l=TT;function c(p){return unescape(encodeURIComponent(p)).length}function u(p,_,w){const b=[];let S;for(;(S=p.exec(w))!==null;)b.push({data:S[0],index:S.index,mode:_,length:S[0].length});return b}function f(p){const _=u(o.NUMERIC,e.NUMERIC,p),w=u(o.ALPHANUMERIC,e.ALPHANUMERIC,p);let b,S;return i.isKanjiModeEnabled()?(b=u(o.BYTE,e.BYTE,p),S=u(o.KANJI,e.KANJI,p)):(b=u(o.BYTE_KANJI,e.BYTE,p),S=[]),_.concat(w,b,S).sort(function(k,A){return k.index-A.index}).map(function(k){return{data:k.data,mode:k.mode,length:k.length}})}function g(p,_){switch(_){case e.NUMERIC:return r.getBitsLength(p);case e.ALPHANUMERIC:return a.getBitsLength(p);case e.KANJI:return s.getBitsLength(p);case e.BYTE:return n.getBitsLength(p)}}function d(p){return p.reduce(function(_,w){const b=_.length-1>=0?_[_.length-1]:null;return b&&b.mode===w.mode?(_[_.length-1].data+=w.data,_):(_.push(w),_)},[])}function h(p){const _=[];for(let w=0;w<p.length;w++){const b=p[w];switch(b.mode){case e.NUMERIC:_.push([b,{data:b.data,mode:e.ALPHANUMERIC,length:b.length},{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.ALPHANUMERIC:_.push([b,{data:b.data,mode:e.BYTE,length:b.length}]);break;case e.KANJI:_.push([b,{data:b.data,mode:e.BYTE,length:c(b.data)}]);break;case e.BYTE:_.push([{data:b.data,mode:e.BYTE,length:c(b.data)}])}}return _}function v(p,_){const w={},b={start:{}};let S=["start"];for(let I=0;I<p.length;I++){const k=p[I],A=[];for(let O=0;O<k.length;O++){const H=k[O],J=""+I+O;A.push(J),w[J]={node:H,lastCount:0},b[J]={};for(let K=0;K<S.length;K++){const z=S[K];w[z]&&w[z].node.mode===H.mode?(b[z][J]=g(w[z].lastCount+H.length,H.mode)-g(w[z].lastCount,H.mode),w[z].lastCount+=H.length):(w[z]&&(w[z].lastCount=H.length),b[z][J]=g(H.length,H.mode)+4+e.getCharCountIndicator(H.mode,_))}}S=A}for(let I=0;I<S.length;I++)b[S[I]].end=0;return{map:b,table:w}}function m(p,_){let w;const b=e.getBestModeForData(p);if(w=e.from(_,b),w!==e.BYTE&&w.bit<b.bit)throw new Error('"'+p+'" cannot be encoded with mode '+e.toString(w)+`.
19
- Suggested mode is: `+e.toString(b));switch(w===e.KANJI&&!i.isKanjiModeEnabled()&&(w=e.BYTE),w){case e.NUMERIC:return new r(p);case e.ALPHANUMERIC:return new a(p);case e.KANJI:return new s(p);case e.BYTE:return new n(p)}}t.fromArray=function(_){return _.reduce(function(w,b){return typeof b=="string"?w.push(m(b,null)):b.data&&w.push(m(b.data,b.mode)),w},[])},t.fromString=function(_,w){const b=f(_,i.isKanjiModeEnabled()),S=h(b),I=v(S,w),k=l.find_path(I.map,"start","end"),A=[];for(let O=1;O<k.length-1;O++)A.push(I.table[k[O]].node);return t.fromArray(d(A))},t.rawSplit=function(_){return t.fromArray(f(_,i.isKanjiModeEnabled()))}})(kv);const tl=pr,_d=Ki,CT=uT,RT=dT,OT=mv,NT=vv,wd=yv,bd=Wi,AT=fT,rl=bv,MT=Sv,jT=jn,Ed=kv;function DT(t,e){const r=t.size,a=NT.getPositions(e);for(let n=0;n<a.length;n++){const s=a[n][0],o=a[n][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||r<=s+i))for(let l=-1;l<=7;l++)o+l<=-1||r<=o+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?t.set(s+i,o+l,!0,!0):t.set(s+i,o+l,!1,!0))}}function LT(t){const e=t.size;for(let r=8;r<e-8;r++){const a=r%2===0;t.set(r,6,a,!0),t.set(6,r,a,!0)}}function zT(t,e){const r=OT.getPositions(e);for(let a=0;a<r.length;a++){const n=r[a][0],s=r[a][1];for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)o===-2||o===2||i===-2||i===2||o===0&&i===0?t.set(n+o,s+i,!0,!0):t.set(n+o,s+i,!1,!0)}}function UT(t,e){const r=t.size,a=rl.getEncodedBits(e);let n,s,o;for(let i=0;i<18;i++)n=Math.floor(i/3),s=i%3+r-8-3,o=(a>>i&1)===1,t.set(n,s,o,!0),t.set(s,n,o,!0)}function Sd(t,e,r){const a=t.size,n=MT.getEncodedBits(e,r);let s,o;for(s=0;s<15;s++)o=(n>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(a-15+s,8,o,!0),s<8?t.set(8,a-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(a-8,8,1,!0)}function qT(t,e){const r=t.size;let a=-1,n=r-1,s=7,o=0;for(let i=r-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!t.isReserved(n,i-l)){let c=!1;o<e.length&&(c=(e[o]>>>s&1)===1),t.set(n,i-l,c),s--,s===-1&&(o++,s=7)}if(n+=a,n<0||r<=n){n-=a,a=-a;break}}}function FT(t,e,r){const a=new CT;r.forEach(function(l){a.put(l.mode.bit,4),a.put(l.getLength(),jT.getCharCountIndicator(l.mode,t)),l.write(a)});const n=tl.getSymbolTotalCodewords(t),s=bd.getTotalCodewordsCount(t,e),o=(n-s)*8;for(a.getLengthInBits()+4<=o&&a.put(0,4);a.getLengthInBits()%8!==0;)a.putBit(0);const i=(o-a.getLengthInBits())/8;for(let l=0;l<i;l++)a.put(l%2?17:236,8);return ZT(a,t,e)}function ZT(t,e,r){const a=tl.getSymbolTotalCodewords(e),n=bd.getTotalCodewordsCount(e,r),s=a-n,o=bd.getBlocksCount(e,r),i=a%o,l=o-i,c=Math.floor(a/o),u=Math.floor(s/o),f=u+1,g=c-u,d=new AT(g);let h=0;const v=new Array(o),m=new Array(o);let p=0;const _=new Uint8Array(t.buffer);for(let k=0;k<o;k++){const A=k<l?u:f;v[k]=_.slice(h,h+A),m[k]=d.encode(v[k]),h+=A,p=Math.max(p,A)}const w=new Uint8Array(a);let b=0,S,I;for(S=0;S<p;S++)for(I=0;I<o;I++)S<v[I].length&&(w[b++]=v[I][S]);for(S=0;S<g;S++)for(I=0;I<o;I++)w[b++]=m[I][S];return w}function VT(t,e,r,a){let n;if(Array.isArray(t))n=Ed.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){const u=Ed.rawSplit(t);c=rl.getBestVersionForData(u,r)}n=Ed.fromString(t,c||40)}else throw new Error("Invalid data");const s=rl.getBestVersionForData(n,r);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
16
+ ]`;continue}n+=a[c],a[c]==="\\"?s=!0:o&&a[c]==="]"?o=!1:!o&&a[c]==="["&&(o=!0)}try{new RegExp(n)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return n}function rv(t,e){var a,n,s,o,i,l;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((a=t.keyType)==null?void 0:a._def.typeName)===V.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((c,u)=>({...c,[u]:Be(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",u]})??Kt(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:Be(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(((n=t.keyType)==null?void 0:n._def.typeName)===V.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:c,...u}=ev(t.keyType._def,e);return{...r,propertyNames:u}}else{if(((o=t.keyType)==null?void 0:o._def.typeName)===V.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(((i=t.keyType)==null?void 0:i._def.typeName)===V.ZodBranded&&t.keyType._def.type._def.typeName===V.ZodString&&((l=t.keyType._def.type._def.checks)!=null&&l.length)){const{type:c,...u}=Ym(t.keyType._def,e);return{...r,propertyNames:u}}}return r}function Pk(t,e){if(e.mapStrategy==="record")return rv(t,e);const r=Be(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Kt(e),a=Be(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Kt(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function Tk(t){const e=t.values,a=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(a.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}function xk(t){return t.target==="openAi"?void 0:{not:Kt({...t,currentPath:[...t.currentPath,"not"]})}}function kk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ji={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ik(t,e){if(e.target==="openApi3")return nv(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(a=>a._def.typeName in ji&&(!a._def.checks||!a._def.checks.length))){const a=r.reduce((n,s)=>{const o=ji[s._def.typeName];return o&&!n.includes(o)?[...n,o]:n},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=r.reduce((n,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...n,o];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(a.length===r.length){const n=a.filter((s,o,i)=>i.indexOf(s)===o);return{type:n.length>1?n:n[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,n)=>[...a,...n._def.values.filter(s=>!a.includes(s))],[])};return nv(t,e)}const nv=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,n)=>Be(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function Ck(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ji[t.innerType._def.typeName],nullable:!0}:{type:[ji[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const a=Be(t.innerType._def,{...e,currentPath:[...e.currentPath]});return a&&"$ref"in a?{allOf:[a],nullable:!0}:a&&{...a,nullable:!0}}const r=Be(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Rk(t,e){const r={type:"number"};if(!t.checks)return r;for(const a of t.checks)switch(a.kind){case"int":r.type="integer",Wm(r,"type",a.message,e);break;case"min":e.target==="jsonSchema7"?a.inclusive?Ge(r,"minimum",a.value,a.message,e):Ge(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),Ge(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?Ge(r,"maximum",a.value,a.message,e):Ge(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),Ge(r,"maximum",a.value,a.message,e));break;case"multipleOf":Ge(r,"multipleOf",a.value,a.message,e);break}return r}function Ok(t,e){const r=e.target==="openAi",a={type:"object",properties:{}},n=[],s=t.shape();for(const i in s){let l=s[i];if(l===void 0||l._def===void 0)continue;let c=Nk(l);c&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);const u=Be(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});u!==void 0&&(a.properties[i]=u,c||n.push(i))}n.length&&(a.required=n);const o=Ak(t,e);return o!==void 0&&(a.additionalProperties=o),a}function Ak(t,e){if(t.catchall._def.typeName!=="ZodNever")return Be(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Nk(t){try{return t.isOptional()}catch{return!0}}const Mk=(t,e)=>{var a;if(e.currentPath.toString()===((a=e.propertyPath)==null?void 0:a.toString()))return Be(t.innerType._def,e);const r=Be(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Kt(e)},r]}:Kt(e)},jk=(t,e)=>{if(e.pipeStrategy==="input")return Be(t.in._def,e);if(e.pipeStrategy==="output")return Be(t.out._def,e);const r=Be(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=Be(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(n=>n!==void 0)}};function Dk(t,e){return Be(t.type._def,e)}function Lk(t,e){const a={type:"array",uniqueItems:!0,items:Be(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Ge(a,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Ge(a,"maxItems",t.maxSize.value,t.maxSize.message,e),a}function zk(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,a)=>Be(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),additionalItems:Be(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,a)=>Be(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function Uk(t){return{not:Kt(t)}}function qk(t){return Kt(t)}const Fk=(t,e)=>Be(t.innerType._def,e),Zk=(t,e,r)=>{switch(e){case V.ZodString:return ev(t,r);case V.ZodNumber:return Rk(t,r);case V.ZodObject:return Ok(t,r);case V.ZodBigInt:return pk(t,r);case V.ZodBoolean:return hk();case V.ZodDate:return Xm(t,r);case V.ZodUndefined:return Uk(r);case V.ZodNull:return kk(r);case V.ZodArray:return fk(t,r);case V.ZodUnion:case V.ZodDiscriminatedUnion:return Ik(t,r);case V.ZodIntersection:return bk(t,r);case V.ZodTuple:return zk(t,r);case V.ZodRecord:return rv(t,r);case V.ZodLiteral:return Ek(t,r);case V.ZodEnum:return _k(t);case V.ZodNativeEnum:return Tk(t);case V.ZodNullable:return Ck(t,r);case V.ZodOptional:return Mk(t,r);case V.ZodMap:return Pk(t,r);case V.ZodSet:return Lk(t,r);case V.ZodLazy:return()=>t.getter()._def;case V.ZodPromise:return Dk(t,r);case V.ZodNaN:case V.ZodNever:return xk(r);case V.ZodEffects:return yk(t,r);case V.ZodAny:return Kt(r);case V.ZodUnknown:return qk(r);case V.ZodDefault:return gk(t,r);case V.ZodBranded:return Ym(t,r);case V.ZodReadonly:return Fk(t,r);case V.ZodCatch:return mk(t,r);case V.ZodPipeline:return jk(t,r);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return(a=>{})()}};function Be(t,e,r=!1){var i;const a=e.seen.get(t);if(e.override){const l=(i=e.override)==null?void 0:i.call(e,t,e,a,r);if(l!==ck)return l}if(a&&!r){const l=Vk(a,e);if(l!==void 0)return l}const n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);const s=Zk(t,t.typeName,e),o=typeof s=="function"?Be(s(),e):s;if(o&&Hk(t,e,o),e.postProcess){const l=e.postProcess(o,t,e);return n.jsonSchema=o,l}return n.jsonSchema=o,o}const Vk=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Qm(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Kt(e)):e.$refStrategy==="seen"?Kt(e):void 0}},Hk=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),av=(t,e)=>{const r=dk(e);let a=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,u])=>({...l,[c]:Be(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Kt(r)}),{}):void 0;const n=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,s=Be(t._def,n===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,n]},!1)??Kt(r),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(s.title=o),r.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[r.openAiAnyTypeName]||(a[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=n===void 0?a?{...s,[r.definitionPath]:a}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,n].join("/"),[r.definitionPath]:{...a,[n]: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};var ed;(function(t){t.Completable="McpCompletable"})(ed||(ed={}));class Di extends Oe{_parse(e){const{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}}Di.create=(t,e)=>new Di({type:t,typeName:ed.Completable,complete:e.complete,...Jk(e)});function Bk(t,e){return Di.create(t,{...t._def,complete:e})}function Jk(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(o,i)=>{var l,c;const{message:u}=t;return o.code==="invalid_enum_value"?{message:u??i.defaultError}:typeof i.data>"u"?{message:(l=u??a)!==null&&l!==void 0?l:i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:(c=u??r)!==null&&c!==void 0?c:i.defaultError}},description:n}}const sv=1e6,td=1e6,ov=1e4,Gk=1e6;class un{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,a){if(e.length>r)throw new Error(`${a} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){un.validateLength(e,sv,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){const r=[];let a="",n=0,s=0;for(;n<e.length;)if(e[n]==="{"){a&&(r.push(a),a="");const o=e.indexOf("}",n);if(o===-1)throw new Error("Unclosed template expression");if(s++,s>ov)throw new Error(`Template contains too many expressions (max ${ov})`);const i=e.slice(n+1,o),l=this.getOperator(i),c=i.includes("*"),u=this.getNames(i),h=u[0];for(const g of u)un.validateLength(g,td,"Variable name");r.push({name:h,operator:l,names:u,exploded:c}),n=o+1}else a+=e[n],n++;return a&&r.push(a),r}getOperator(e){return["+","#",".","/","?","&"].find(a=>e.startsWith(a))||""}getNames(e){const r=this.getOperator(e);return e.slice(r.length).split(",").map(a=>a.replace("*","").trim()).filter(a=>a.length>0)}encodeValue(e,r){return un.validateLength(e,td,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){const o=e.names.map(l=>{const c=r[l];if(c===void 0)return"";const u=Array.isArray(c)?c.map(h=>this.encodeValue(h,e.operator)).join(","):this.encodeValue(c.toString(),e.operator);return`${l}=${u}`}).filter(l=>l.length>0);return o.length===0?"":(e.operator==="?"?"?":"&")+o.join("&")}if(e.names.length>1){const o=e.names.map(i=>r[i]).filter(i=>i!==void 0);return o.length===0?"":o.map(i=>Array.isArray(i)?i[0]:i).join(",")}const a=r[e.name];if(a===void 0)return"";const s=(Array.isArray(a)?a:[a]).map(o=>this.encodeValue(o,e.operator));switch(e.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(e){let r="",a=!1;for(const n of this.parts){if(typeof n=="string"){r+=n;continue}const s=this.expandPart(n,e);s&&((n.operator==="?"||n.operator==="&")&&a?r+=s.replace("?","&"):r+=s,(n.operator==="?"||n.operator==="&")&&(a=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){const r=[];for(const s of e.names)un.validateLength(s,td,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let s=0;s<e.names.length;s++){const o=e.names[s],i=s===0?"\\"+e.operator:"&";r.push({pattern:i+this.escapeRegExp(o)+"=([^&]+)",name:o})}return r}let a;const n=e.name;switch(e.operator){case"":a=e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)";break;case"+":case"#":a="(.+)";break;case".":a="\\.([^/,]+)";break;case"/":a="/"+(e.exploded?"([^/]+(?:,[^/]+)*)":"([^/,]+)");break;default:a="([^/]+)"}return r.push({pattern:a,name:n}),r}match(e){un.validateLength(e,sv,"URI");let r="^";const a=[];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,a.push({name:u,exploded:i.exploded})}r+="$",un.validateLength(r,Gk,"Generated regex pattern");const n=new RegExp(r),s=e.match(n);if(!s)return null;const o={};for(let i=0;i<a.length;i++){const{name:l,exploded:c}=a[i],u=s[i+1],h=l.replace("*","");c&&u.includes(",")?o[h]=u.split(","):o[h]=u}return o}}class iv{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new lk(e,r)}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Jc.shape.method.value),this.server.assertCanSetRequestHandler(Gc.shape.method.value),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Jc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{const a={name:e,title:r.title,description:r.description,inputSchema:r.inputSchema?av(r.inputSchema,{strictUnions:!0}):Wk,annotations:r.annotations};return r.outputSchema&&(a.outputSchema=av(r.outputSchema,{strictUnions:!0})),a})})),this.server.setRequestHandler(Gc,async(e,r)=>{const a=this._registeredTools[e.params.name];if(!a)throw new st(rt.InvalidParams,`Tool ${e.params.name} not found`);if(!a.enabled)throw new st(rt.InvalidParams,`Tool ${e.params.name} disabled`);let n;if(a.inputSchema){const s=await a.inputSchema.safeParseAsync(e.params.arguments);if(!s.success)throw new st(rt.InvalidParams,`Invalid arguments for tool ${e.params.name}: ${s.error.message}`);const o=s.data,i=a.callback;try{n=await Promise.resolve(i(o,r))}catch(l){n={content:[{type:"text",text:l instanceof Error?l.message:String(l)}],isError:!0}}}else{const s=a.callback;try{n=await Promise.resolve(s(r))}catch(o){n={content:[{type:"text",text:o instanceof Error?o.message:String(o)}],isError:!0}}}if(a.outputSchema&&!n.isError){if(!n.structuredContent)throw new st(rt.InvalidParams,`Tool ${e.params.name} has an output schema but no structured content was provided`);const s=await a.outputSchema.safeParseAsync(n.structuredContent);if(!s.success)throw new st(rt.InvalidParams,`Invalid structured content for tool ${e.params.name}: ${s.error.message}`)}return n}),this._toolHandlersInitialized=!0)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Yc.shape.method.value),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Yc,async e=>{switch(e.params.ref.type){case"ref/prompt":return this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return this.handleResourceCompletion(e,e.params.ref);default:throw new st(rt.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){const a=this._registeredPrompts[r.name];if(!a)throw new st(rt.InvalidParams,`Prompt ${r.name} not found`);if(!a.enabled)throw new st(rt.InvalidParams,`Prompt ${r.name} disabled`);if(!a.argsSchema)return Li;const n=a.argsSchema.shape[e.params.argument.name];if(!(n instanceof Di))return Li;const o=await n._def.complete(e.params.argument.value,e.params.context);return cv(o)}async handleResourceCompletion(e,r){const a=Object.values(this._registeredResourceTemplates).find(o=>o.resourceTemplate.uriTemplate.toString()===r.uri);if(!a){if(this._registeredResources[r.uri])return Li;throw new st(rt.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}const n=a.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return Li;const s=await n(e.params.argument.value,e.params.context);return cv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(oi.shape.method.value),this.server.assertCanSetRequestHandler(Uc.shape.method.value),this.server.assertCanSetRequestHandler(qc.shape.method.value),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(oi,async(e,r)=>{const a=Object.entries(this._registeredResources).filter(([s,o])=>o.enabled).map(([s,o])=>({uri:s,name:o.name,...o.metadata})),n=[];for(const s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;const o=await s.resourceTemplate.listCallback(r);for(const i of o.resources)n.push({...s.metadata,...i})}return{resources:[...a,...n]}}),this.server.setRequestHandler(Uc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,a])=>({name:r,uriTemplate:a.resourceTemplate.uriTemplate.toString(),...a.metadata}))})),this.server.setRequestHandler(qc,async(e,r)=>{const a=new URL(e.params.uri),n=this._registeredResources[a.toString()];if(n){if(!n.enabled)throw new st(rt.InvalidParams,`Resource ${a} disabled`);return n.readCallback(a,r)}for(const s of Object.values(this._registeredResourceTemplates)){const o=s.resourceTemplate.uriTemplate.match(a.toString());if(o)return s.readCallback(a,o,r)}throw new st(rt.InvalidParams,`Resource ${a} not found`)}),this.setCompletionRequestHandler(),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Fc.shape.method.value),this.server.assertCanSetRequestHandler(Zc.shape.method.value),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Fc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Yk(r.argsSchema):void 0}))})),this.server.setRequestHandler(Zc,async(e,r)=>{const a=this._registeredPrompts[e.params.name];if(!a)throw new st(rt.InvalidParams,`Prompt ${e.params.name} not found`);if(!a.enabled)throw new st(rt.InvalidParams,`Prompt ${e.params.name} disabled`);if(a.argsSchema){const n=await a.argsSchema.safeParseAsync(e.params.arguments);if(!n.success)throw new st(rt.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${n.error.message}`);const s=n.data,o=a.callback;return await Promise.resolve(o(s,r))}else{const n=a.callback;return await Promise.resolve(n(r))}}),this.setCompletionRequestHandler(),this._promptHandlersInitialized=!0)}resource(e,r,...a){let n;typeof a[0]=="object"&&(n=a.shift());const s=a[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const o=this._createRegisteredResource(e,void 0,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const o=this._createRegisteredResourceTemplate(e,void 0,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}registerResource(e,r,a,n){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);const s=this._createRegisteredResource(e,a.title,r,a,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);const s=this._createRegisteredResourceTemplate(e,a.title,r,a,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,a,n,s){const o={name:e,title:r,metadata:n,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==a&&(delete this._registeredResources[a],i.uri&&(this._registeredResources[i.uri]=o)),typeof i.name<"u"&&(o.name=i.name),typeof i.title<"u"&&(o.title=i.title),typeof i.metadata<"u"&&(o.metadata=i.metadata),typeof i.callback<"u"&&(o.readCallback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[a]=o,o}_createRegisteredResourceTemplate(e,r,a,n,s){const o={resourceTemplate:a,title:r,metadata:n,readCallback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredResourceTemplates[e],i.name&&(this._registeredResourceTemplates[i.name]=o)),typeof i.title<"u"&&(o.title=i.title),typeof i.template<"u"&&(o.resourceTemplate=i.template),typeof i.metadata<"u"&&(o.metadata=i.metadata),typeof i.callback<"u"&&(o.readCallback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResourceTemplates[e]=o,o}_createRegisteredPrompt(e,r,a,n,s){const o={title:r,description:a,argsSchema:n===void 0?void 0:ee(n),callback:s,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=o)),typeof i.title<"u"&&(o.title=i.title),typeof i.description<"u"&&(o.description=i.description),typeof i.argsSchema<"u"&&(o.argsSchema=ee(i.argsSchema)),typeof i.callback<"u"&&(o.callback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,o}_createRegisteredTool(e,r,a,n,s,o,i){const l={title:r,description:a,inputSchema:n===void 0?void 0:ee(n),outputSchema:s===void 0?void 0:ee(s),annotations:o,callback:i,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:c=>{typeof c.name<"u"&&c.name!==e&&(delete this._registeredTools[e],c.name&&(this._registeredTools[c.name]=l)),typeof c.title<"u"&&(l.title=c.title),typeof c.description<"u"&&(l.description=c.description),typeof c.paramsSchema<"u"&&(l.inputSchema=ee(c.paramsSchema)),typeof c.callback<"u"&&(l.callback=c.callback),typeof c.annotations<"u"&&(l.annotations=c.annotations),typeof c.enabled<"u"&&(l.enabled=c.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let a,n,s,o;if(typeof r[0]=="string"&&(a=r.shift()),r.length>1){const l=r[0];lv(l)?(n=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!lv(r[0])&&(o=r.shift())):typeof l=="object"&&l!==null&&(o=r.shift())}const i=r[0];return this._createRegisteredTool(e,void 0,a,n,s,o,i)}registerTool(e,r,a){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);const{title:n,description:s,inputSchema:o,outputSchema:i,annotations:l}=r;return this._createRegisteredTool(e,n,s,o,i,l,a)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let a;typeof r[0]=="string"&&(a=r.shift());let n;r.length>1&&(n=r.shift());const s=r[0],o=this._createRegisteredPrompt(e,void 0,a,n,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,r,a){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);const{title:n,description:s,argsSchema:o}=r,i=this._createRegisteredPrompt(e,n,s,o,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}class Kk{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new un(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){var r;return(r=this._callbacks.complete)===null||r===void 0?void 0:r[e]}}const Wk={type:"object",properties:{}};function lv(t){return typeof t!="object"||t===null?!1:Object.keys(t).length===0||Object.values(t).some(Qk)}function Qk(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Yk(t){return Object.entries(t.shape).map(([e,r])=>({name:e,description:r.description,required:!r.isOptional()}))}function cv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}const Li={completion:{values:[],hasMore:!1}};function Xk(t){var e;if(t.title!==void 0&&t.title!=="")return t.title;if("annotations"in t){const r=t;if(!((e=r.annotations)===null||e===void 0)&&e.title)return r.annotations.title}return t.name}class Zs{constructor(){this._messageQueue=[]}static createLinkedPair(){const e=new Zs,r=new Zs;return e._otherTransport=r,r._otherTransport=e,[e,r]}async start(){for(var e;this._messageQueue.length>0;){const r=this._messageQueue.shift();(e=this.onmessage)===null||e===void 0||e.call(this,r.message,r.extra)}}async close(){var e;const r=this._otherTransport;this._otherTransport=void 0,await(r==null?void 0:r.close()),(e=this.onclose)===null||e===void 0||e.call(this)}async send(e,r){if(!this._otherTransport)throw new Error("Not connected");this._otherTransport.onmessage?this._otherTransport.onmessage(e,{authInfo:r==null?void 0:r.authInfo}):this._otherTransport._messageQueue.push({message:e,extra:{authInfo:r==null?void 0:r.authInfo}})}}class eI{constructor(e,r){const a={name:"web-mcp-server",version:"1.0.0"},n={prompts:{listChanged:!0},resources:{subscribe:!0,listChanged:!0},tools:{listChanged:!0},completions:{},logging:{}};this.server=new iv(e||a,r||{capabilities:n}),this.server.server.oninitialized=()=>{var s;(s=this.oninitialized)==null||s.call(this)},this.server.server.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.server.server.onerror=s=>{var o;(o=this.onerror)==null||o.call(this,s)},this.server.server.setRequestHandler(Kc,async()=>({}))}async connect(e){return typeof e.start=="function"?(this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0):(this.transport=new Gu(e),await this.transport.listen()),await this.server.connect(this.transport),this.transport}async close(){await this.server.close()}registerTool(e,r,a){return this.server.registerTool(e,r,a)}registerPrompt(e,r,a){return this.server.registerPrompt(e,r,a)}registerResource(e,r,a,n){return typeof r=="string"?this.server.registerResource(e,r,a,n):this.server.registerResource(e,r,a,n)}isConnected(){return this.server.isConnected()}sendResourceListChanged(){this.server.sendResourceListChanged()}sendToolListChanged(){this.server.sendToolListChanged()}sendPromptListChanged(){this.server.sendPromptListChanged()}getClientCapabilities(){return this.server.server.getClientCapabilities()}getClientVersion(){return this.server.server.getClientVersion()}async ping(){return await this.server.server.ping()}async createMessage(e,r){return await this.server.server.createMessage(e,r)}async elicitInput(e,r){return await this.server.server.elicitInput(e,r)}async listRoots(e,r){return await this.server.server.listRoots(e,r)}async sendLoggingMessage(e){return await this.server.server.sendLoggingMessage(e)}async sendResourceUpdated(e){return await this.server.server.sendResourceUpdated(e)}request(e,r,a){return this.server.server.request(e,r,a)}async notification(e,r){return await this.server.server.notification(e,r)}setRequestHandler(e,r){this.server.server.setRequestHandler(e,r)}removeRequestHandler(e){this.server.server.removeRequestHandler(e)}setNotificationHandler(e,r){this.server.server.setNotificationHandler(e,r)}removeNotificationHandler(e){this.server.server.removeNotificationHandler(e)}onSubscribe(e){this.server.server.setRequestHandler(Th,e)}onUnsubscribe(e){this.server.server.setRequestHandler(xh,e)}onSetLogLevel(e){this.server.server.setRequestHandler(Kc,e)}onListResources(e){this.server.server.setRequestHandler(oi,e)}onRootsListChanged(e){this.server.server.setNotificationHandler(qh,e)}async onPagehide(e){e.persisted||this.transport&&typeof this.transport.close=="function"&&await this.transport.close()}}const tI=(t,e)=>new Gu(t,e),rI=()=>Fx(),nI=t=>t instanceof Gu,aI=t=>t instanceof iv;class uv{constructor(e,r){const a={name:"web-mcp-client",version:"1.0.0"},n={roots:{listChanged:!0},sampling:{},elicitation:{}};this.client=new Ns(e||a,r||{capabilities:n}),this.client.onclose=()=>{var s;(s=this.onclose)==null||s.call(this)},this.client.onerror=s=>{var o;(o=this.onerror)==null||o.call(this,s)}}async connect(e){if(typeof e.start=="function")return this.transport=e,this.transport.onclose=void 0,this.transport.onerror=void 0,this.transport.onmessage=void 0,await this.client.connect(this.transport),{transport:this.transport,sessionId:this.transport.sessionId};const{url:r,token:a,sessionId:n,type:s,agent:o,onError:i}=e;if(o===!0){const u={client:this.client,url:r,token:a,sessionId:n};let h;return await(async()=>{const{transport:d,sessionId:f}=s==="sse"?await nk(u):s==="socket"?await sk(u):await ak(u);d.onerror=async v=>{i==null||i(v)},h={transport:d,sessionId:f}})(),h}const l=new URL(r);let c;if(s==="channel"&&(c=new Ju(r),await this.client.connect(c)),s==="sse"){const u=Bm(a,n);c=new zs(l,u),await this.client.connect(c)}if(s==="socket"&&(c=new Vm(new URL(`${r}?sessionId=${n}&token=${a}`)),c.sessionId=n,await this.client.connect(c)),typeof c>"u"){const u=Jm(a,n);c=new Us(l,u),await this.client.connect(c)}return this.transport=c,{transport:this.transport,sessionId:this.transport.sessionId}}async close(){await this.client.close()}getServerCapabilities(){return this.client.getServerCapabilities()}getServerVersion(){return this.client.getServerVersion()}getInstructions(){return this.client.getInstructions()}async ping(e){return await this.client.ping(e)}async complete(e,r){return await this.client.complete(e,r)}async setLoggingLevel(e,r){return await this.client.setLoggingLevel(e,r)}async getPrompt(e,r){return await this.client.getPrompt(e,r)}async listPrompts(e,r){return await this.client.listPrompts(e,r)}async listResources(e,r){return await this.client.listResources(e,r)}async listResourceTemplates(e,r){return await this.client.listResourceTemplates(e,r)}async readResource(e,r){return await this.client.readResource(e,r)}async subscribeResource(e,r){return await this.client.subscribeResource(e,r)}async unsubscribeResource(e,r){return await this.client.unsubscribeResource(e,r)}async callTool(e,r){return await this.client.callTool(e,ii,r)}async listTools(e,r){return await this.client.listTools(e,r)}async sendRootsListChanged(){return await this.client.sendRootsListChanged()}request(e,r,a){return this.client.request(e,r,a)}async notification(e,r){return await this.client.notification(e,r)}setRequestHandler(e,r){this.client.setRequestHandler(e,r)}removeRequestHandler(e){this.client.removeRequestHandler(e)}setNotificationHandler(e,r){this.client.setNotificationHandler(e,r)}removeNotificationHandler(e){this.client.removeNotificationHandler(e)}onElicit(e){this.client.setRequestHandler(Lh,e)}onCreateMessage(e){this.client.setRequestHandler(Dh,e)}onListRoots(e){this.client.setRequestHandler(Uh,e)}onToolListChanged(e){this.client.setNotificationHandler(Nh,e)}onPromptListChanged(e){this.client.setNotificationHandler(Oh,e)}onResourceListChanged(e){this.client.setNotificationHandler(Ph,e)}onResourceUpdated(e){this.client.setNotificationHandler(kh,e)}onLoggingMessage(e){this.client.setNotificationHandler(jh,e)}async onPagehide(e){e.persisted||(dv(this.transport)?await this.transport.terminateSession():this.transport&&typeof this.transport.close=="function"&&await this.transport.close())}}const sI=(t,e)=>new zs(t,e),oI=(t,e)=>new Us(t,e),iI=(t,e)=>new Ju(t,e),lI=t=>t instanceof zs,dv=t=>t instanceof Us,cI=t=>t instanceof Ju,uI=t=>t instanceof Ns,za=(t,e,r)=>{window.postMessage({type:t,direction:r,data:e},"*")},fv=(t,e,r)=>{const a=async function(n){n.source===window&&n.data.type===t&&n.data.direction===r&&await e(n.data.data)};return window.addEventListener("message",a),()=>window.removeEventListener("message",a)},rd=(t,e,r)=>{if(r.endsWith("content"))chrome.tabs.query({},a=>{a.forEach(n=>{chrome.tabs.sendMessage(n.id,{type:t,data:e,direction:r,tabId:n.id})})});else return chrome.runtime.sendMessage({direction:r,type:t,data:e})},nd=(t,e,r,a)=>{const n=(s,o,i)=>{if(s.type===t&&s.direction===r&&(!a||a&&s.tabId===a)){const{data:l}=s;e(l,o,i),i(o)}};return chrome.runtime.onMessage.addListener(n),()=>chrome.runtime.onMessage.removeListener(n)};class pv{constructor(e){this._isStarted=!1,this._isClosed=!1,this.targetSessionId=e,this._messageListener=nd("mcp-server-to-client",r=>{var a;try{if(r.sessionId!==this.targetSessionId)return;const n=ln.parse(r.mcpMessage);(a=this.onmessage)==null||a.call(this,n)}catch(n){console.log("【Client Transport】处理server消息错误:",n)}},"content->side")}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){this._throwError(()=>this._isClosed,"【Client Transport】 未启动,无法重新启动"),this._isStarted=!0}async send(e,r){this._throwError(()=>!this._isStarted,"【Client Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Client Transport】 已关闭,无法发送消息");const a=chrome.sessionRegistry.get(this.targetSessionId);this._throwError(()=>!a,`【Client Transport】sessionRegistry中未找到${this.targetSessionId}`);const n=a.tabIds[a.tabIds.length-1];rd("mcp-client-to-server",{sessionId:this.targetSessionId,tabId:n,mcpMessage:e},"side->content")}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this._messageListener&&this._messageListener(),this.onclose&&this.onclose()}catch{this._throwError(()=>!0,"【Client Transport】 关闭时发生错误")}}}const hv=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});class dI{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||hv(),this.tabId=r,this._messageListener1=fv("sidepanel-ready-to-page",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(a=>{console.error("【Page Svr Transport】 notifyRegistration失败:",a)})},"content->page"),this._messageListener2=fv("mcp-client-to-server-to-page",a=>{var o,i,l;if(a.sessionId!==this.sessionId||a.tabId!==this.tabId)return;console.log("【Page Svr Transport】 即将处理 mcpMessage",a.mcpMessage);const n=ln.parse(a.mcpMessage);(o=this.onmessage)==null||o.call(this,n),((i=a.mcpMessage.params)==null?void 0:i.name)&&za("update-page-app-message",{status:"run",message:(l=a.mcpMessage.params)==null?void 0:l.name},"page->content")},"content->page")}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){if(!this._isStarted){if(this._isClosed)throw new Error("【Page Svr Transport】 已关闭,无法重新启动");this._isStarted=!0}}async send(e,r){var a;this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Page Svr Transport】 已关闭,无法发送消息"),za("mcp-server-to-client-from-page",{sessionId:this.sessionId,mcpMessage:e},"page->content"),"result"in e&&((a=e.result)!=null&&a.content)&&za("update-page-app-message",{status:"ready",message:""},"page->content")}async notifyRegistration(e){this._throwError(()=>!this._isStarted,"【Page Svr Transport】 未启动,无法注册消息"),this._lastRegistration=e;try{za("mcp-server-register-from-page",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"page->content")}catch(r){this._throwError(()=>!0,"【Page Svr Transport】 注册 server 失败"+String(r))}}async close(){if(!this._isClosed)try{this._messageListener1&&this._messageListener1(),this._messageListener2&&this._messageListener2(),this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Page Svr Transport】 关闭时发生错误"+String(e))}}}class fI{constructor(e=null,r){this._isStarted=!1,this._isClosed=!1,this._lastRegistration=null,this.sessionId=e||hv(),this.tabId=r,nd("sidepanel-ready",()=>{this._lastRegistration&&this._isStarted&&this.notifyRegistration(this._lastRegistration).catch(a=>{console.log("【Content Svr Transport】 notifyRegistration 失败",a)})},"side->content",this.tabId)}_throwError(e,r){if(e()){const a=new Error(r);throw console.log(r,a),this.onerror&&this.onerror(a),a}}async start(){if(console.log("【Content Svr Transport】 启动 start",this.sessionId),!this._isStarted){if(this._isClosed)throw new Error("【Content Svr Transport】 已关闭,无法重新启动");nd("mcp-client-to-server",e=>{var r,a,n;if(!(e.sessionId!==this.sessionId||e.tabId!==this.tabId))try{console.log("【Content Svr Transport】 即将处理 mcpMessage",e.mcpMessage);const s=ln.parse(e.mcpMessage);(r=this.onmessage)==null||r.call(this,s),((a=e.mcpMessage.params)==null?void 0:a.name)&&za("update-page-app-message",{status:"run",message:(n=e.mcpMessage.params)==null?void 0:n.name},"page->content")}catch(s){console.log("【Content Svr Transport】 处理消息时发生错误:",s)}},"side->content",this.tabId),this._isStarted=!0}}async send(e,r){var a;this._throwError(()=>!this._isStarted,"【Content Svr Transport】 未启动,无法发送消息"),this._throwError(()=>this._isClosed,"【Content Svr Transport】 已关闭,无法发送消息");try{console.log("【Content Svr Transport】 发送消息到 MCP Client",e),rd("mcp-server-to-client",{sessionId:this.sessionId,mcpMessage:e},"content->side"),"result"in e&&((a=e.result)!=null&&a.content)&&za("update-page-app-message",{status:"ready",message:""},"page->content")}catch(n){this._throwError(()=>!0,"【Content Svr Transport】发送消息失败"+String(n))}}async notifyRegistration(e){this._isStarted&&(this._lastRegistration=e,rd("mcp-server-register",{sessionId:this.sessionId,serverInfo:{...e,url:window.location.origin,title:document.title}},"content->side"))}async close(){if(!this._isClosed)try{this._isClosed=!0,this._isStarted=!1,this.onclose&&this.onclose()}catch(e){this._throwError(()=>!0,"【Content Svr Transport】 关闭时发生错误"+String(e))}}}var Ua={},pI=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},mv={},nr={};let ad;const hI=[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];nr.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17},nr.getSymbolTotalCodewords=function(e){return hI[e]},nr.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e},nr.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');ad=e},nr.isKanjiModeEnabled=function(){return typeof ad<"u"},nr.toSJIS=function(e){return ad(e)};var zi={};(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+r)}}t.isValid=function(a){return a&&typeof a.bit<"u"&&a.bit>=0&&a.bit<4},t.from=function(a,n){if(t.isValid(a))return a;try{return e(a)}catch{return n}}})(zi);function vv(){this.buffer=[],this.length=0}vv.prototype={get:function(t){const e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let r=0;r<e;r++)this.putBit((t>>>e-r-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var mI=vv;function Vs(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)}Vs.prototype.set=function(t,e,r,a){const n=t*this.size+e;this.data[n]=r,a&&(this.reservedBit[n]=!0)},Vs.prototype.get=function(t,e){return this.data[t*this.size+e]},Vs.prototype.xor=function(t,e,r){this.data[t*this.size+e]^=r},Vs.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};var vI=Vs,gv={};(function(t){const e=nr.getSymbolSize;t.getRowColCoords=function(a){if(a===1)return[];const n=Math.floor(a/7)+2,s=e(a),o=s===145?26:Math.ceil((s-13)/(2*n-2))*2,i=[s-7];for(let l=1;l<n-1;l++)i[l]=i[l-1]-o;return i.push(6),i.reverse()},t.getPositions=function(a){const n=[],s=t.getRowColCoords(a),o=s.length;for(let i=0;i<o;i++)for(let l=0;l<o;l++)i===0&&l===0||i===0&&l===o-1||i===o-1&&l===0||n.push([s[i],s[l]]);return n}})(gv);var yv={};const gI=nr.getSymbolSize,_v=7;yv.getPositions=function(e){const r=gI(e);return[[0,0],[r-_v,0],[0,r-_v]]};var wv={};(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(n){return n!=null&&n!==""&&!isNaN(n)&&n>=0&&n<=7},t.from=function(n){return t.isValid(n)?parseInt(n,10):void 0},t.getPenaltyN1=function(n){const s=n.size;let o=0,i=0,l=0,c=null,u=null;for(let h=0;h<s;h++){i=l=0,c=u=null;for(let g=0;g<s;g++){let d=n.get(h,g);d===c?i++:(i>=5&&(o+=e.N1+(i-5)),c=d,i=1),d=n.get(g,h),d===u?l++:(l>=5&&(o+=e.N1+(l-5)),u=d,l=1)}i>=5&&(o+=e.N1+(i-5)),l>=5&&(o+=e.N1+(l-5))}return o},t.getPenaltyN2=function(n){const s=n.size;let o=0;for(let i=0;i<s-1;i++)for(let l=0;l<s-1;l++){const c=n.get(i,l)+n.get(i,l+1)+n.get(i+1,l)+n.get(i+1,l+1);(c===4||c===0)&&o++}return o*e.N2},t.getPenaltyN3=function(n){const s=n.size;let o=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|n.get(c,u),u>=10&&(i===1488||i===93)&&o++,l=l<<1&2047|n.get(u,c),u>=10&&(l===1488||l===93)&&o++}return o*e.N3},t.getPenaltyN4=function(n){let s=0;const o=n.data.length;for(let l=0;l<o;l++)s+=n.data[l];return Math.abs(Math.ceil(s*100/o/5)-10)*e.N4};function r(a,n,s){switch(a){case t.Patterns.PATTERN000:return(n+s)%2===0;case t.Patterns.PATTERN001:return n%2===0;case t.Patterns.PATTERN010:return s%3===0;case t.Patterns.PATTERN011:return(n+s)%3===0;case t.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(s/3))%2===0;case t.Patterns.PATTERN101:return n*s%2+n*s%3===0;case t.Patterns.PATTERN110:return(n*s%2+n*s%3)%2===0;case t.Patterns.PATTERN111:return(n*s%3+(n+s)%2)%2===0;default:throw new Error("bad maskPattern:"+a)}}t.applyMask=function(n,s){const o=s.size;for(let i=0;i<o;i++)for(let l=0;l<o;l++)s.isReserved(l,i)||s.xor(l,i,r(n,l,i))},t.getBestMask=function(n,s){const o=Object.keys(t.Patterns).length;let i=0,l=1/0;for(let c=0;c<o;c++){s(c),t.applyMask(c,n);const u=t.getPenaltyN1(n)+t.getPenaltyN2(n)+t.getPenaltyN3(n)+t.getPenaltyN4(n);t.applyMask(c,n),u<l&&(l=u,i=c)}return i}})(wv);var Ui={};const Pn=zi,qi=[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],Fi=[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];Ui.getBlocksCount=function(e,r){switch(r){case Pn.L:return qi[(e-1)*4+0];case Pn.M:return qi[(e-1)*4+1];case Pn.Q:return qi[(e-1)*4+2];case Pn.H:return qi[(e-1)*4+3];default:return}},Ui.getTotalCodewordsCount=function(e,r){switch(r){case Pn.L:return Fi[(e-1)*4+0];case Pn.M:return Fi[(e-1)*4+1];case Pn.Q:return Fi[(e-1)*4+2];case Pn.H:return Fi[(e-1)*4+3];default:return}};var bv={},Zi={};const Hs=new Uint8Array(512),Vi=new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)Hs[r]=e,Vi[e]=r,e<<=1,e&256&&(e^=285);for(let r=255;r<512;r++)Hs[r]=Hs[r-255]})(),Zi.log=function(e){if(e<1)throw new Error("log("+e+")");return Vi[e]},Zi.exp=function(e){return Hs[e]},Zi.mul=function(e,r){return e===0||r===0?0:Hs[Vi[e]+Vi[r]]},function(t){const e=Zi;t.mul=function(a,n){const s=new Uint8Array(a.length+n.length-1);for(let o=0;o<a.length;o++)for(let i=0;i<n.length;i++)s[o+i]^=e.mul(a[o],n[i]);return s},t.mod=function(a,n){let s=new Uint8Array(a);for(;s.length-n.length>=0;){const o=s[0];for(let l=0;l<n.length;l++)s[l]^=e.mul(n[l],o);let i=0;for(;i<s.length&&s[i]===0;)i++;s=s.slice(i)}return s},t.generateECPolynomial=function(a){let n=new Uint8Array([1]);for(let s=0;s<a;s++)n=t.mul(n,new Uint8Array([1,e.exp(s)]));return n}}(bv);const Ev=bv;function sd(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}sd.prototype.initialize=function(e){this.degree=e,this.genPoly=Ev.generateECPolynomial(this.degree)},sd.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");const r=new Uint8Array(e.length+this.degree);r.set(e);const a=Ev.mod(r,this.genPoly),n=this.degree-a.length;if(n>0){const s=new Uint8Array(this.degree);return s.set(a,n),s}return a};var yI=sd,$v={},Tn={},od={};od.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40};var Hr={};const Sv="[0-9]+",_I="[A-Z $%*+\\-./:]+";let Bs="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Bs=Bs.replace(/u/g,"\\u");const wI="(?:(?![A-Z0-9 $%*+\\-./:]|"+Bs+`)(?:.|[\r
17
+ ]))+`;Hr.KANJI=new RegExp(Bs,"g"),Hr.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Hr.BYTE=new RegExp(wI,"g"),Hr.NUMERIC=new RegExp(Sv,"g"),Hr.ALPHANUMERIC=new RegExp(_I,"g");const bI=new RegExp("^"+Bs+"$"),EI=new RegExp("^"+Sv+"$"),$I=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Hr.testKanji=function(e){return bI.test(e)},Hr.testNumeric=function(e){return EI.test(e)},Hr.testAlphanumeric=function(e){return $I.test(e)},function(t){const e=od,r=Hr;t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(s,o){if(!s.ccBits)throw new Error("Invalid mode: "+s);if(!e.isValid(o))throw new Error("Invalid version: "+o);return o>=1&&o<10?s.ccBits[0]:o<27?s.ccBits[1]:s.ccBits[2]},t.getBestModeForData=function(s){return r.testNumeric(s)?t.NUMERIC:r.testAlphanumeric(s)?t.ALPHANUMERIC:r.testKanji(s)?t.KANJI:t.BYTE},t.toString=function(s){if(s&&s.id)return s.id;throw new Error("Invalid mode")},t.isValid=function(s){return s&&s.bit&&s.ccBits};function a(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+n)}}t.from=function(s,o){if(t.isValid(s))return s;try{return a(s)}catch{return o}}}(Tn),function(t){const e=nr,r=Ui,a=zi,n=Tn,s=od,o=7973,i=e.getBCHDigit(o);function l(g,d,f){for(let v=1;v<=40;v++)if(d<=t.getCapacity(v,f,g))return v}function c(g,d){return n.getCharCountIndicator(g,d)+4}function u(g,d){let f=0;return g.forEach(function(v){const m=c(v.mode,d);f+=m+v.getBitsLength()}),f}function h(g,d){for(let f=1;f<=40;f++)if(u(g,f)<=t.getCapacity(f,d,n.MIXED))return f}t.from=function(d,f){return s.isValid(d)?parseInt(d,10):f},t.getCapacity=function(d,f,v){if(!s.isValid(d))throw new Error("Invalid QR Code version");typeof v>"u"&&(v=n.BYTE);const m=e.getSymbolTotalCodewords(d),p=r.getTotalCodewordsCount(d,f),y=(m-p)*8;if(v===n.MIXED)return y;const _=y-c(v,d);switch(v){case n.NUMERIC:return Math.floor(_/10*3);case n.ALPHANUMERIC:return Math.floor(_/11*2);case n.KANJI:return Math.floor(_/13);case n.BYTE:default:return Math.floor(_/8)}},t.getBestVersionForData=function(d,f){let v;const m=a.from(f,a.M);if(Array.isArray(d)){if(d.length>1)return h(d,m);if(d.length===0)return 1;v=d[0]}else v=d;return l(v.mode,v.getLength(),m)},t.getEncodedBits=function(d){if(!s.isValid(d)||d<7)throw new Error("Invalid QR Code version");let f=d<<12;for(;e.getBCHDigit(f)-i>=0;)f^=o<<e.getBCHDigit(f)-i;return d<<12|f}}($v);var Pv={};const id=nr,Tv=1335,SI=21522,xv=id.getBCHDigit(Tv);Pv.getEncodedBits=function(e,r){const a=e.bit<<3|r;let n=a<<10;for(;id.getBCHDigit(n)-xv>=0;)n^=Tv<<id.getBCHDigit(n)-xv;return(a<<10|n)^SI};var kv={};const PI=Tn;function qa(t){this.mode=PI.NUMERIC,this.data=t.toString()}qa.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)},qa.prototype.getLength=function(){return this.data.length},qa.prototype.getBitsLength=function(){return qa.getBitsLength(this.data.length)},qa.prototype.write=function(e){let r,a,n;for(r=0;r+3<=this.data.length;r+=3)a=this.data.substr(r,3),n=parseInt(a,10),e.put(n,10);const s=this.data.length-r;s>0&&(a=this.data.substr(r),n=parseInt(a,10),e.put(n,s*3+1))};var TI=qa;const xI=Tn,ld=["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 Fa(t){this.mode=xI.ALPHANUMERIC,this.data=t}Fa.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)},Fa.prototype.getLength=function(){return this.data.length},Fa.prototype.getBitsLength=function(){return Fa.getBitsLength(this.data.length)},Fa.prototype.write=function(e){let r;for(r=0;r+2<=this.data.length;r+=2){let a=ld.indexOf(this.data[r])*45;a+=ld.indexOf(this.data[r+1]),e.put(a,11)}this.data.length%2&&e.put(ld.indexOf(this.data[r]),6)};var kI=Fa;const II=Tn;function Za(t){this.mode=II.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Za.getBitsLength=function(e){return e*8},Za.prototype.getLength=function(){return this.data.length},Za.prototype.getBitsLength=function(){return Za.getBitsLength(this.data.length)},Za.prototype.write=function(t){for(let e=0,r=this.data.length;e<r;e++)t.put(this.data[e],8)};var CI=Za;const RI=Tn,OI=nr;function Va(t){this.mode=RI.KANJI,this.data=t}Va.getBitsLength=function(e){return e*13},Va.prototype.getLength=function(){return this.data.length},Va.prototype.getBitsLength=function(){return Va.getBitsLength(this.data.length)},Va.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let r=OI.toSJIS(this.data[e]);if(r>=33088&&r<=40956)r-=33088;else if(r>=57408&&r<=60351)r-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
18
+ Make sure your charset is UTF-8`);r=(r>>>8&255)*192+(r&255),t.put(r,13)}};var AI=Va,Iv={exports:{}};(function(t){var e={single_source_shortest_paths:function(r,a,n){var s={},o={};o[a]=0;var i=e.PriorityQueue.make();i.push(a,0);for(var l,c,u,h,g,d,f,v,m;!i.empty();){l=i.pop(),c=l.value,h=l.cost,g=r[c]||{};for(u in g)g.hasOwnProperty(u)&&(d=g[u],f=h+d,v=o[u],m=typeof o[u]>"u",(m||v>f)&&(o[u]=f,i.push(u,f),s[u]=c))}if(typeof n<"u"&&typeof o[n]>"u"){var p=["Could not find a path from ",a," to ",n,"."].join("");throw new Error(p)}return s},extract_shortest_path_from_predecessor_list:function(r,a){for(var n=[],s=a;s;)n.push(s),r[s],s=r[s];return n.reverse(),n},find_path:function(r,a,n){var s=e.single_source_shortest_paths(r,a,n);return e.extract_shortest_path_from_predecessor_list(s,n)},PriorityQueue:{make:function(r){var a=e.PriorityQueue,n={},s;r=r||{};for(s in a)a.hasOwnProperty(s)&&(n[s]=a[s]);return n.queue=[],n.sorter=r.sorter||a.default_sorter,n},default_sorter:function(r,a){return r.cost-a.cost},push:function(r,a){var n={value:r,cost:a};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(Iv);var NI=Iv.exports;(function(t){const e=Tn,r=TI,a=kI,n=CI,s=AI,o=Hr,i=nr,l=NI;function c(p){return unescape(encodeURIComponent(p)).length}function u(p,y,_){const w=[];let E;for(;(E=p.exec(_))!==null;)w.push({data:E[0],index:E.index,mode:y,length:E[0].length});return w}function h(p){const y=u(o.NUMERIC,e.NUMERIC,p),_=u(o.ALPHANUMERIC,e.ALPHANUMERIC,p);let w,E;return i.isKanjiModeEnabled()?(w=u(o.BYTE,e.BYTE,p),E=u(o.KANJI,e.KANJI,p)):(w=u(o.BYTE_KANJI,e.BYTE,p),E=[]),y.concat(_,w,E).sort(function(T,O){return T.index-O.index}).map(function(T){return{data:T.data,mode:T.mode,length:T.length}})}function g(p,y){switch(y){case e.NUMERIC:return r.getBitsLength(p);case e.ALPHANUMERIC:return a.getBitsLength(p);case e.KANJI:return s.getBitsLength(p);case e.BYTE:return n.getBitsLength(p)}}function d(p){return p.reduce(function(y,_){const w=y.length-1>=0?y[y.length-1]:null;return w&&w.mode===_.mode?(y[y.length-1].data+=_.data,y):(y.push(_),y)},[])}function f(p){const y=[];for(let _=0;_<p.length;_++){const w=p[_];switch(w.mode){case e.NUMERIC:y.push([w,{data:w.data,mode:e.ALPHANUMERIC,length:w.length},{data:w.data,mode:e.BYTE,length:w.length}]);break;case e.ALPHANUMERIC:y.push([w,{data:w.data,mode:e.BYTE,length:w.length}]);break;case e.KANJI:y.push([w,{data:w.data,mode:e.BYTE,length:c(w.data)}]);break;case e.BYTE:y.push([{data:w.data,mode:e.BYTE,length:c(w.data)}])}}return y}function v(p,y){const _={},w={start:{}};let E=["start"];for(let P=0;P<p.length;P++){const T=p[P],O=[];for(let M=0;M<T.length;M++){const J=T[M],H=""+P+M;O.push(H),_[H]={node:J,lastCount:0},w[H]={};for(let G=0;G<E.length;G++){const F=E[G];_[F]&&_[F].node.mode===J.mode?(w[F][H]=g(_[F].lastCount+J.length,J.mode)-g(_[F].lastCount,J.mode),_[F].lastCount+=J.length):(_[F]&&(_[F].lastCount=J.length),w[F][H]=g(J.length,J.mode)+4+e.getCharCountIndicator(J.mode,y))}}E=O}for(let P=0;P<E.length;P++)w[E[P]].end=0;return{map:w,table:_}}function m(p,y){let _;const w=e.getBestModeForData(p);if(_=e.from(y,w),_!==e.BYTE&&_.bit<w.bit)throw new Error('"'+p+'" cannot be encoded with mode '+e.toString(_)+`.
19
+ Suggested mode is: `+e.toString(w));switch(_===e.KANJI&&!i.isKanjiModeEnabled()&&(_=e.BYTE),_){case e.NUMERIC:return new r(p);case e.ALPHANUMERIC:return new a(p);case e.KANJI:return new s(p);case e.BYTE:return new n(p)}}t.fromArray=function(y){return y.reduce(function(_,w){return typeof w=="string"?_.push(m(w,null)):w.data&&_.push(m(w.data,w.mode)),_},[])},t.fromString=function(y,_){const w=h(y,i.isKanjiModeEnabled()),E=f(w),P=v(E,_),T=l.find_path(P.map,"start","end"),O=[];for(let M=1;M<T.length-1;M++)O.push(P.table[T[M]].node);return t.fromArray(d(O))},t.rawSplit=function(y){return t.fromArray(h(y,i.isKanjiModeEnabled()))}})(kv);const Hi=nr,cd=zi,MI=mI,jI=vI,DI=gv,LI=yv,ud=wv,dd=Ui,zI=yI,Bi=$v,UI=Pv,qI=Tn,fd=kv;function FI(t,e){const r=t.size,a=LI.getPositions(e);for(let n=0;n<a.length;n++){const s=a[n][0],o=a[n][1];for(let i=-1;i<=7;i++)if(!(s+i<=-1||r<=s+i))for(let l=-1;l<=7;l++)o+l<=-1||r<=o+l||(i>=0&&i<=6&&(l===0||l===6)||l>=0&&l<=6&&(i===0||i===6)||i>=2&&i<=4&&l>=2&&l<=4?t.set(s+i,o+l,!0,!0):t.set(s+i,o+l,!1,!0))}}function ZI(t){const e=t.size;for(let r=8;r<e-8;r++){const a=r%2===0;t.set(r,6,a,!0),t.set(6,r,a,!0)}}function VI(t,e){const r=DI.getPositions(e);for(let a=0;a<r.length;a++){const n=r[a][0],s=r[a][1];for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)o===-2||o===2||i===-2||i===2||o===0&&i===0?t.set(n+o,s+i,!0,!0):t.set(n+o,s+i,!1,!0)}}function HI(t,e){const r=t.size,a=Bi.getEncodedBits(e);let n,s,o;for(let i=0;i<18;i++)n=Math.floor(i/3),s=i%3+r-8-3,o=(a>>i&1)===1,t.set(n,s,o,!0),t.set(s,n,o,!0)}function pd(t,e,r){const a=t.size,n=UI.getEncodedBits(e,r);let s,o;for(s=0;s<15;s++)o=(n>>s&1)===1,s<6?t.set(s,8,o,!0):s<8?t.set(s+1,8,o,!0):t.set(a-15+s,8,o,!0),s<8?t.set(8,a-s-1,o,!0):s<9?t.set(8,15-s-1+1,o,!0):t.set(8,15-s-1,o,!0);t.set(a-8,8,1,!0)}function BI(t,e){const r=t.size;let a=-1,n=r-1,s=7,o=0;for(let i=r-1;i>0;i-=2)for(i===6&&i--;;){for(let l=0;l<2;l++)if(!t.isReserved(n,i-l)){let c=!1;o<e.length&&(c=(e[o]>>>s&1)===1),t.set(n,i-l,c),s--,s===-1&&(o++,s=7)}if(n+=a,n<0||r<=n){n-=a,a=-a;break}}}function JI(t,e,r){const a=new MI;r.forEach(function(l){a.put(l.mode.bit,4),a.put(l.getLength(),qI.getCharCountIndicator(l.mode,t)),l.write(a)});const n=Hi.getSymbolTotalCodewords(t),s=dd.getTotalCodewordsCount(t,e),o=(n-s)*8;for(a.getLengthInBits()+4<=o&&a.put(0,4);a.getLengthInBits()%8!==0;)a.putBit(0);const i=(o-a.getLengthInBits())/8;for(let l=0;l<i;l++)a.put(l%2?17:236,8);return GI(a,t,e)}function GI(t,e,r){const a=Hi.getSymbolTotalCodewords(e),n=dd.getTotalCodewordsCount(e,r),s=a-n,o=dd.getBlocksCount(e,r),i=a%o,l=o-i,c=Math.floor(a/o),u=Math.floor(s/o),h=u+1,g=c-u,d=new zI(g);let f=0;const v=new Array(o),m=new Array(o);let p=0;const y=new Uint8Array(t.buffer);for(let T=0;T<o;T++){const O=T<l?u:h;v[T]=y.slice(f,f+O),m[T]=d.encode(v[T]),f+=O,p=Math.max(p,O)}const _=new Uint8Array(a);let w=0,E,P;for(E=0;E<p;E++)for(P=0;P<o;P++)E<v[P].length&&(_[w++]=v[P][E]);for(E=0;E<g;E++)for(P=0;P<o;P++)_[w++]=m[P][E];return _}function KI(t,e,r,a){let n;if(Array.isArray(t))n=fd.fromArray(t);else if(typeof t=="string"){let c=e;if(!c){const u=fd.rawSplit(t);c=Bi.getBestVersionForData(u,r)}n=fd.fromString(t,c||40)}else throw new Error("Invalid data");const s=Bi.getBestVersionForData(n,r);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
20
20
  The chosen QR Code version cannot contain this amount of data.
21
21
  Minimum version required to store current data is: `+s+`.
22
- `);const o=FT(e,r,n),i=tl.getSymbolSize(e),l=new RT(i);return DT(l,e),LT(l),zT(l,e),Sd(l,r,0),e>=7&&UT(l,e),qT(l,o),isNaN(a)&&(a=wd.getBestMask(l,Sd.bind(null,l,r))),wd.applyMask(a,l),Sd(l,r,a),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:a,segments:n}}fv.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let a=_d.M,n,s;return typeof r<"u"&&(a=_d.from(r.errorCorrectionLevel,_d.M),n=rl.from(r.version),s=wd.from(r.maskPattern),r.toSJISFunc&&tl.setToSJISFunction(r.toSJISFunc)),VT(e,n,a,s)};var xv={},$d={};(function(t){function e(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let a=r.slice().replace("#","").split("");if(a.length<3||a.length===5||a.length>8)throw new Error("Invalid hex color: "+r);(a.length===3||a.length===4)&&(a=Array.prototype.concat.apply([],a.map(function(s){return[s,s]}))),a.length===6&&a.push("F","F");const n=parseInt(a.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+a.slice(0,6).join("")}}t.getOptions=function(a){a||(a={}),a.color||(a.color={});const n=typeof a.margin>"u"||a.margin===null||a.margin<0?4:a.margin,s=a.width&&a.width>=21?a.width:void 0,o=a.scale||4;return{width:s,scale:s?4:o,margin:n,color:{dark:e(a.color.dark||"#000000ff"),light:e(a.color.light||"#ffffffff")},type:a.type,rendererOpts:a.rendererOpts||{}}},t.getScale=function(a,n){return n.width&&n.width>=a+n.margin*2?n.width/(a+n.margin*2):n.scale},t.getImageWidth=function(a,n){const s=t.getScale(a,n);return Math.floor((a+n.margin*2)*s)},t.qrToImageData=function(a,n,s){const o=n.modules.size,i=n.modules.data,l=t.getScale(o,s),c=Math.floor((o+s.margin*2)*l),u=s.margin*l,f=[s.color.light,s.color.dark];for(let g=0;g<c;g++)for(let d=0;d<c;d++){let h=(g*c+d)*4,v=s.color.light;if(g>=u&&d>=u&&g<c-u&&d<c-u){const m=Math.floor((g-u)/l),p=Math.floor((d-u)/l);v=f[i[m*o+p]?1:0]}a[h++]=v.r,a[h++]=v.g,a[h++]=v.b,a[h]=v.a}}})($d),function(t){const e=$d;function r(n,s,o){n.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=o,s.width=o,s.style.height=o+"px",s.style.width=o+"px"}function a(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,o,i){let l=i,c=o;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),o||(c=a()),l=e.getOptions(l);const u=e.getImageWidth(s.modules.size,l),f=c.getContext("2d"),g=f.createImageData(u,u);return e.qrToImageData(g.data,s,l),r(f,c,u),f.putImageData(g,0,0),c},t.renderToDataURL=function(s,o,i){let l=i;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),l||(l={});const c=t.render(s,o,l),u=l.type||"image/png",f=l.rendererOpts||{};return c.toDataURL(u,f.quality)}}(xv);var Tv={};const HT=$d;function Cv(t,e){const r=t.a/255,a=e+'="'+t.hex+'"';return r<1?a+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':a}function Pd(t,e,r){let a=t+e;return typeof r<"u"&&(a+=" "+r),a}function BT(t,e,r){let a="",n=0,s=!1,o=0;for(let i=0;i<t.length;i++){const l=Math.floor(i%e),c=Math.floor(i/e);!l&&!s&&(s=!0),t[i]?(o++,i>0&&l>0&&t[i-1]||(a+=s?Pd("M",l+r,.5+c+r):Pd("m",n,0),n=0,s=!1),l+1<e&&t[i+1]||(a+=Pd("h",o),o=0)):n++}return a}Tv.render=function(e,r,a){const n=HT.getOptions(r),s=e.modules.size,o=e.modules.data,i=s+n.margin*2,l=n.color.light.a?"<path "+Cv(n.color.light,"fill")+' d="M0 0h'+i+"v"+i+'H0z"/>':"",c="<path "+Cv(n.color.dark,"stroke")+' d="'+BT(o,s,n.margin)+'"/>',u='viewBox="0 0 '+i+" "+i+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(n.width?'width="'+n.width+'" height="'+n.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
23
- `;return typeof a=="function"&&a(null,g),g};const JT=lT,kd=fv,Rv=xv,GT=Tv;function Id(t,e,r,a,n){const s=[].slice.call(arguments,1),o=s.length,i=typeof s[o-1]=="function";if(!i&&!JT())throw new Error("Callback required as last argument");if(i){if(o<2)throw new Error("Too few arguments provided");o===2?(n=r,r=e,e=a=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=a,a=void 0):(n=a,a=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=a=void 0):o===2&&!e.getContext&&(a=r,r=e,e=void 0),new Promise(function(l,c){try{const u=kd.create(r,a);l(t(u,e,a))}catch(u){c(u)}})}try{const l=kd.create(r,a);n(null,t(l,e,a))}catch(l){n(l)}}Ba.create=kd.create,Ba.toCanvas=Id.bind(null,Rv.render),Ba.toDataURL=Id.bind(null,Rv.renderToDataURL),Ba.toString=Id.bind(null,function(t,e,r){return GT.render(t,r)});class Ov{constructor(e,{size:r=200,margin:a=4,color:n="#000",bgColor:s="#fff"}){this.value=e,this.size=r,this.margin=a,this.color=n,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return Ba.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return Ba.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const KT="https://agent.opentiny.design/tiny-robot",Nv="https://ai.opentiny.design/next-remoter",Av=t=>[{action:"qr-code",show:!0,text:"弹出二维码",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
22
+ `);const o=JI(e,r,n),i=Hi.getSymbolSize(e),l=new jI(i);return FI(l,e),ZI(l),VI(l,e),pd(l,r,0),e>=7&&HI(l,e),BI(l,o),isNaN(a)&&(a=ud.getBestMask(l,pd.bind(null,l,r))),ud.applyMask(a,l),pd(l,r,a),{modules:l,version:e,errorCorrectionLevel:r,maskPattern:a,segments:n}}mv.create=function(e,r){if(typeof e>"u"||e==="")throw new Error("No input text");let a=cd.M,n,s;return typeof r<"u"&&(a=cd.from(r.errorCorrectionLevel,cd.M),n=Bi.from(r.version),s=ud.from(r.maskPattern),r.toSJISFunc&&Hi.setToSJISFunction(r.toSJISFunc)),KI(e,n,a,s)};var Cv={},hd={};(function(t){function e(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let a=r.slice().replace("#","").split("");if(a.length<3||a.length===5||a.length>8)throw new Error("Invalid hex color: "+r);(a.length===3||a.length===4)&&(a=Array.prototype.concat.apply([],a.map(function(s){return[s,s]}))),a.length===6&&a.push("F","F");const n=parseInt(a.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+a.slice(0,6).join("")}}t.getOptions=function(a){a||(a={}),a.color||(a.color={});const n=typeof a.margin>"u"||a.margin===null||a.margin<0?4:a.margin,s=a.width&&a.width>=21?a.width:void 0,o=a.scale||4;return{width:s,scale:s?4:o,margin:n,color:{dark:e(a.color.dark||"#000000ff"),light:e(a.color.light||"#ffffffff")},type:a.type,rendererOpts:a.rendererOpts||{}}},t.getScale=function(a,n){return n.width&&n.width>=a+n.margin*2?n.width/(a+n.margin*2):n.scale},t.getImageWidth=function(a,n){const s=t.getScale(a,n);return Math.floor((a+n.margin*2)*s)},t.qrToImageData=function(a,n,s){const o=n.modules.size,i=n.modules.data,l=t.getScale(o,s),c=Math.floor((o+s.margin*2)*l),u=s.margin*l,h=[s.color.light,s.color.dark];for(let g=0;g<c;g++)for(let d=0;d<c;d++){let f=(g*c+d)*4,v=s.color.light;if(g>=u&&d>=u&&g<c-u&&d<c-u){const m=Math.floor((g-u)/l),p=Math.floor((d-u)/l);v=h[i[m*o+p]?1:0]}a[f++]=v.r,a[f++]=v.g,a[f++]=v.b,a[f]=v.a}}})(hd),function(t){const e=hd;function r(n,s,o){n.clearRect(0,0,s.width,s.height),s.style||(s.style={}),s.height=o,s.width=o,s.style.height=o+"px",s.style.width=o+"px"}function a(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}t.render=function(s,o,i){let l=i,c=o;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),o||(c=a()),l=e.getOptions(l);const u=e.getImageWidth(s.modules.size,l),h=c.getContext("2d"),g=h.createImageData(u,u);return e.qrToImageData(g.data,s,l),r(h,c,u),h.putImageData(g,0,0),c},t.renderToDataURL=function(s,o,i){let l=i;typeof l>"u"&&(!o||!o.getContext)&&(l=o,o=void 0),l||(l={});const c=t.render(s,o,l),u=l.type||"image/png",h=l.rendererOpts||{};return c.toDataURL(u,h.quality)}}(Cv);var Rv={};const WI=hd;function Ov(t,e){const r=t.a/255,a=e+'="'+t.hex+'"';return r<1?a+" "+e+'-opacity="'+r.toFixed(2).slice(1)+'"':a}function md(t,e,r){let a=t+e;return typeof r<"u"&&(a+=" "+r),a}function QI(t,e,r){let a="",n=0,s=!1,o=0;for(let i=0;i<t.length;i++){const l=Math.floor(i%e),c=Math.floor(i/e);!l&&!s&&(s=!0),t[i]?(o++,i>0&&l>0&&t[i-1]||(a+=s?md("M",l+r,.5+c+r):md("m",n,0),n=0,s=!1),l+1<e&&t[i+1]||(a+=md("h",o),o=0)):n++}return a}Rv.render=function(e,r,a){const n=WI.getOptions(r),s=e.modules.size,o=e.modules.data,i=s+n.margin*2,l=n.color.light.a?"<path "+Ov(n.color.light,"fill")+' d="M0 0h'+i+"v"+i+'H0z"/>':"",c="<path "+Ov(n.color.dark,"stroke")+' d="'+QI(o,s,n.margin)+'"/>',u='viewBox="0 0 '+i+" "+i+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(n.width?'width="'+n.width+'" height="'+n.width+'" ':"")+u+' shape-rendering="crispEdges">'+l+c+`</svg>
23
+ `;return typeof a=="function"&&a(null,g),g};const YI=pI,vd=mv,Av=Cv,XI=Rv;function gd(t,e,r,a,n){const s=[].slice.call(arguments,1),o=s.length,i=typeof s[o-1]=="function";if(!i&&!YI())throw new Error("Callback required as last argument");if(i){if(o<2)throw new Error("Too few arguments provided");o===2?(n=r,r=e,e=a=void 0):o===3&&(e.getContext&&typeof n>"u"?(n=a,a=void 0):(n=a,a=r,r=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(r=e,e=a=void 0):o===2&&!e.getContext&&(a=r,r=e,e=void 0),new Promise(function(l,c){try{const u=vd.create(r,a);l(t(u,e,a))}catch(u){c(u)}})}try{const l=vd.create(r,a);n(null,t(l,e,a))}catch(l){n(l)}}Ua.create=vd.create,Ua.toCanvas=gd.bind(null,Av.render),Ua.toDataURL=gd.bind(null,Av.renderToDataURL),Ua.toString=gd.bind(null,function(t,e,r){return XI.render(t,r)});class Nv{constructor(e,{size:r=200,margin:a=4,color:n="#000",bgColor:s="#fff"}){this.value=e,this.size=r,this.margin=a,this.color=n,this.bgColor=s}get qrCodeOption(){return{width:this.size,margin:this.margin,color:{dark:this.color,light:this.bgColor}}}async toDataURL(){return Ua.toDataURL(this.value,this.qrCodeOption)}async toCanvas(e){return Ua.toCanvas(e,this.value,this.qrCodeOption)}async toImage(e){e.src=await this.toDataURL()}}const eC="https://agent.opentiny.design/tiny-robot",Mv="https://ai.opentiny.design/next-remoter",jv=t=>[{action:"qr-code",show:!0,text:"弹出二维码",icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
24
24
  <rect x="3" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
25
25
  <rect x="15" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
26
26
  <rect x="3" y="15" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2" fill="none"/>
@@ -47,9 +47,9 @@ Minimum version required to store current data is: `+s+`.
47
47
  </svg>`},{action:"remote-url",show:!0,text:`${t.remoteUrl}`,tip:t.remoteUrl,showCopyIcon:!0,icon:`<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
48
48
  <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
49
49
  <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
50
- </svg>`}];class WT{constructor(e){if(this.isExpanded=!1,!e.sessionId)throw new Error("sessionId is required");this.options={...e,qrCodeUrl:e.qrCodeUrl||Nv,remoteUrl:e.remoteUrl||KT},this.menuItems=this.mergeMenuItems(e.menuItems),this.init()}get sessionPrefix(){var e;return(e=this.options.qrCodeUrl)!=null&&e.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(e){return e?Av(this.options).map(r=>{const a=e.find(n=>n.action===r.action);return a?{...r,...a,show:a.show!==void 0?a.show:r.show}:r}):Av(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=`
50
+ </svg>`}];class tC{constructor(e){if(this.isExpanded=!1,!e.sessionId)throw new Error("sessionId is required");this.options={...e,qrCodeUrl:e.qrCodeUrl||Mv,remoteUrl:e.remoteUrl||eC},this.menuItems=this.mergeMenuItems(e.menuItems),this.init()}get sessionPrefix(){var e;return(e=this.options.qrCodeUrl)!=null&&e.includes("?")?"&sessionId=":"?sessionId="}mergeMenuItems(e){return e?jv(this.options).map(r=>{const a=e.find(n=>n.action===r.action);return a?{...r,...a,show:a.show!==void 0?a.show:r.show}:r}):jv(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=`
51
51
  <div class="tiny-remoter-floating-block__icon">
52
- <img style="display: block; width: 56px;" src="${Nv}/svgs/logo-next-no-bg-left.svg" alt="icon" />
52
+ <img style="display: block; width: 56px;" src="${Mv}/svgs/logo-next-no-bg-left.svg" alt="icon" />
53
53
  </div>
54
54
  `,document.body.appendChild(this.floatingBlock)}createDropdownMenu(){this.dropdownMenu=document.createElement("div"),this.dropdownMenu.className="tiny-remoter-floating-dropdown";const e=this.menuItems.filter(r=>r.show!==!1).map(r=>`
55
55
  <div class="tiny-remoter-dropdown-item" data-action="${r.action}">
@@ -65,7 +65,7 @@ Minimum version required to store current data is: `+s+`.
65
65
  </div>
66
66
  `:""}
67
67
  </div>
68
- `).join("");this.dropdownMenu.innerHTML=e,document.body.appendChild(this.dropdownMenu)}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",e=>{const r=e.target,a=r.closest(".tiny-remoter-copy-icon");if(a){e.stopPropagation();const o=a.dataset.action;o&&this.handleAction(o);return}const n=r.closest(".tiny-remoter-dropdown-item"),s=n==null?void 0:n.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",e=>{const r=e.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",e=>{e.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(e){switch(e){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(e){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const a=document.execCommand("copy");document.body.removeChild(r),a?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(e){const r=e?"复制成功!":"复制失败,请手动复制",a=document.createElement("div");a.className=`tiny-remoter-copy-feedback ${e?"success":"error"}`,a.textContent=r,document.body.appendChild(a),setTimeout(()=>a.classList.add("show"),10),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},300)},1500)}async showQRCode(){const r=await new Ov((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),a=this.createModal("扫码前往智能遥控器",`
68
+ `).join("");this.dropdownMenu.innerHTML=e,document.body.appendChild(this.dropdownMenu)}bindEvents(){this.floatingBlock.addEventListener("click",()=>{this.toggleDropdown()}),this.dropdownMenu.addEventListener("click",e=>{const r=e.target,a=r.closest(".tiny-remoter-copy-icon");if(a){e.stopPropagation();const o=a.dataset.action;o&&this.handleAction(o);return}const n=r.closest(".tiny-remoter-dropdown-item"),s=n==null?void 0:n.dataset.action;s&&this.handleAction(s)}),document.addEventListener("click",e=>{const r=e.target;!this.floatingBlock.contains(r)&&!this.dropdownMenu.contains(r)&&this.closeDropdown()}),document.addEventListener("keydown",e=>{e.key==="Escape"&&this.closeDropdown()})}toggleDropdown(){this.isExpanded?this.closeDropdown():this.openDropdown()}openDropdown(){this.isExpanded=!0,this.floatingBlock.classList.add("expanded"),this.dropdownMenu.classList.add("show")}closeDropdown(){this.isExpanded=!1,this.floatingBlock.classList.remove("expanded"),this.dropdownMenu.classList.remove("show")}handleAction(e){switch(e){case"qr-code":this.showQRCode();break;case"ai-chat":this.showAIChat();break;case"remote-control":this.copyRemoteControl();break;case"remote-url":this.copyRemoteURL();break}this.closeDropdown()}copyRemoteControl(){this.copyToClipboard(this.options.sessionId.slice(-6))}copyRemoteURL(){this.copyToClipboard(this.options.remoteUrl+this.sessionPrefix+this.options.sessionId)}async copyToClipboard(e){try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e),this.showCopyFeedback(!0);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.left="-999999px",r.style.top="-999999px",document.body.appendChild(r),r.focus(),r.select();const a=document.execCommand("copy");document.body.removeChild(r),a?this.showCopyFeedback(!0):this.showCopyFeedback(!1)}}catch(r){console.error("复制失败:",r),this.showCopyFeedback(!1)}}showCopyFeedback(e){const r=e?"复制成功!":"复制失败,请手动复制",a=document.createElement("div");a.className=`tiny-remoter-copy-feedback ${e?"success":"error"}`,a.textContent=r,document.body.appendChild(a),setTimeout(()=>a.classList.add("show"),10),setTimeout(()=>{a.classList.remove("show"),setTimeout(()=>{a.parentNode&&a.parentNode.removeChild(a)},300)},1500)}async showQRCode(){const r=await new Nv((this.options.qrCodeUrl||"")+this.sessionPrefix+this.options.sessionId,{}).toDataURL(),a=this.createModal("扫码前往智能遥控器",`
69
69
  <div style="text-align: center; padding: 32px;">
70
70
  <!-- 二维码容器 - 添加渐变背景和阴影效果 -->
71
71
  <div style="
@@ -466,40 +466,44 @@ Minimum version required to store current data is: `+s+`.
466
466
  color: white;
467
467
  }
468
468
  }
469
- `,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const QT=(t={})=>new WT(t);var Mv="vercel.ai.error",YT=Symbol.for(Mv),jv,XT=class ow extends Error{constructor({name:e,message:r,cause:a}){super(r),this[jv]=!0,this.name=e,this.cause=a}static isInstance(e){return ow.hasMarker(e,Mv)}static hasMarker(e,r){const a=Symbol.for(r);return e!=null&&typeof e=="object"&&a in e&&typeof e[a]=="boolean"&&e[a]===!0}};jv=YT;var $e=XT,Dv="AI_APICallError",Lv=`vercel.ai.error.${Dv}`,eC=Symbol.for(Lv),zv,Nt=class extends $e{constructor({message:t,url:e,requestBodyValues:r,statusCode:a,responseHeaders:n,responseBody:s,cause:o,isRetryable:i=a!=null&&(a===408||a===409||a===429||a>=500),data:l}){super({name:Dv,message:t,cause:o}),this[zv]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=n,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(t){return $e.hasMarker(t,Lv)}};zv=eC;var Uv="AI_EmptyResponseBodyError",qv=`vercel.ai.error.${Uv}`,tC=Symbol.for(qv),Fv,rC=class extends $e{constructor({message:t="Empty response body"}={}){super({name:Uv,message:t}),this[Fv]=!0}static isInstance(t){return $e.hasMarker(t,qv)}};Fv=tC;function Qa(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Zv="AI_InvalidArgumentError",Vv=`vercel.ai.error.${Zv}`,nC=Symbol.for(Vv),Hv,Bv=class extends $e{constructor({message:e,cause:r,argument:a}){super({name:Zv,message:e,cause:r}),this[Hv]=!0,this.argument=a}static isInstance(e){return $e.hasMarker(e,Vv)}};Hv=nC;var Jv="AI_InvalidPromptError",Gv=`vercel.ai.error.${Jv}`,aC=Symbol.for(Gv),Kv,ra=class extends $e{constructor({prompt:t,message:e,cause:r}){super({name:Jv,message:`Invalid prompt: ${e}`,cause:r}),this[Kv]=!0,this.prompt=t}static isInstance(t){return $e.hasMarker(t,Gv)}};Kv=aC;var Wv="AI_InvalidResponseDataError",Qv=`vercel.ai.error.${Wv}`,sC=Symbol.for(Qv),Yv,Ys=class extends $e{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Wv,message:e}),this[Yv]=!0,this.data=t}static isInstance(t){return $e.hasMarker(t,Qv)}};Yv=sC;var Xv="AI_JSONParseError",eg=`vercel.ai.error.${Xv}`,oC=Symbol.for(eg),tg,nl=class extends $e{constructor({text:t,cause:e}){super({name:Xv,message:`JSON parsing failed: Text: ${t}.
470
- Error message: ${Qa(e)}`,cause:e}),this[tg]=!0,this.text=t}static isInstance(t){return $e.hasMarker(t,eg)}};tg=oC;var rg="AI_LoadAPIKeyError",ng=`vercel.ai.error.${rg}`,iC=Symbol.for(ng),ag,al=class extends $e{constructor({message:t}){super({name:rg,message:t}),this[ag]=!0}static isInstance(t){return $e.hasMarker(t,ng)}};ag=iC;var sg="AI_NoSuchModelError",og=`vercel.ai.error.${sg}`,lC=Symbol.for(og),ig,xd=class extends $e{constructor({errorName:t=sg,modelId:e,modelType:r,message:a=`No such ${r}: ${e}`}){super({name:t,message:a}),this[ig]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return $e.hasMarker(t,og)}};ig=lC;var lg="AI_TooManyEmbeddingValuesForCallError",cg=`vercel.ai.error.${lg}`,cC=Symbol.for(cg),ug,uC=class extends $e{constructor(t){super({name:lg,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[ug]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return $e.hasMarker(t,cg)}};ug=cC;var dg="AI_TypeValidationError",pg=`vercel.ai.error.${dg}`,dC=Symbol.for(pg),fg,pC=class $p extends $e{constructor({value:e,cause:r}){super({name:dg,message:`Type validation failed: Value: ${JSON.stringify(e)}.
471
- Error message: ${Qa(r)}`,cause:r}),this[fg]=!0,this.value=e}static isInstance(e){return $e.hasMarker(e,pg)}static wrap({value:e,cause:r}){return $p.isInstance(r)&&r.value===e?r:new $p({value:e,cause:r})}};fg=dC;var Xs=pC,hg="AI_UnsupportedFunctionalityError",mg=`vercel.ai.error.${hg}`,fC=Symbol.for(mg),vg,Mr=class extends $e{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:hg,message:e}),this[vg]=!0,this.functionality=t}static isInstance(t){return $e.hasMarker(t,mg)}};vg=fC;function B(t,e,r){function a(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(t),e(i,l);for(const u in o.prototype)u in i||Object.defineProperty(i,u,{value:o.prototype[u].bind(i)});i._zod.constr=o,i._zod.def=l}const n=(r==null?void 0:r.Parent)??Object;class s extends n{}Object.defineProperty(s,"name",{value:t});function o(i){var l;const c=r!=null&&r.Parent?new s:this;a(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(o,"init",{value:a}),Object.defineProperty(o,Symbol.hasInstance,{value:i=>{var l,c;return r!=null&&r.Parent&&i instanceof r.Parent?!0:(c=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:c.has(t)}}),Object.defineProperty(o,"name",{value:t}),o}class eo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const gg={};function Dn(t){return gg}function yg(t){const e=Object.values(t).filter(a=>typeof a=="number");return Object.entries(t).filter(([a,n])=>e.indexOf(+a)===-1).map(([a,n])=>n)}function hC(t,e){return typeof e=="bigint"?e.toString():e}function Td(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Cd(t){return t==null}function Rd(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function mC(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}function Ge(t,e,r){Object.defineProperty(t,e,{get(){{const a=r();return t[e]=a,a}},set(a){Object.defineProperty(t,e,{value:a})},configurable:!0})}function sl(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function to(t){return JSON.stringify(t)}const _g=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function ol(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const vC=Td(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function il(t){if(ol(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(ol(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const gC=new Set(["string","number","symbol"]);function ro(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function na(t,e,r){const a=new t._zod.constr(e??t._zod.def);return(!e||r!=null&&r.parent)&&(a._zod.parent=t),a}function fe(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function yC(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const _C={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 wC(t,e){const r={},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&(r[n]=a.shape[n])}return na(t,{...t._zod.def,shape:r,checks:[]})}function bC(t,e){const r={...t._zod.def.shape},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&delete r[n]}return na(t,{...t._zod.def,shape:r,checks:[]})}function EC(t,e){if(!il(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const a={...t._zod.def.shape,...e};return sl(this,"shape",a),a},checks:[]};return na(t,r)}function SC(t,e){return na(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return sl(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function $C(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=t?new t({type:"optional",innerType:a[s]}):a[s])}else for(const s in a)n[s]=t?new t({type:"optional",innerType:a[s]}):a[s];return na(e,{...e._zod.def,shape:n,checks:[]})}function PC(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=new t({type:"nonoptional",innerType:a[s]}))}else for(const s in a)n[s]=new t({type:"nonoptional",innerType:a[s]});return na(e,{...e._zod.def,shape:n,checks:[]})}function no(t,e=0){var r;for(let a=e;a<t.issues.length;a++)if(((r=t.issues[a])==null?void 0:r.continue)!==!0)return!0;return!1}function aa(t,e){return e.map(r=>{var a;return(a=r).path??(a.path=[]),r.path.unshift(t),r})}function ll(t){return typeof t=="string"?t:t==null?void 0:t.message}function Ln(t,e,r){var n,s,o,i,l,c;const a={...t,path:t.path??[]};if(!t.message){const u=ll((o=(s=(n=t.inst)==null?void 0:n._zod.def)==null?void 0:s.error)==null?void 0:o.call(s,t))??ll((i=e==null?void 0:e.error)==null?void 0:i.call(e,t))??ll((l=r.customError)==null?void 0:l.call(r,t))??ll((c=r.localeError)==null?void 0:c.call(r,t))??"Invalid input";a.message=u}return delete a.inst,delete a.continue,e!=null&&e.reportInput||delete a.input,a}function Od(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function ao(...t){const[e,r,a]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:a}:{...e}}const wg=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,hC,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},bg=B("$ZodError",wg),Eg=B("$ZodError",wg,{Parent:Error});function kC(t,e=r=>r.message){const r={},a=[];for(const n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):a.push(e(n));return{formErrors:a,fieldErrors:r}}function IC(t,e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(i=>n({issues:i}));else if(o.code==="invalid_key")n({issues:o.issues});else if(o.code==="invalid_element")n({issues:o.issues});else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(o))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return n(t),a}const xC=t=>(e,r,a,n)=>{const s=a?Object.assign(a,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new eo;if(o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>Ln(l,s,Dn())));throw _g(i,n==null?void 0:n.callee),i}return o.value},TC=t=>async(e,r,a,n)=>{const s=a?Object.assign(a,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>Ln(l,s,Dn())));throw _g(i,n==null?void 0:n.callee),i}return o.value},Sg=t=>(e,r,a)=>{const n=a?{...a,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new eo;return s.issues.length?{success:!1,error:new(t??bg)(s.issues.map(o=>Ln(o,n,Dn())))}:{success:!0,data:s.value}},CC=Sg(Eg),$g=t=>async(e,r,a)=>{const n=a?Object.assign(a,{async:!0}):{async:!0};let s=e._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>Ln(o,n,Dn())))}:{success:!0,data:s.value}},RC=$g(Eg),OC=/^[cC][^\s-]{8,}$/,NC=/^[0-9a-z]+$/,AC=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,MC=/^[0-9a-vA-V]{20}$/,jC=/^[A-Za-z0-9]{27}$/,DC=/^[a-zA-Z0-9_-]{21}$/,LC=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,zC=/^([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})$/,Pg=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,UC=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,qC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function FC(){return new RegExp(qC,"u")}const ZC=/^(?:(?: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])$/,VC=/^(([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})$/,HC=/^((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])$/,BC=/^(([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])$/,JC=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kg=/^[A-Za-z0-9_-]*$/,GC=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,KC=/^\+(?:[0-9]){6,14}[0-9]$/,Ig="(?:(?:\\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])))",WC=new RegExp(`^${Ig}$`);function xg(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function QC(t){return new RegExp(`^${xg(t)}$`)}function YC(t){const e=xg({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const a=`${e}(?:${r.join("|")})`;return new RegExp(`^${Ig}T(?:${a})$`)}const XC=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},eR=/^\d+$/,tR=/^-?\d+(?:\.\d+)?/i,rR=/true|false/i,nR=/null/i,aR=/^[^A-Z]*$/,sR=/^[^a-z]*$/,nr=B("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Tg={number:"number",bigint:"bigint",object:"date"},Cg=B("$ZodCheckLessThan",(t,e)=>{nr.init(t,e);const r=Tg[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value<=e.value:a.value<e.value)||a.issues.push({origin:r,code:"too_big",maximum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Rg=B("$ZodCheckGreaterThan",(t,e)=>{nr.init(t,e);const r=Tg[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value>=e.value:a.value>e.value)||a.issues.push({origin:r,code:"too_small",minimum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),oR=B("$ZodCheckMultipleOf",(t,e)=>{nr.init(t,e),t._zod.onattach.push(r=>{var a;(a=r._zod.bag).multipleOf??(a.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):mC(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),iR=B("$ZodCheckNumberFormat",(t,e)=>{var o;nr.init(t,e),e.format=e.format||"float64";const r=(o=e.format)==null?void 0:o.includes("int"),a=r?"int":"number",[n,s]=_C[e.format];t._zod.onattach.push(i=>{const l=i._zod.bag;l.format=e.format,l.minimum=n,l.maximum=s,r&&(l.pattern=eR)}),t._zod.check=i=>{const l=i.value;if(r){if(!Number.isInteger(l)){i.issues.push({expected:a,format:e.format,code:"invalid_type",input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort});return}}l<n&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:t})}}),lR=B("$ZodCheckMaxLength",(t,e)=>{var r;nr.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!Cd(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(a._zod.bag.maximum=e.maximum)}),t._zod.check=a=>{const n=a.value;if(n.length<=e.maximum)return;const o=Od(n);a.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),cR=B("$ZodCheckMinLength",(t,e)=>{var r;nr.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!Cd(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(a._zod.bag.minimum=e.minimum)}),t._zod.check=a=>{const n=a.value;if(n.length>=e.minimum)return;const o=Od(n);a.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),uR=B("$ZodCheckLengthEquals",(t,e)=>{var r;nr.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!Cd(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=a=>{const n=a.value,s=n.length;if(s===e.length)return;const o=Od(n),i=s>e.length;a.issues.push({origin:o,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:a.value,inst:t,continue:!e.abort})}}),cl=B("$ZodCheckStringFormat",(t,e)=>{var r,a;nr.init(t,e),t._zod.onattach.push(n=>{const s=n._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(a=t._zod).check??(a.check=()=>{})}),dR=B("$ZodCheckRegex",(t,e)=>{cl.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),pR=B("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=aR),cl.init(t,e)}),fR=B("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=sR),cl.init(t,e)}),hR=B("$ZodCheckIncludes",(t,e)=>{nr.init(t,e);const r=ro(e.includes),a=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=a,t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(a)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),mR=B("$ZodCheckStartsWith",(t,e)=>{nr.init(t,e);const r=new RegExp(`^${ro(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.startsWith(e.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:a.value,inst:t,continue:!e.abort})}}),vR=B("$ZodCheckEndsWith",(t,e)=>{nr.init(t,e);const r=new RegExp(`.*${ro(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.endsWith(e.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:a.value,inst:t,continue:!e.abort})}}),gR=B("$ZodCheckOverwrite",(t,e)=>{nr.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class yR{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const a=e.split(`
469
+ `,document.head.appendChild(e)}destroy(){this.floatingBlock.parentNode&&this.floatingBlock.parentNode.removeChild(this.floatingBlock),this.dropdownMenu.parentNode&&this.dropdownMenu.parentNode.removeChild(this.dropdownMenu)}}const rC=(t={})=>new tC(t);var Dv="vercel.ai.error",nC=Symbol.for(Dv),Lv,aC=class mw extends Error{constructor({name:e,message:r,cause:a}){super(r),this[Lv]=!0,this.name=e,this.cause=a}static isInstance(e){return mw.hasMarker(e,Dv)}static hasMarker(e,r){const a=Symbol.for(r);return e!=null&&typeof e=="object"&&a in e&&typeof e[a]=="boolean"&&e[a]===!0}};Lv=nC;var Pe=aC,zv="AI_APICallError",Uv=`vercel.ai.error.${zv}`,sC=Symbol.for(Uv),qv,Xe=class extends Pe{constructor({message:t,url:e,requestBodyValues:r,statusCode:a,responseHeaders:n,responseBody:s,cause:o,isRetryable:i=a!=null&&(a===408||a===409||a===429||a>=500),data:l}){super({name:zv,message:t,cause:o}),this[qv]=!0,this.url=e,this.requestBodyValues=r,this.statusCode=a,this.responseHeaders=n,this.responseBody=s,this.isRetryable=i,this.data=l}static isInstance(t){return Pe.hasMarker(t,Uv)}};qv=sC;var Fv="AI_EmptyResponseBodyError",Zv=`vercel.ai.error.${Fv}`,oC=Symbol.for(Zv),Vv,Hv=class extends Pe{constructor({message:t="Empty response body"}={}){super({name:Fv,message:t}),this[Vv]=!0}static isInstance(t){return Pe.hasMarker(t,Zv)}};Vv=oC;function Ha(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Bv="AI_InvalidArgumentError",Jv=`vercel.ai.error.${Bv}`,iC=Symbol.for(Jv),Gv,yd=class extends Pe{constructor({message:e,cause:r,argument:a}){super({name:Bv,message:e,cause:r}),this[Gv]=!0,this.argument=a}static isInstance(e){return Pe.hasMarker(e,Jv)}};Gv=iC;var Kv="AI_InvalidPromptError",Wv=`vercel.ai.error.${Kv}`,lC=Symbol.for(Wv),Qv,Kn=class extends Pe{constructor({prompt:t,message:e,cause:r}){super({name:Kv,message:`Invalid prompt: ${e}`,cause:r}),this[Qv]=!0,this.prompt=t}static isInstance(t){return Pe.hasMarker(t,Wv)}};Qv=lC;var Yv="AI_InvalidResponseDataError",Xv=`vercel.ai.error.${Yv}`,cC=Symbol.for(Xv),eg,Js=class extends Pe{constructor({data:t,message:e=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Yv,message:e}),this[eg]=!0,this.data=t}static isInstance(t){return Pe.hasMarker(t,Xv)}};eg=cC;var tg="AI_JSONParseError",rg=`vercel.ai.error.${tg}`,uC=Symbol.for(rg),ng,xn=class extends Pe{constructor({text:t,cause:e}){super({name:tg,message:`JSON parsing failed: Text: ${t}.
470
+ Error message: ${Ha(e)}`,cause:e}),this[ng]=!0,this.text=t}static isInstance(t){return Pe.hasMarker(t,rg)}};ng=uC;var ag="AI_LoadAPIKeyError",sg=`vercel.ai.error.${ag}`,dC=Symbol.for(sg),og,Ji=class extends Pe{constructor({message:t}){super({name:ag,message:t}),this[og]=!0}static isInstance(t){return Pe.hasMarker(t,sg)}};og=dC;var ig="AI_NoSuchModelError",lg=`vercel.ai.error.${ig}`,fC=Symbol.for(lg),cg,_d=class extends Pe{constructor({errorName:t=ig,modelId:e,modelType:r,message:a=`No such ${r}: ${e}`}){super({name:t,message:a}),this[cg]=!0,this.modelId=e,this.modelType=r}static isInstance(t){return Pe.hasMarker(t,lg)}};cg=fC;var ug="AI_TooManyEmbeddingValuesForCallError",dg=`vercel.ai.error.${ug}`,pC=Symbol.for(dg),fg,hC=class extends Pe{constructor(t){super({name:ug,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[fg]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return Pe.hasMarker(t,dg)}};fg=pC;var pg="AI_TypeValidationError",hg=`vercel.ai.error.${pg}`,mC=Symbol.for(hg),mg,vC=class Pf extends Pe{constructor({value:e,cause:r}){super({name:pg,message:`Type validation failed: Value: ${JSON.stringify(e)}.
471
+ Error message: ${Ha(r)}`,cause:r}),this[mg]=!0,this.value=e}static isInstance(e){return Pe.hasMarker(e,hg)}static wrap({value:e,cause:r}){return Pf.isInstance(r)&&r.value===e?r:new Pf({value:e,cause:r})}};mg=mC;var Br=vC,vg="AI_UnsupportedFunctionalityError",gg=`vercel.ai.error.${vg}`,gC=Symbol.for(gg),yg,fr=class extends Pe{constructor({functionality:t,message:e=`'${t}' functionality not supported.`}){super({name:vg,message:e}),this[yg]=!0,this.functionality=t}static isInstance(t){return Pe.hasMarker(t,gg)}};yg=gC;class _g extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}}function wd(t){}function yC(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:e=wd,onError:r=wd,onRetry:a=wd,onComment:n}=t;let s="",o=!0,i,l="",c="";function u(v){const m=o?v.replace(/^\xEF\xBB\xBF/,""):v,[p,y]=_C(`${s}${m}`);for(const _ of p)h(_);s=y,o=!1}function h(v){if(v===""){d();return}if(v.startsWith(":")){n&&n(v.slice(v.startsWith(": ")?2:1));return}const m=v.indexOf(":");if(m!==-1){const p=v.slice(0,m),y=v[m+1]===" "?2:1,_=v.slice(m+y);g(p,_,v);return}g(v,"",v)}function g(v,m,p){switch(v){case"event":c=m;break;case"data":l=`${l}${m}
472
+ `;break;case"id":i=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?a(parseInt(m,10)):r(new _g(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:p}));break;default:r(new _g(`Unknown field "${v.length>20?`${v.slice(0,20)}…`:v}"`,{type:"unknown-field",field:v,value:m,line:p}));break}}function d(){l.length>0&&e({id:i,event:c||void 0,data:l.endsWith(`
473
+ `)?l.slice(0,-1):l}),i=void 0,l="",c=""}function f(v={}){s&&v.consume&&h(s),o=!0,i=void 0,l="",c="",s=""}return{feed:u,reset:f}}function _C(t){const e=[];let r="",a=0;for(;a<t.length;){const n=t.indexOf("\r",a),s=t.indexOf(`
474
+ `,a);let o=-1;if(n!==-1&&s!==-1?o=Math.min(n,s):n!==-1?n===t.length-1?o=-1:o=n:s!==-1&&(o=s),o===-1){r=t.slice(a);break}else{const i=t.slice(a,o);e.push(i),a=o+1,t[a-1]==="\r"&&t[a]===`
475
+ `&&a++}}return[e,r]}class wC extends TransformStream{constructor({onError:e,onRetry:r,onComment:a}={}){let n;super({start(s){n=yC({onEvent:o=>{s.enqueue(o)},onError(o){e==="terminate"?s.error(o):typeof e=="function"&&e(o)},onRetry:r,onComment:a})},transform(s){n.feed(s)}})}}function B(t,e,r){function a(i,l){var c;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(c=i._zod).traits??(c.traits=new Set),i._zod.traits.add(t),e(i,l);for(const u in o.prototype)u in i||Object.defineProperty(i,u,{value:o.prototype[u].bind(i)});i._zod.constr=o,i._zod.def=l}const n=(r==null?void 0:r.Parent)??Object;class s extends n{}Object.defineProperty(s,"name",{value:t});function o(i){var l;const c=r!=null&&r.Parent?new s:this;a(c,i),(l=c._zod).deferred??(l.deferred=[]);for(const u of c._zod.deferred)u();return c}return Object.defineProperty(o,"init",{value:a}),Object.defineProperty(o,Symbol.hasInstance,{value:i=>{var l,c;return r!=null&&r.Parent&&i instanceof r.Parent?!0:(c=(l=i==null?void 0:i._zod)==null?void 0:l.traits)==null?void 0:c.has(t)}}),Object.defineProperty(o,"name",{value:t}),o}class Gs extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const wg={};function kn(t){return wg}function bg(t){const e=Object.values(t).filter(a=>typeof a=="number");return Object.entries(t).filter(([a,n])=>e.indexOf(+a)===-1).map(([a,n])=>n)}function bC(t,e){return typeof e=="bigint"?e.toString():e}function bd(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function Ed(t){return t==null}function $d(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function EC(t,e){const r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,s=Number.parseInt(t.toFixed(n).replace(".","")),o=Number.parseInt(e.toFixed(n).replace(".",""));return s%o/10**n}function Je(t,e,r){Object.defineProperty(t,e,{get(){{const a=r();return t[e]=a,a}},set(a){Object.defineProperty(t,e,{value:a})},configurable:!0})}function Gi(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ks(t){return JSON.stringify(t)}const Eg=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ki(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const $C=bd(()=>{var t;if(typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Wi(t){if(Ki(t)===!1)return!1;const e=t.constructor;if(e===void 0)return!0;const r=e.prototype;return!(Ki(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}const SC=new Set(["string","number","symbol"]);function Ws(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Wn(t,e,r){const a=new t._zod.constr(e??t._zod.def);return(!e||r!=null&&r.parent)&&(a._zod.parent=t),a}function de(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function PC(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const TC={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 xC(t,e){const r={},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&(r[n]=a.shape[n])}return Wn(t,{...t._zod.def,shape:r,checks:[]})}function kC(t,e){const r={...t._zod.def.shape},a=t._zod.def;for(const n in e){if(!(n in a.shape))throw new Error(`Unrecognized key: "${n}"`);e[n]&&delete r[n]}return Wn(t,{...t._zod.def,shape:r,checks:[]})}function IC(t,e){if(!Wi(e))throw new Error("Invalid input to extend: expected a plain object");const r={...t._zod.def,get shape(){const a={...t._zod.def.shape,...e};return Gi(this,"shape",a),a},checks:[]};return Wn(t,r)}function CC(t,e){return Wn(t,{...t._zod.def,get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return Gi(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function RC(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in a))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=t?new t({type:"optional",innerType:a[s]}):a[s])}else for(const s in a)n[s]=t?new t({type:"optional",innerType:a[s]}):a[s];return Wn(e,{...e._zod.def,shape:n,checks:[]})}function OC(t,e,r){const a=e._zod.def.shape,n={...a};if(r)for(const s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(n[s]=new t({type:"nonoptional",innerType:a[s]}))}else for(const s in a)n[s]=new t({type:"nonoptional",innerType:a[s]});return Wn(e,{...e._zod.def,shape:n,checks:[]})}function Qs(t,e=0){var r;for(let a=e;a<t.issues.length;a++)if(((r=t.issues[a])==null?void 0:r.continue)!==!0)return!0;return!1}function Qn(t,e){return e.map(r=>{var a;return(a=r).path??(a.path=[]),r.path.unshift(t),r})}function Qi(t){return typeof t=="string"?t:t==null?void 0:t.message}function In(t,e,r){var n,s,o,i,l,c;const a={...t,path:t.path??[]};if(!t.message){const u=Qi((o=(s=(n=t.inst)==null?void 0:n._zod.def)==null?void 0:s.error)==null?void 0:o.call(s,t))??Qi((i=e==null?void 0:e.error)==null?void 0:i.call(e,t))??Qi((l=r.customError)==null?void 0:l.call(r,t))??Qi((c=r.localeError)==null?void 0:c.call(r,t))??"Invalid input";a.message=u}return delete a.inst,delete a.continue,e!=null&&e.reportInput||delete a.input,a}function Sd(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ys(...t){const[e,r,a]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:a}:{...e}}const $g=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,bC,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Sg=B("$ZodError",$g),Pg=B("$ZodError",$g,{Parent:Error});function AC(t,e=r=>r.message){const r={},a=[];for(const n of t.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(e(n))):a.push(e(n));return{formErrors:a,fieldErrors:r}}function NC(t,e){const r=e||function(s){return s.message},a={_errors:[]},n=s=>{for(const o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(i=>n({issues:i}));else if(o.code==="invalid_key")n({issues:o.issues});else if(o.code==="invalid_element")n({issues:o.issues});else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(i[c]=i[c]||{_errors:[]},i[c]._errors.push(r(o))):i[c]=i[c]||{_errors:[]},i=i[c],l++}}};return n(t),a}const MC=t=>(e,r,a,n)=>{const s=a?Object.assign(a,{async:!1}):{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Gs;if(o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>In(l,s,kn())));throw Eg(i,n==null?void 0:n.callee),i}return o.value},jC=t=>async(e,r,a,n)=>{const s=a?Object.assign(a,{async:!0}):{async:!0};let o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){const i=new((n==null?void 0:n.Err)??t)(o.issues.map(l=>In(l,s,kn())));throw Eg(i,n==null?void 0:n.callee),i}return o.value},Tg=t=>(e,r,a)=>{const n=a?{...a,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},n);if(s instanceof Promise)throw new Gs;return s.issues.length?{success:!1,error:new(t??Sg)(s.issues.map(o=>In(o,n,kn())))}:{success:!0,data:s.value}},DC=Tg(Pg),xg=t=>async(e,r,a)=>{const n=a?Object.assign(a,{async:!0}):{async:!0};let s=e._zod.run({value:r,issues:[]},n);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(o=>In(o,n,kn())))}:{success:!0,data:s.value}},LC=xg(Pg),zC=/^[cC][^\s-]{8,}$/,UC=/^[0-9a-z]+$/,qC=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,FC=/^[0-9a-vA-V]{20}$/,ZC=/^[A-Za-z0-9]{27}$/,VC=/^[a-zA-Z0-9_-]{21}$/,HC=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,BC=/^([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})$/,kg=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,JC=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,GC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function KC(){return new RegExp(GC,"u")}const WC=/^(?:(?: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])$/,QC=/^(([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})$/,YC=/^((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])$/,XC=/^(([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])$/,eR=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ig=/^[A-Za-z0-9_-]*$/,tR=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,rR=/^\+(?:[0-9]){6,14}[0-9]$/,Cg="(?:(?:\\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])))",nR=new RegExp(`^${Cg}$`);function Rg(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function aR(t){return new RegExp(`^${Rg(t)}$`)}function sR(t){const e=Rg({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");const a=`${e}(?:${r.join("|")})`;return new RegExp(`^${Cg}T(?:${a})$`)}const oR=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},iR=/^\d+$/,lR=/^-?\d+(?:\.\d+)?/i,cR=/true|false/i,uR=/null/i,dR=/^[^A-Z]*$/,fR=/^[^a-z]*$/,Wt=B("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Og={number:"number",bigint:"bigint",object:"date"},Ag=B("$ZodCheckLessThan",(t,e)=>{Wt.init(t,e);const r=Og[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?n.maximum=e.value:n.exclusiveMaximum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value<=e.value:a.value<e.value)||a.issues.push({origin:r,code:"too_big",maximum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ng=B("$ZodCheckGreaterThan",(t,e)=>{Wt.init(t,e);const r=Og[typeof e.value];t._zod.onattach.push(a=>{const n=a._zod.bag,s=(e.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?n.minimum=e.value:n.exclusiveMinimum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value>=e.value:a.value>e.value)||a.issues.push({origin:r,code:"too_small",minimum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),pR=B("$ZodCheckMultipleOf",(t,e)=>{Wt.init(t,e),t._zod.onattach.push(r=>{var a;(a=r._zod.bag).multipleOf??(a.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):EC(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),hR=B("$ZodCheckNumberFormat",(t,e)=>{var o;Wt.init(t,e),e.format=e.format||"float64";const r=(o=e.format)==null?void 0:o.includes("int"),a=r?"int":"number",[n,s]=TC[e.format];t._zod.onattach.push(i=>{const l=i._zod.bag;l.format=e.format,l.minimum=n,l.maximum=s,r&&(l.pattern=iR)}),t._zod.check=i=>{const l=i.value;if(r){if(!Number.isInteger(l)){i.issues.push({expected:a,format:e.format,code:"invalid_type",input:l,inst:t});return}if(!Number.isSafeInteger(l)){l>0?i.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort}):i.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort});return}}l<n&&i.issues.push({origin:"number",input:l,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),l>s&&i.issues.push({origin:"number",input:l,code:"too_big",maximum:s,inst:t})}}),mR=B("$ZodCheckMaxLength",(t,e)=>{var r;Wt.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!Ed(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(a._zod.bag.maximum=e.maximum)}),t._zod.check=a=>{const n=a.value;if(n.length<=e.maximum)return;const o=Sd(n);a.issues.push({origin:o,code:"too_big",maximum:e.maximum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),vR=B("$ZodCheckMinLength",(t,e)=>{var r;Wt.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!Ed(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(a._zod.bag.minimum=e.minimum)}),t._zod.check=a=>{const n=a.value;if(n.length>=e.minimum)return;const o=Sd(n);a.issues.push({origin:o,code:"too_small",minimum:e.minimum,inclusive:!0,input:n,inst:t,continue:!e.abort})}}),gR=B("$ZodCheckLengthEquals",(t,e)=>{var r;Wt.init(t,e),(r=t._zod.def).when??(r.when=a=>{const n=a.value;return!Ed(n)&&n.length!==void 0}),t._zod.onattach.push(a=>{const n=a._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=a=>{const n=a.value,s=n.length;if(s===e.length)return;const o=Sd(n),i=s>e.length;a.issues.push({origin:o,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:a.value,inst:t,continue:!e.abort})}}),Yi=B("$ZodCheckStringFormat",(t,e)=>{var r,a;Wt.init(t,e),t._zod.onattach.push(n=>{const s=n._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(a=t._zod).check??(a.check=()=>{})}),yR=B("$ZodCheckRegex",(t,e)=>{Yi.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),_R=B("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=dR),Yi.init(t,e)}),wR=B("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=fR),Yi.init(t,e)}),bR=B("$ZodCheckIncludes",(t,e)=>{Wt.init(t,e);const r=Ws(e.includes),a=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=a,t._zod.onattach.push(n=>{const s=n._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(a)}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),ER=B("$ZodCheckStartsWith",(t,e)=>{Wt.init(t,e);const r=new RegExp(`^${Ws(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.startsWith(e.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:a.value,inst:t,continue:!e.abort})}}),$R=B("$ZodCheckEndsWith",(t,e)=>{Wt.init(t,e);const r=new RegExp(`.*${Ws(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),t._zod.check=a=>{a.value.endsWith(e.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:a.value,inst:t,continue:!e.abort})}}),SR=B("$ZodCheckOverwrite",(t,e)=>{Wt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class PR{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const a=e.split(`
472
476
  `).filter(o=>o),n=Math.min(...a.map(o=>o.length-o.trimStart().length)),s=a.map(o=>o.slice(n)).map(o=>" ".repeat(this.indent*2)+o);for(const o of s)this.content.push(o)}compile(){const e=Function,r=this==null?void 0:this.args,n=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new e(...r,n.join(`
473
- `))}}const _R={major:4,minor:0,patch:0},et=B("$ZodType",(t,e)=>{var n;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=_R;const a=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&a.unshift(t);for(const s of a)for(const o of s._zod.onattach)o(t);if(a.length===0)(r=t._zod).deferred??(r.deferred=[]),(n=t._zod.deferred)==null||n.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,i,l)=>{let c=no(o),u;for(const f of i){if(f._zod.def.when){if(!f._zod.def.when(o))continue}else if(c)continue;const g=o.issues.length,d=f._zod.check(o);if(d instanceof Promise&&(l==null?void 0:l.async)===!1)throw new eo;if(u||d instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await d,o.issues.length!==g&&(c||(c=no(o,g)))});else{if(o.issues.length===g)continue;c||(c=no(o,g))}}return u?u.then(()=>o):o};t._zod.run=(o,i)=>{const l=t._zod.parse(o,i);if(l instanceof Promise){if(i.async===!1)throw new eo;return l.then(c=>s(c,a,i))}return s(l,a,i)}}t["~standard"]={validate:s=>{var o;try{const i=CC(t,s);return i.success?{value:i.data}:{issues:(o=i.error)==null?void 0:o.issues}}catch{return RC(t,s).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),Nd=B("$ZodString",(t,e)=>{var r;et.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??XC(t._zod.bag),t._zod.parse=(a,n)=>{if(e.coerce)try{a.value=String(a.value)}catch{}return typeof a.value=="string"||a.issues.push({expected:"string",code:"invalid_type",input:a.value,inst:t}),a}}),ct=B("$ZodStringFormat",(t,e)=>{cl.init(t,e),Nd.init(t,e)}),wR=B("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=zC),ct.init(t,e)}),bR=B("$ZodUUID",(t,e)=>{if(e.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(a===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Pg(a))}else e.pattern??(e.pattern=Pg());ct.init(t,e)}),ER=B("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=UC),ct.init(t,e)}),SR=B("$ZodURL",(t,e)=>{ct.init(t,e),t._zod.check=r=>{try{const a=r.value,n=new URL(a),s=n.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:GC.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!a.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:t,continue:!e.abort})}}}),$R=B("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=FC()),ct.init(t,e)}),PR=B("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=DC),ct.init(t,e)}),kR=B("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=OC),ct.init(t,e)}),IR=B("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=NC),ct.init(t,e)}),xR=B("$ZodULID",(t,e)=>{e.pattern??(e.pattern=AC),ct.init(t,e)}),TR=B("$ZodXID",(t,e)=>{e.pattern??(e.pattern=MC),ct.init(t,e)}),CR=B("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=jC),ct.init(t,e)}),RR=B("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=YC(e)),ct.init(t,e)}),OR=B("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=WC),ct.init(t,e)}),NR=B("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=QC(e)),ct.init(t,e)}),AR=B("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=LC),ct.init(t,e)}),MR=B("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ZC),ct.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv4"})}),jR=B("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=VC),ct.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),DR=B("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=HC),ct.init(t,e)}),LR=B("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=BC),ct.init(t,e),t._zod.check=r=>{const[a,n]=r.value.split("/");try{if(!n)throw new Error;const s=Number(n);if(`${s}`!==n)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Og(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const zR=B("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=JC),ct.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Og(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function UR(t){if(!kg.test(t))return!1;const e=t.replace(/[-_]/g,a=>a==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Og(r)}const qR=B("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=kg),ct.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{UR(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),FR=B("$ZodE164",(t,e)=>{e.pattern??(e.pattern=KC),ct.init(t,e)});function ZR(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[a]=r;if(!a)return!1;const n=JSON.parse(atob(a));return!("typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}const VR=B("$ZodJWT",(t,e)=>{ct.init(t,e),t._zod.check=r=>{ZR(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ng=B("$ZodNumber",(t,e)=>{et.init(t,e),t._zod.pattern=t._zod.bag.pattern??tR,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;const s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...s?{received:s}:{}}),r}}),HR=B("$ZodNumber",(t,e)=>{iR.init(t,e),Ng.init(t,e)}),BR=B("$ZodBoolean",(t,e)=>{et.init(t,e),t._zod.pattern=rR,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=!!r.value}catch{}const n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),JR=B("$ZodNull",(t,e)=>{et.init(t,e),t._zod.pattern=nR,t._zod.values=new Set([null]),t._zod.parse=(r,a)=>{const n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),GR=B("$ZodAny",(t,e)=>{et.init(t,e),t._zod.parse=r=>r}),KR=B("$ZodUnknown",(t,e)=>{et.init(t,e),t._zod.parse=r=>r}),WR=B("$ZodNever",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Ag(t,e,r){t.issues.length&&e.issues.push(...aa(r,t.issues)),e.value[r]=t.value}const QR=B("$ZodArray",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);const s=[];for(let o=0;o<n.length;o++){const i=n[o],l=e.element._zod.run({value:i,issues:[]},a);l instanceof Promise?s.push(l.then(c=>Ag(c,r,o))):Ag(l,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function ul(t,e,r){t.issues.length&&e.issues.push(...aa(r,t.issues)),e.value[r]=t.value}function Mg(t,e,r,a){t.issues.length?a[r]===void 0?r in a?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...aa(r,t.issues)):t.value===void 0?r in a&&(e.value[r]=void 0):e.value[r]=t.value}const YR=B("$ZodObject",(t,e)=>{et.init(t,e);const r=Td(()=>{const f=Object.keys(e.shape);for(const d of f)if(!(e.shape[d]instanceof et))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const g=yC(e.shape);return{shape:e.shape,keys:f,keySet:new Set(f),numKeys:f.length,optionalKeys:new Set(g)}});Ge(t._zod,"propValues",()=>{const f=e.shape,g={};for(const d in f){const h=f[d]._zod;if(h.values){g[d]??(g[d]=new Set);for(const v of h.values)g[d].add(v)}}return g});const a=f=>{const g=new yR(["shape","payload","ctx"]),d=r.value,h=_=>{const w=to(_);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};g.write("const input = payload.value;");const v=Object.create(null);let m=0;for(const _ of d.keys)v[_]=`key_${m++}`;g.write("const newResult = {}");for(const _ of d.keys)if(d.optionalKeys.has(_)){const w=v[_];g.write(`const ${w} = ${h(_)};`);const b=to(_);g.write(`
474
- if (${w}.issues.length) {
475
- if (input[${b}] === undefined) {
476
- if (${b} in input) {
477
- newResult[${b}] = undefined;
477
+ `))}}const TR={major:4,minor:0,patch:0},et=B("$ZodType",(t,e)=>{var n;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=TR;const a=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&a.unshift(t);for(const s of a)for(const o of s._zod.onattach)o(t);if(a.length===0)(r=t._zod).deferred??(r.deferred=[]),(n=t._zod.deferred)==null||n.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,i,l)=>{let c=Qs(o),u;for(const h of i){if(h._zod.def.when){if(!h._zod.def.when(o))continue}else if(c)continue;const g=o.issues.length,d=h._zod.check(o);if(d instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Gs;if(u||d instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await d,o.issues.length!==g&&(c||(c=Qs(o,g)))});else{if(o.issues.length===g)continue;c||(c=Qs(o,g))}}return u?u.then(()=>o):o};t._zod.run=(o,i)=>{const l=t._zod.parse(o,i);if(l instanceof Promise){if(i.async===!1)throw new Gs;return l.then(c=>s(c,a,i))}return s(l,a,i)}}t["~standard"]={validate:s=>{var o;try{const i=DC(t,s);return i.success?{value:i.data}:{issues:(o=i.error)==null?void 0:o.issues}}catch{return LC(t,s).then(l=>{var c;return l.success?{value:l.data}:{issues:(c=l.error)==null?void 0:c.issues}})}},vendor:"zod",version:1}}),Pd=B("$ZodString",(t,e)=>{var r;et.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??oR(t._zod.bag),t._zod.parse=(a,n)=>{if(e.coerce)try{a.value=String(a.value)}catch{}return typeof a.value=="string"||a.issues.push({expected:"string",code:"invalid_type",input:a.value,inst:t}),a}}),ct=B("$ZodStringFormat",(t,e)=>{Yi.init(t,e),Pd.init(t,e)}),xR=B("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=BC),ct.init(t,e)}),kR=B("$ZodUUID",(t,e)=>{if(e.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(a===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=kg(a))}else e.pattern??(e.pattern=kg());ct.init(t,e)}),IR=B("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=JC),ct.init(t,e)}),CR=B("$ZodURL",(t,e)=>{ct.init(t,e),t._zod.check=r=>{try{const a=r.value,n=new URL(a),s=n.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:tR.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!a.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:t,continue:!e.abort})}}}),RR=B("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=KC()),ct.init(t,e)}),OR=B("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=VC),ct.init(t,e)}),AR=B("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=zC),ct.init(t,e)}),NR=B("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=UC),ct.init(t,e)}),MR=B("$ZodULID",(t,e)=>{e.pattern??(e.pattern=qC),ct.init(t,e)}),jR=B("$ZodXID",(t,e)=>{e.pattern??(e.pattern=FC),ct.init(t,e)}),DR=B("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=ZC),ct.init(t,e)}),LR=B("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=sR(e)),ct.init(t,e)}),zR=B("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=nR),ct.init(t,e)}),UR=B("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=aR(e)),ct.init(t,e)}),qR=B("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=HC),ct.init(t,e)}),FR=B("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=WC),ct.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv4"})}),ZR=B("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=QC),ct.init(t,e),t._zod.onattach.push(r=>{const a=r._zod.bag;a.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),VR=B("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=YC),ct.init(t,e)}),HR=B("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=XC),ct.init(t,e),t._zod.check=r=>{const[a,n]=r.value.split("/");try{if(!n)throw new Error;const s=Number(n);if(`${s}`!==n)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${a}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Mg(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const BR=B("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=eR),ct.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Mg(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function JR(t){if(!Ig.test(t))return!1;const e=t.replace(/[-_]/g,a=>a==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Mg(r)}const GR=B("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ig),ct.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{JR(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),KR=B("$ZodE164",(t,e)=>{e.pattern??(e.pattern=rR),ct.init(t,e)});function WR(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[a]=r;if(!a)return!1;const n=JSON.parse(atob(a));return!("typ"in n&&(n==null?void 0:n.typ)!=="JWT"||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}}const QR=B("$ZodJWT",(t,e)=>{ct.init(t,e),t._zod.check=r=>{WR(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),jg=B("$ZodNumber",(t,e)=>{et.init(t,e),t._zod.pattern=t._zod.bag.pattern??lR,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;const s=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...s?{received:s}:{}}),r}}),YR=B("$ZodNumber",(t,e)=>{hR.init(t,e),jg.init(t,e)}),XR=B("$ZodBoolean",(t,e)=>{et.init(t,e),t._zod.pattern=cR,t._zod.parse=(r,a)=>{if(e.coerce)try{r.value=!!r.value}catch{}const n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:t}),r}}),eO=B("$ZodNull",(t,e)=>{et.init(t,e),t._zod.pattern=uR,t._zod.values=new Set([null]),t._zod.parse=(r,a)=>{const n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:t}),r}}),tO=B("$ZodAny",(t,e)=>{et.init(t,e),t._zod.parse=r=>r}),rO=B("$ZodUnknown",(t,e)=>{et.init(t,e),t._zod.parse=r=>r}),nO=B("$ZodNever",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Dg(t,e,r){t.issues.length&&e.issues.push(...Qn(r,t.issues)),e.value[r]=t.value}const aO=B("$ZodArray",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);const s=[];for(let o=0;o<n.length;o++){const i=n[o],l=e.element._zod.run({value:i,issues:[]},a);l instanceof Promise?s.push(l.then(c=>Dg(c,r,o))):Dg(l,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function Xi(t,e,r){t.issues.length&&e.issues.push(...Qn(r,t.issues)),e.value[r]=t.value}function Lg(t,e,r,a){t.issues.length?a[r]===void 0?r in a?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Qn(r,t.issues)):t.value===void 0?r in a&&(e.value[r]=void 0):e.value[r]=t.value}const sO=B("$ZodObject",(t,e)=>{et.init(t,e);const r=bd(()=>{const h=Object.keys(e.shape);for(const d of h)if(!(e.shape[d]instanceof et))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);const g=PC(e.shape);return{shape:e.shape,keys:h,keySet:new Set(h),numKeys:h.length,optionalKeys:new Set(g)}});Je(t._zod,"propValues",()=>{const h=e.shape,g={};for(const d in h){const f=h[d]._zod;if(f.values){g[d]??(g[d]=new Set);for(const v of f.values)g[d].add(v)}}return g});const a=h=>{const g=new PR(["shape","payload","ctx"]),d=r.value,f=y=>{const _=Ks(y);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};g.write("const input = payload.value;");const v=Object.create(null);let m=0;for(const y of d.keys)v[y]=`key_${m++}`;g.write("const newResult = {}");for(const y of d.keys)if(d.optionalKeys.has(y)){const _=v[y];g.write(`const ${_} = ${f(y)};`);const w=Ks(y);g.write(`
478
+ if (${_}.issues.length) {
479
+ if (input[${w}] === undefined) {
480
+ if (${w} in input) {
481
+ newResult[${w}] = undefined;
478
482
  }
479
483
  } else {
480
484
  payload.issues = payload.issues.concat(
481
- ${w}.issues.map((iss) => ({
485
+ ${_}.issues.map((iss) => ({
482
486
  ...iss,
483
- path: iss.path ? [${b}, ...iss.path] : [${b}],
487
+ path: iss.path ? [${w}, ...iss.path] : [${w}],
484
488
  }))
485
489
  );
486
490
  }
487
- } else if (${w}.value === undefined) {
488
- if (${b} in input) newResult[${b}] = undefined;
491
+ } else if (${_}.value === undefined) {
492
+ if (${w} in input) newResult[${w}] = undefined;
489
493
  } else {
490
- newResult[${b}] = ${w}.value;
494
+ newResult[${w}] = ${_}.value;
491
495
  }
492
- `)}else{const w=v[_];g.write(`const ${w} = ${h(_)};`),g.write(`
493
- if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
496
+ `)}else{const _=v[y];g.write(`const ${_} = ${f(y)};`),g.write(`
497
+ if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
494
498
  ...iss,
495
- path: iss.path ? [${to(_)}, ...iss.path] : [${to(_)}]
496
- })));`),g.write(`newResult[${to(_)}] = ${w}.value`)}g.write("payload.value = newResult;"),g.write("return payload;");const p=g.compile();return(_,w)=>p(f,_,w)};let n;const s=ol,o=!gg.jitless,l=o&&vC.value,c=e.catchall;let u;t._zod.parse=(f,g)=>{u??(u=r.value);const d=f.value;if(!s(d))return f.issues.push({expected:"object",code:"invalid_type",input:d,inst:t}),f;const h=[];if(o&&l&&(g==null?void 0:g.async)===!1&&g.jitless!==!0)n||(n=a(e.shape)),f=n(f,g);else{f.value={};const w=u.shape;for(const b of u.keys){const S=w[b],I=S._zod.run({value:d[b],issues:[]},g),k=S._zod.optin==="optional"&&S._zod.optout==="optional";I instanceof Promise?h.push(I.then(A=>k?Mg(A,f,b,d):ul(A,f,b))):k?Mg(I,f,b,d):ul(I,f,b)}}if(!c)return h.length?Promise.all(h).then(()=>f):f;const v=[],m=u.keySet,p=c._zod,_=p.def.type;for(const w of Object.keys(d)){if(m.has(w))continue;if(_==="never"){v.push(w);continue}const b=p.run({value:d[w],issues:[]},g);b instanceof Promise?h.push(b.then(S=>ul(S,f,w))):ul(b,f,w)}return v.length&&f.issues.push({code:"unrecognized_keys",keys:v,input:d,inst:t}),h.length?Promise.all(h).then(()=>f):f}});function jg(t,e,r,a){for(const n of t)if(n.issues.length===0)return e.value=n.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(n=>n.issues.map(s=>Ln(s,a,Dn())))}),e}const Dg=B("$ZodUnion",(t,e)=>{et.init(t,e),Ge(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ge(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ge(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ge(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>Rd(a.source)).join("|")})$`)}}),t._zod.parse=(r,a)=>{let n=!1;const s=[];for(const o of e.options){const i=o._zod.run({value:r.value,issues:[]},a);if(i instanceof Promise)s.push(i),n=!0;else{if(i.issues.length===0)return i;s.push(i)}}return n?Promise.all(s).then(o=>jg(o,r,t,a)):jg(s,r,t,a)}}),XR=B("$ZodDiscriminatedUnion",(t,e)=>{Dg.init(t,e);const r=t._zod.parse;Ge(t._zod,"propValues",()=>{const n={};for(const s of e.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const[i,l]of Object.entries(o)){n[i]||(n[i]=new Set);for(const c of l)n[i].add(c)}}return n});const a=Td(()=>{const n=e.options,s=new Map;for(const o of n){const i=o._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,o)}}return s});t._zod.parse=(n,s)=>{const o=n.value;if(!ol(o))return n.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),n;const i=a.value.get(o==null?void 0:o[e.discriminator]);return i?i._zod.run(n,s):e.unionFallback?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),n)}}),eO=B("$ZodIntersection",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=r.value,s=e.left._zod.run({value:n,issues:[]},a),o=e.right._zod.run({value:n,issues:[]},a);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([l,c])=>Lg(r,l,c)):Lg(r,s,o)}});function Ad(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(il(t)&&il(e)){const r=Object.keys(e),a=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(const s of a){const o=Ad(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};n[s]=o.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let a=0;a<t.length;a++){const n=t[a],s=e[a],o=Ad(n,s);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Lg(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),no(t))return t;const a=Ad(e.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return t.value=a.data,t}const tO=B("$ZodRecord",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!il(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),r;const s=[];if(e.keyType._zod.values){const o=e.keyType._zod.values;r.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=e.valueType._zod.run({value:n[l],issues:[]},a);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...aa(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...aa(l,c.issues)),r.value[l]=c.value)}let i;for(const l in n)o.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:i})}else{r.value={};for(const o of Reflect.ownKeys(n)){if(o==="__proto__")continue;const i=e.keyType._zod.run({value:o,issues:[]},a);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=>Ln(c,a,Dn())),input:o,path:[o],inst:t}),r.value[i.value]=i.value;continue}const l=e.valueType._zod.run({value:n[o],issues:[]},a);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...aa(o,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...aa(o,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),rO=B("$ZodEnum",(t,e)=>{et.init(t,e);const r=yg(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(a=>gC.has(typeof a)).map(a=>typeof a=="string"?ro(a):a.toString()).join("|")})$`),t._zod.parse=(a,n)=>{const s=a.value;return t._zod.values.has(s)||a.issues.push({code:"invalid_value",values:r,input:s,inst:t}),a}}),nO=B("$ZodLiteral",(t,e)=>{et.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?ro(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,a)=>{const n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:e.values,input:n,inst:t}),r}}),aO=B("$ZodTransform",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=e.transform(r.value,r);if(a.async)return(n instanceof Promise?n:Promise.resolve(n)).then(o=>(r.value=o,r));if(n instanceof Promise)throw new eo;return r.value=n,r}}),sO=B("$ZodOptional",(t,e)=>{et.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ge(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ge(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${Rd(r.source)})?$`):void 0}),t._zod.parse=(r,a)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,a):r.value===void 0?r:e.innerType._zod.run(r,a)}),oO=B("$ZodNullable",(t,e)=>{et.init(t,e),Ge(t._zod,"optin",()=>e.innerType._zod.optin),Ge(t._zod,"optout",()=>e.innerType._zod.optout),Ge(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${Rd(r.source)}|null)$`):void 0}),Ge(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,a)=>r.value===null?r:e.innerType._zod.run(r,a)}),iO=B("$ZodDefault",(t,e)=>{et.init(t,e),t._zod.optin="optional",Ge(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>zg(s,e)):zg(n,e)}});function zg(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const lO=B("$ZodPrefault",(t,e)=>{et.init(t,e),t._zod.optin="optional",Ge(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,a))}),cO=B("$ZodNonOptional",(t,e)=>{et.init(t,e),Ge(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(a=>a!==void 0)):void 0}),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>Ug(s,t)):Ug(n,t)}});function Ug(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const uO=B("$ZodCatch",(t,e)=>{et.init(t,e),t._zod.optin="optional",Ge(t._zod,"optout",()=>e.innerType._zod.optout),Ge(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>Ln(o,a,Dn()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>Ln(s,a,Dn()))},input:r.value}),r.issues=[]),r)}}),dO=B("$ZodPipe",(t,e)=>{et.init(t,e),Ge(t._zod,"values",()=>e.in._zod.values),Ge(t._zod,"optin",()=>e.in._zod.optin),Ge(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,a)=>{const n=e.in._zod.run(r,a);return n instanceof Promise?n.then(s=>qg(s,e,a)):qg(n,e,a)}});function qg(t,e,r){return no(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const pO=B("$ZodReadonly",(t,e)=>{et.init(t,e),Ge(t._zod,"propValues",()=>e.innerType._zod.propValues),Ge(t._zod,"values",()=>e.innerType._zod.values),Ge(t._zod,"optin",()=>e.innerType._zod.optin),Ge(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(Fg):Fg(n)}});function Fg(t){return t.value=Object.freeze(t.value),t}const fO=B("$ZodLazy",(t,e)=>{et.init(t,e),Ge(t._zod,"innerType",()=>e.getter()),Ge(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Ge(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Ge(t._zod,"optin",()=>t._zod.innerType._zod.optin),Ge(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,a)=>t._zod.innerType._zod.run(r,a)}),hO=B("$ZodCustom",(t,e)=>{nr.init(t,e),et.init(t,e),t._zod.parse=(r,a)=>r,t._zod.check=r=>{const a=r.value,n=e.fn(a);if(n instanceof Promise)return n.then(s=>Zg(s,r,a,t));Zg(n,r,a,t)}});function Zg(t,e,r,a){if(!t){const n={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(n.params=a._zod.def.params),e.issues.push(ao(n))}}class Vg{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const a=r[0];if(this._map.set(e,a),a&&typeof a=="object"&&"id"in a){if(this._idmap.has(a.id))throw new Error(`ID ${a.id} already exists in the registry`);this._idmap.set(a.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const a={...this.get(r)??{}};return delete a.id,{...a,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function mO(){return new Vg}const so=mO();function vO(t,e){return new t({type:"string",...fe(e)})}function gO(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...fe(e)})}function Hg(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...fe(e)})}function yO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...fe(e)})}function _O(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fe(e)})}function wO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fe(e)})}function bO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fe(e)})}function EO(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...fe(e)})}function SO(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...fe(e)})}function $O(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...fe(e)})}function PO(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...fe(e)})}function kO(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...fe(e)})}function IO(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...fe(e)})}function xO(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...fe(e)})}function TO(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...fe(e)})}function CO(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...fe(e)})}function RO(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...fe(e)})}function OO(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...fe(e)})}function NO(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fe(e)})}function Bg(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...fe(e)})}function AO(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...fe(e)})}function MO(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...fe(e)})}function jO(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...fe(e)})}function DO(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fe(e)})}function LO(t,e){return new t({type:"string",format:"date",check:"string_format",...fe(e)})}function zO(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...fe(e)})}function UO(t,e){return new t({type:"string",format:"duration",check:"string_format",...fe(e)})}function qO(t,e){return new t({type:"number",checks:[],...fe(e)})}function FO(t,e){return new t({type:"number",coerce:!0,checks:[],...fe(e)})}function ZO(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...fe(e)})}function VO(t,e){return new t({type:"boolean",...fe(e)})}function HO(t,e){return new t({type:"null",...fe(e)})}function BO(t){return new t({type:"any"})}function JO(t){return new t({type:"unknown"})}function GO(t,e){return new t({type:"never",...fe(e)})}function Jg(t,e){return new Cg({check:"less_than",...fe(e),value:t,inclusive:!1})}function Md(t,e){return new Cg({check:"less_than",...fe(e),value:t,inclusive:!0})}function Gg(t,e){return new Rg({check:"greater_than",...fe(e),value:t,inclusive:!1})}function jd(t,e){return new Rg({check:"greater_than",...fe(e),value:t,inclusive:!0})}function Kg(t,e){return new oR({check:"multiple_of",...fe(e),value:t})}function Wg(t,e){return new lR({check:"max_length",...fe(e),maximum:t})}function dl(t,e){return new cR({check:"min_length",...fe(e),minimum:t})}function Qg(t,e){return new uR({check:"length_equals",...fe(e),length:t})}function KO(t,e){return new dR({check:"string_format",format:"regex",...fe(e),pattern:t})}function WO(t){return new pR({check:"string_format",format:"lowercase",...fe(t)})}function QO(t){return new fR({check:"string_format",format:"uppercase",...fe(t)})}function YO(t,e){return new hR({check:"string_format",format:"includes",...fe(e),includes:t})}function XO(t,e){return new mR({check:"string_format",format:"starts_with",...fe(e),prefix:t})}function e2(t,e){return new vR({check:"string_format",format:"ends_with",...fe(e),suffix:t})}function oo(t){return new gR({check:"overwrite",tx:t})}function t2(t){return oo(e=>e.normalize(t))}function r2(){return oo(t=>t.trim())}function n2(){return oo(t=>t.toLowerCase())}function a2(){return oo(t=>t.toUpperCase())}function s2(t,e,r){return new t({type:"array",element:e,...fe(r)})}function o2(t,e,r){const a=fe(r);return a.abort??(a.abort=!0),new t({type:"custom",check:"custom",fn:e,...a})}function i2(t,e,r){return new t({type:"custom",check:"custom",fn:e,...fe(r)})}class Yg{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??so,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var f,g,d;var a;const n=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const l=(g=(f=e._zod).toJSONSchema)==null?void 0:g.call(f);if(l)i.schema=l;else{const h={...r,schemaPath:[...r.schemaPath,e],path:r.path},v=e._zod.parent;if(v)i.ref=v,this.process(v,h),this.seen.get(v).isParent=!0;else{const m=i.schema;switch(n.type){case"string":{const p=m;p.type="string";const{minimum:_,maximum:w,format:b,patterns:S,contentEncoding:I}=e._zod.bag;if(typeof _=="number"&&(p.minLength=_),typeof w=="number"&&(p.maxLength=w),b&&(p.format=s[b]??b,p.format===""&&delete p.format),I&&(p.contentEncoding=I),S&&S.size>0){const k=[...S];k.length===1?p.pattern=k[0].source:k.length>1&&(i.schema.allOf=[...k.map(A=>({...this.target==="draft-7"?{type:"string"}:{},pattern:A.source}))])}break}case"number":{const p=m,{minimum:_,maximum:w,format:b,multipleOf:S,exclusiveMaximum:I,exclusiveMinimum:k}=e._zod.bag;typeof b=="string"&&b.includes("int")?p.type="integer":p.type="number",typeof k=="number"&&(p.exclusiveMinimum=k),typeof _=="number"&&(p.minimum=_,typeof k=="number"&&(k>=_?delete p.minimum:delete p.exclusiveMinimum)),typeof I=="number"&&(p.exclusiveMaximum=I),typeof w=="number"&&(p.maximum=w,typeof I=="number"&&(I<=w?delete p.maximum:delete p.exclusiveMaximum)),typeof S=="number"&&(p.multipleOf=S);break}case"boolean":{const p=m;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.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":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=m,{minimum:_,maximum:w}=e._zod.bag;typeof _=="number"&&(p.minItems=_),typeof w=="number"&&(p.maxItems=w),p.type="array",p.items=this.process(n.element,{...h,path:[...h.path,"items"]});break}case"object":{const p=m;p.type="object",p.properties={};const _=n.shape;for(const S in _)p.properties[S]=this.process(_[S],{...h,path:[...h.path,"properties",S]});const w=new Set(Object.keys(_)),b=new Set([...w].filter(S=>{const I=n.shape[S]._zod;return this.io==="input"?I.optin===void 0:I.optout===void 0}));b.size>0&&(p.required=Array.from(b)),((d=n.catchall)==null?void 0:d._zod.def.type)==="never"?p.additionalProperties=!1:n.catchall?n.catchall&&(p.additionalProperties=this.process(n.catchall,{...h,path:[...h.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=m;p.anyOf=n.options.map((_,w)=>this.process(_,{...h,path:[...h.path,"anyOf",w]}));break}case"intersection":{const p=m,_=this.process(n.left,{...h,path:[...h.path,"allOf",0]}),w=this.process(n.right,{...h,path:[...h.path,"allOf",1]}),b=I=>"allOf"in I&&Object.keys(I).length===1,S=[...b(_)?_.allOf:[_],...b(w)?w.allOf:[w]];p.allOf=S;break}case"tuple":{const p=m;p.type="array";const _=n.items.map((S,I)=>this.process(S,{...h,path:[...h.path,"prefixItems",I]}));if(this.target==="draft-2020-12"?p.prefixItems=_:p.items=_,n.rest){const S=this.process(n.rest,{...h,path:[...h.path,"items"]});this.target==="draft-2020-12"?p.items=S:p.additionalItems=S}n.rest&&(p.items=this.process(n.rest,{...h,path:[...h.path,"items"]}));const{minimum:w,maximum:b}=e._zod.bag;typeof w=="number"&&(p.minItems=w),typeof b=="number"&&(p.maxItems=b);break}case"record":{const p=m;p.type="object",p.propertyNames=this.process(n.keyType,{...h,path:[...h.path,"propertyNames"]}),p.additionalProperties=this.process(n.valueType,{...h,path:[...h.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const p=m,_=yg(n.entries);_.every(w=>typeof w=="number")&&(p.type="number"),_.every(w=>typeof w=="string")&&(p.type="string"),p.enum=_;break}case"literal":{const p=m,_=[];for(const w of n.values)if(w===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof w=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");_.push(Number(w))}else _.push(w);if(_.length!==0)if(_.length===1){const w=_[0];p.type=w===null?"null":typeof w,p.const=w}else _.every(w=>typeof w=="number")&&(p.type="number"),_.every(w=>typeof w=="string")&&(p.type="string"),_.every(w=>typeof w=="boolean")&&(p.type="string"),_.every(w=>w===null)&&(p.type="null"),p.enum=_;break}case"file":{const p=m,_={type:"string",format:"binary",contentEncoding:"binary"},{minimum:w,maximum:b,mime:S}=e._zod.bag;w!==void 0&&(_.minLength=w),b!==void 0&&(_.maxLength=b),S?S.length===1?(_.contentMediaType=S[0],Object.assign(p,_)):p.anyOf=S.map(I=>({..._,contentMediaType:I})):Object.assign(p,_);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(n.innerType,h);m.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(n.innerType,h),i.ref=n.innerType;break}case"success":{const p=m;p.type="boolean";break}case"default":{this.process(n.innerType,h),i.ref=n.innerType,m.default=JSON.parse(JSON.stringify(n.defaultValue));break}case"prefault":{this.process(n.innerType,h),i.ref=n.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break}case"catch":{this.process(n.innerType,h),i.ref=n.innerType;let p;try{p=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=m,_=e._zod.pattern;if(!_)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=_.source;break}case"pipe":{const p=this.io==="input"?n.in._zod.def.type==="transform"?n.out:n.in:n.out;this.process(p,h),i.ref=p;break}case"readonly":{this.process(n.innerType,h),i.ref=n.innerType,m.readOnly=!0;break}case"promise":{this.process(n.innerType,h),i.ref=n.innerType;break}case"optional":{this.process(n.innerType,h),i.ref=n.innerType;break}case"lazy":{const p=e._zod.innerType;this.process(p,h),i.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),this.io==="input"&&Rt(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((a=i.schema).default??(a.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){var u,f,g,d,h,v;const a={cycles:(r==null?void 0:r.cycles)??"ref",reused:(r==null?void 0:r.reused)??"inline",external:(r==null?void 0:r.external)??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=m=>{var S;const p=this.target==="draft-2020-12"?"$defs":"definitions";if(a.external){const I=(S=a.external.registry.get(m[0]))==null?void 0:S.id,k=a.external.uri??(O=>O);if(I)return{ref:k(I)};const A=m[1].defId??m[1].schema.id??`schema${this.counter++}`;return m[1].defId=A,{defId:A,ref:`${k("__shared")}#/${p}/${A}`}}if(m[1]===n)return{ref:"#"};const w=`#/${p}/`,b=m[1].schema.id??`__schema${this.counter++}`;return{defId:b,ref:w+b}},o=m=>{if(m[1].schema.$ref)return;const p=m[1],{ref:_,defId:w}=s(m);p.def={...p.schema},w&&(p.defId=w);const b=p.schema;for(const S in b)delete b[S];b.$ref=_};if(a.cycles==="throw")for(const m of this.seen.entries()){const p=m[1];if(p.cycle)throw new Error(`Cycle detected: #/${(u=p.cycle)==null?void 0:u.join("/")}/<root>
499
+ path: iss.path ? [${Ks(y)}, ...iss.path] : [${Ks(y)}]
500
+ })));`),g.write(`newResult[${Ks(y)}] = ${_}.value`)}g.write("payload.value = newResult;"),g.write("return payload;");const p=g.compile();return(y,_)=>p(h,y,_)};let n;const s=Ki,o=!wg.jitless,l=o&&$C.value,c=e.catchall;let u;t._zod.parse=(h,g)=>{u??(u=r.value);const d=h.value;if(!s(d))return h.issues.push({expected:"object",code:"invalid_type",input:d,inst:t}),h;const f=[];if(o&&l&&(g==null?void 0:g.async)===!1&&g.jitless!==!0)n||(n=a(e.shape)),h=n(h,g);else{h.value={};const _=u.shape;for(const w of u.keys){const E=_[w],P=E._zod.run({value:d[w],issues:[]},g),T=E._zod.optin==="optional"&&E._zod.optout==="optional";P instanceof Promise?f.push(P.then(O=>T?Lg(O,h,w,d):Xi(O,h,w))):T?Lg(P,h,w,d):Xi(P,h,w)}}if(!c)return f.length?Promise.all(f).then(()=>h):h;const v=[],m=u.keySet,p=c._zod,y=p.def.type;for(const _ of Object.keys(d)){if(m.has(_))continue;if(y==="never"){v.push(_);continue}const w=p.run({value:d[_],issues:[]},g);w instanceof Promise?f.push(w.then(E=>Xi(E,h,_))):Xi(w,h,_)}return v.length&&h.issues.push({code:"unrecognized_keys",keys:v,input:d,inst:t}),f.length?Promise.all(f).then(()=>h):h}});function zg(t,e,r,a){for(const n of t)if(n.issues.length===0)return e.value=n.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(n=>n.issues.map(s=>In(s,a,kn())))}),e}const Ug=B("$ZodUnion",(t,e)=>{et.init(t,e),Je(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Je(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Je(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Je(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>$d(a.source)).join("|")})$`)}}),t._zod.parse=(r,a)=>{let n=!1;const s=[];for(const o of e.options){const i=o._zod.run({value:r.value,issues:[]},a);if(i instanceof Promise)s.push(i),n=!0;else{if(i.issues.length===0)return i;s.push(i)}}return n?Promise.all(s).then(o=>zg(o,r,t,a)):zg(s,r,t,a)}}),oO=B("$ZodDiscriminatedUnion",(t,e)=>{Ug.init(t,e);const r=t._zod.parse;Je(t._zod,"propValues",()=>{const n={};for(const s of e.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(const[i,l]of Object.entries(o)){n[i]||(n[i]=new Set);for(const c of l)n[i].add(c)}}return n});const a=bd(()=>{const n=e.options,s=new Map;for(const o of n){const i=o._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(const l of i){if(s.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);s.set(l,o)}}return s});t._zod.parse=(n,s)=>{const o=n.value;if(!Ki(o))return n.issues.push({code:"invalid_type",expected:"object",input:o,inst:t}),n;const i=a.value.get(o==null?void 0:o[e.discriminator]);return i?i._zod.run(n,s):e.unionFallback?r(n,s):(n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:o,path:[e.discriminator],inst:t}),n)}}),iO=B("$ZodIntersection",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=r.value,s=e.left._zod.run({value:n,issues:[]},a),o=e.right._zod.run({value:n,issues:[]},a);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([l,c])=>qg(r,l,c)):qg(r,s,o)}});function Td(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Wi(t)&&Wi(e)){const r=Object.keys(e),a=Object.keys(t).filter(s=>r.indexOf(s)!==-1),n={...t,...e};for(const s of a){const o=Td(t[s],e[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};n[s]=o.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let a=0;a<t.length;a++){const n=t[a],s=e[a],o=Td(n,s);if(!o.valid)return{valid:!1,mergeErrorPath:[a,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function qg(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Qs(t))return t;const a=Td(e.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return t.value=a.data,t}const lO=B("$ZodRecord",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=r.value;if(!Wi(n))return r.issues.push({expected:"record",code:"invalid_type",input:n,inst:t}),r;const s=[];if(e.keyType._zod.values){const o=e.keyType._zod.values;r.value={};for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){const c=e.valueType._zod.run({value:n[l],issues:[]},a);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Qn(l,u.issues)),r.value[l]=u.value})):(c.issues.length&&r.issues.push(...Qn(l,c.issues)),r.value[l]=c.value)}let i;for(const l in n)o.has(l)||(i=i??[],i.push(l));i&&i.length>0&&r.issues.push({code:"unrecognized_keys",input:n,inst:t,keys:i})}else{r.value={};for(const o of Reflect.ownKeys(n)){if(o==="__proto__")continue;const i=e.keyType._zod.run({value:o,issues:[]},a);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=>In(c,a,kn())),input:o,path:[o],inst:t}),r.value[i.value]=i.value;continue}const l=e.valueType._zod.run({value:n[o],issues:[]},a);l instanceof Promise?s.push(l.then(c=>{c.issues.length&&r.issues.push(...Qn(o,c.issues)),r.value[i.value]=c.value})):(l.issues.length&&r.issues.push(...Qn(o,l.issues)),r.value[i.value]=l.value)}}return s.length?Promise.all(s).then(()=>r):r}}),cO=B("$ZodEnum",(t,e)=>{et.init(t,e);const r=bg(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(a=>SC.has(typeof a)).map(a=>typeof a=="string"?Ws(a):a.toString()).join("|")})$`),t._zod.parse=(a,n)=>{const s=a.value;return t._zod.values.has(s)||a.issues.push({code:"invalid_value",values:r,input:s,inst:t}),a}}),uO=B("$ZodLiteral",(t,e)=>{et.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Ws(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,a)=>{const n=r.value;return t._zod.values.has(n)||r.issues.push({code:"invalid_value",values:e.values,input:n,inst:t}),r}}),dO=B("$ZodTransform",(t,e)=>{et.init(t,e),t._zod.parse=(r,a)=>{const n=e.transform(r.value,r);if(a.async)return(n instanceof Promise?n:Promise.resolve(n)).then(o=>(r.value=o,r));if(n instanceof Promise)throw new Gs;return r.value=n,r}}),fO=B("$ZodOptional",(t,e)=>{et.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Je(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Je(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${$d(r.source)})?$`):void 0}),t._zod.parse=(r,a)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,a):r.value===void 0?r:e.innerType._zod.run(r,a)}),pO=B("$ZodNullable",(t,e)=>{et.init(t,e),Je(t._zod,"optin",()=>e.innerType._zod.optin),Je(t._zod,"optout",()=>e.innerType._zod.optout),Je(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${$d(r.source)}|null)$`):void 0}),Je(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,a)=>r.value===null?r:e.innerType._zod.run(r,a)}),hO=B("$ZodDefault",(t,e)=>{et.init(t,e),t._zod.optin="optional",Je(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{if(r.value===void 0)return r.value=e.defaultValue,r;const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>Fg(s,e)):Fg(n,e)}});function Fg(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const mO=B("$ZodPrefault",(t,e)=>{et.init(t,e),t._zod.optin="optional",Je(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,a))}),vO=B("$ZodNonOptional",(t,e)=>{et.init(t,e),Je(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(a=>a!==void 0)):void 0}),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>Zg(s,t)):Zg(n,t)}});function Zg(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const gO=B("$ZodCatch",(t,e)=>{et.init(t,e),t._zod.optin="optional",Je(t._zod,"optout",()=>e.innerType._zod.optout),Je(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>In(o,a,kn()))},input:r.value}),r.issues=[]),r)):(r.value=n.value,n.issues.length&&(r.value=e.catchValue({...r,error:{issues:n.issues.map(s=>In(s,a,kn()))},input:r.value}),r.issues=[]),r)}}),yO=B("$ZodPipe",(t,e)=>{et.init(t,e),Je(t._zod,"values",()=>e.in._zod.values),Je(t._zod,"optin",()=>e.in._zod.optin),Je(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,a)=>{const n=e.in._zod.run(r,a);return n instanceof Promise?n.then(s=>Vg(s,e,a)):Vg(n,e,a)}});function Vg(t,e,r){return Qs(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}const _O=B("$ZodReadonly",(t,e)=>{et.init(t,e),Je(t._zod,"propValues",()=>e.innerType._zod.propValues),Je(t._zod,"values",()=>e.innerType._zod.values),Je(t._zod,"optin",()=>e.innerType._zod.optin),Je(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,a)=>{const n=e.innerType._zod.run(r,a);return n instanceof Promise?n.then(Hg):Hg(n)}});function Hg(t){return t.value=Object.freeze(t.value),t}const wO=B("$ZodLazy",(t,e)=>{et.init(t,e),Je(t._zod,"innerType",()=>e.getter()),Je(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Je(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Je(t._zod,"optin",()=>t._zod.innerType._zod.optin),Je(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(r,a)=>t._zod.innerType._zod.run(r,a)}),bO=B("$ZodCustom",(t,e)=>{Wt.init(t,e),et.init(t,e),t._zod.parse=(r,a)=>r,t._zod.check=r=>{const a=r.value,n=e.fn(a);if(n instanceof Promise)return n.then(s=>Bg(s,r,a,t));Bg(n,r,a,t)}});function Bg(t,e,r,a){if(!t){const n={code:"custom",input:r,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(n.params=a._zod.def.params),e.issues.push(Ys(n))}}class Jg{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){const a=r[0];if(this._map.set(e,a),a&&typeof a=="object"&&"id"in a){if(this._idmap.has(a.id))throw new Error(`ID ${a.id} already exists in the registry`);this._idmap.set(a.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const a={...this.get(r)??{}};return delete a.id,{...a,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function EO(){return new Jg}const Xs=EO();function $O(t,e){return new t({type:"string",...de(e)})}function SO(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...de(e)})}function Gg(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...de(e)})}function PO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...de(e)})}function TO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...de(e)})}function xO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...de(e)})}function kO(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...de(e)})}function IO(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...de(e)})}function CO(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...de(e)})}function RO(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...de(e)})}function OO(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...de(e)})}function AO(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...de(e)})}function NO(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...de(e)})}function MO(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...de(e)})}function jO(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...de(e)})}function DO(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...de(e)})}function LO(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...de(e)})}function zO(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...de(e)})}function UO(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...de(e)})}function Kg(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...de(e)})}function qO(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...de(e)})}function FO(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...de(e)})}function ZO(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...de(e)})}function VO(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...de(e)})}function HO(t,e){return new t({type:"string",format:"date",check:"string_format",...de(e)})}function BO(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...de(e)})}function JO(t,e){return new t({type:"string",format:"duration",check:"string_format",...de(e)})}function GO(t,e){return new t({type:"number",checks:[],...de(e)})}function KO(t,e){return new t({type:"number",coerce:!0,checks:[],...de(e)})}function WO(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...de(e)})}function QO(t,e){return new t({type:"boolean",...de(e)})}function YO(t,e){return new t({type:"null",...de(e)})}function XO(t){return new t({type:"any"})}function e2(t){return new t({type:"unknown"})}function t2(t,e){return new t({type:"never",...de(e)})}function Wg(t,e){return new Ag({check:"less_than",...de(e),value:t,inclusive:!1})}function xd(t,e){return new Ag({check:"less_than",...de(e),value:t,inclusive:!0})}function Qg(t,e){return new Ng({check:"greater_than",...de(e),value:t,inclusive:!1})}function kd(t,e){return new Ng({check:"greater_than",...de(e),value:t,inclusive:!0})}function Yg(t,e){return new pR({check:"multiple_of",...de(e),value:t})}function Xg(t,e){return new mR({check:"max_length",...de(e),maximum:t})}function el(t,e){return new vR({check:"min_length",...de(e),minimum:t})}function ey(t,e){return new gR({check:"length_equals",...de(e),length:t})}function r2(t,e){return new yR({check:"string_format",format:"regex",...de(e),pattern:t})}function n2(t){return new _R({check:"string_format",format:"lowercase",...de(t)})}function a2(t){return new wR({check:"string_format",format:"uppercase",...de(t)})}function s2(t,e){return new bR({check:"string_format",format:"includes",...de(e),includes:t})}function o2(t,e){return new ER({check:"string_format",format:"starts_with",...de(e),prefix:t})}function i2(t,e){return new $R({check:"string_format",format:"ends_with",...de(e),suffix:t})}function eo(t){return new SR({check:"overwrite",tx:t})}function l2(t){return eo(e=>e.normalize(t))}function c2(){return eo(t=>t.trim())}function u2(){return eo(t=>t.toLowerCase())}function d2(){return eo(t=>t.toUpperCase())}function f2(t,e,r){return new t({type:"array",element:e,...de(r)})}function p2(t,e,r){const a=de(r);return a.abort??(a.abort=!0),new t({type:"custom",check:"custom",fn:e,...a})}function h2(t,e,r){return new t({type:"custom",check:"custom",fn:e,...de(r)})}class ty{constructor(e){this.counter=0,this.metadataRegistry=(e==null?void 0:e.metadata)??Xs,this.target=(e==null?void 0:e.target)??"draft-2020-12",this.unrepresentable=(e==null?void 0:e.unrepresentable)??"throw",this.override=(e==null?void 0:e.override)??(()=>{}),this.io=(e==null?void 0:e.io)??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var h,g,d;var a;const n=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},o=this.seen.get(e);if(o)return o.count++,r.schemaPath.includes(e)&&(o.cycle=r.path),o.schema;const i={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,i);const l=(g=(h=e._zod).toJSONSchema)==null?void 0:g.call(h);if(l)i.schema=l;else{const f={...r,schemaPath:[...r.schemaPath,e],path:r.path},v=e._zod.parent;if(v)i.ref=v,this.process(v,f),this.seen.get(v).isParent=!0;else{const m=i.schema;switch(n.type){case"string":{const p=m;p.type="string";const{minimum:y,maximum:_,format:w,patterns:E,contentEncoding:P}=e._zod.bag;if(typeof y=="number"&&(p.minLength=y),typeof _=="number"&&(p.maxLength=_),w&&(p.format=s[w]??w,p.format===""&&delete p.format),P&&(p.contentEncoding=P),E&&E.size>0){const T=[...E];T.length===1?p.pattern=T[0].source:T.length>1&&(i.schema.allOf=[...T.map(O=>({...this.target==="draft-7"?{type:"string"}:{},pattern:O.source}))])}break}case"number":{const p=m,{minimum:y,maximum:_,format:w,multipleOf:E,exclusiveMaximum:P,exclusiveMinimum:T}=e._zod.bag;typeof w=="string"&&w.includes("int")?p.type="integer":p.type="number",typeof T=="number"&&(p.exclusiveMinimum=T),typeof y=="number"&&(p.minimum=y,typeof T=="number"&&(T>=y?delete p.minimum:delete p.exclusiveMinimum)),typeof P=="number"&&(p.exclusiveMaximum=P),typeof _=="number"&&(p.maximum=_,typeof P=="number"&&(P<=_?delete p.maximum:delete p.exclusiveMaximum)),typeof E=="number"&&(p.multipleOf=E);break}case"boolean":{const p=m;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.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":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=m,{minimum:y,maximum:_}=e._zod.bag;typeof y=="number"&&(p.minItems=y),typeof _=="number"&&(p.maxItems=_),p.type="array",p.items=this.process(n.element,{...f,path:[...f.path,"items"]});break}case"object":{const p=m;p.type="object",p.properties={};const y=n.shape;for(const E in y)p.properties[E]=this.process(y[E],{...f,path:[...f.path,"properties",E]});const _=new Set(Object.keys(y)),w=new Set([..._].filter(E=>{const P=n.shape[E]._zod;return this.io==="input"?P.optin===void 0:P.optout===void 0}));w.size>0&&(p.required=Array.from(w)),((d=n.catchall)==null?void 0:d._zod.def.type)==="never"?p.additionalProperties=!1:n.catchall?n.catchall&&(p.additionalProperties=this.process(n.catchall,{...f,path:[...f.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=m;p.anyOf=n.options.map((y,_)=>this.process(y,{...f,path:[...f.path,"anyOf",_]}));break}case"intersection":{const p=m,y=this.process(n.left,{...f,path:[...f.path,"allOf",0]}),_=this.process(n.right,{...f,path:[...f.path,"allOf",1]}),w=P=>"allOf"in P&&Object.keys(P).length===1,E=[...w(y)?y.allOf:[y],...w(_)?_.allOf:[_]];p.allOf=E;break}case"tuple":{const p=m;p.type="array";const y=n.items.map((E,P)=>this.process(E,{...f,path:[...f.path,"prefixItems",P]}));if(this.target==="draft-2020-12"?p.prefixItems=y:p.items=y,n.rest){const E=this.process(n.rest,{...f,path:[...f.path,"items"]});this.target==="draft-2020-12"?p.items=E:p.additionalItems=E}n.rest&&(p.items=this.process(n.rest,{...f,path:[...f.path,"items"]}));const{minimum:_,maximum:w}=e._zod.bag;typeof _=="number"&&(p.minItems=_),typeof w=="number"&&(p.maxItems=w);break}case"record":{const p=m;p.type="object",p.propertyNames=this.process(n.keyType,{...f,path:[...f.path,"propertyNames"]}),p.additionalProperties=this.process(n.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 p=m,y=bg(n.entries);y.every(_=>typeof _=="number")&&(p.type="number"),y.every(_=>typeof _=="string")&&(p.type="string"),p.enum=y;break}case"literal":{const p=m,y=[];for(const _ of n.values)if(_===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof _=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");y.push(Number(_))}else y.push(_);if(y.length!==0)if(y.length===1){const _=y[0];p.type=_===null?"null":typeof _,p.const=_}else y.every(_=>typeof _=="number")&&(p.type="number"),y.every(_=>typeof _=="string")&&(p.type="string"),y.every(_=>typeof _=="boolean")&&(p.type="string"),y.every(_=>_===null)&&(p.type="null"),p.enum=y;break}case"file":{const p=m,y={type:"string",format:"binary",contentEncoding:"binary"},{minimum:_,maximum:w,mime:E}=e._zod.bag;_!==void 0&&(y.minLength=_),w!==void 0&&(y.maxLength=w),E?E.length===1?(y.contentMediaType=E[0],Object.assign(p,y)):p.anyOf=E.map(P=>({...y,contentMediaType:P})):Object.assign(p,y);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(n.innerType,f);m.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(n.innerType,f),i.ref=n.innerType;break}case"success":{const p=m;p.type="boolean";break}case"default":{this.process(n.innerType,f),i.ref=n.innerType,m.default=JSON.parse(JSON.stringify(n.defaultValue));break}case"prefault":{this.process(n.innerType,f),i.ref=n.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(n.defaultValue)));break}case"catch":{this.process(n.innerType,f),i.ref=n.innerType;let p;try{p=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=m,y=e._zod.pattern;if(!y)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=y.source;break}case"pipe":{const p=this.io==="input"?n.in._zod.def.type==="transform"?n.out:n.in:n.out;this.process(p,f),i.ref=p;break}case"readonly":{this.process(n.innerType,f),i.ref=n.innerType,m.readOnly=!0;break}case"promise":{this.process(n.innerType,f),i.ref=n.innerType;break}case"optional":{this.process(n.innerType,f),i.ref=n.innerType;break}case"lazy":{const p=e._zod.innerType;this.process(p,f),i.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(i.schema,c),this.io==="input"&&kt(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((a=i.schema).default??(a.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,r){var u,h,g,d,f,v;const a={cycles:(r==null?void 0:r.cycles)??"ref",reused:(r==null?void 0:r.reused)??"inline",external:(r==null?void 0:r.external)??void 0},n=this.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const s=m=>{var E;const p=this.target==="draft-2020-12"?"$defs":"definitions";if(a.external){const P=(E=a.external.registry.get(m[0]))==null?void 0:E.id,T=a.external.uri??(M=>M);if(P)return{ref:T(P)};const O=m[1].defId??m[1].schema.id??`schema${this.counter++}`;return m[1].defId=O,{defId:O,ref:`${T("__shared")}#/${p}/${O}`}}if(m[1]===n)return{ref:"#"};const _=`#/${p}/`,w=m[1].schema.id??`__schema${this.counter++}`;return{defId:w,ref:_+w}},o=m=>{if(m[1].schema.$ref)return;const p=m[1],{ref:y,defId:_}=s(m);p.def={...p.schema},_&&(p.defId=_);const w=p.schema;for(const E in w)delete w[E];w.$ref=y};if(a.cycles==="throw")for(const m of this.seen.entries()){const p=m[1];if(p.cycle)throw new Error(`Cycle detected: #/${(u=p.cycle)==null?void 0:u.join("/")}/<root>
497
501
 
498
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const m of this.seen.entries()){const p=m[1];if(e===m[0]){o(m);continue}if(a.external){const w=(f=a.external.registry.get(m[0]))==null?void 0:f.id;if(e!==m[0]&&w){o(m);continue}}if((g=this.metadataRegistry.get(m[0]))==null?void 0:g.id){o(m);continue}if(p.cycle){o(m);continue}if(p.count>1&&a.reused==="ref"){o(m);continue}}const i=(m,p)=>{const _=this.seen.get(m),w=_.def??_.schema,b={...w};if(_.ref===null)return;const S=_.ref;if(_.ref=null,S){i(S,p);const I=this.seen.get(S).schema;I.$ref&&p.target==="draft-7"?(w.allOf=w.allOf??[],w.allOf.push(I)):(Object.assign(w,I),Object.assign(w,b))}_.isParent||this.override({zodSchema:m,jsonSchema:w,path:_.path??[]})};for(const m of[...this.seen.entries()].reverse())i(m[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}`),(d=a.external)!=null&&d.uri){const m=(h=a.external.registry.get(e))==null?void 0:h.id;if(!m)throw new Error("Schema is missing an `id` property");l.$id=a.external.uri(m)}Object.assign(l,n.def);const c=((v=a.external)==null?void 0:v.defs)??{};for(const m of this.seen.entries()){const p=m[1];p.def&&p.defId&&(c[p.defId]=p.def)}a.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 l2(t,e){if(t instanceof Vg){const a=new Yg(e),n={};for(const i of t._idmap.entries()){const[l,c]=i;a.process(c)}const s={},o={registry:t,uri:e==null?void 0:e.uri,defs:n};for(const i of t._idmap.entries()){const[l,c]=i;s[l]=a.emit(c,{...e,external:o})}if(Object.keys(n).length>0){const i=a.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:n}}return{schemas:s}}const r=new Yg(e);return r.process(t),r.emit(t,e)}function Rt(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const n=t._zod.def;switch(n.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 Rt(n.element,r);case"object":{for(const s in n.shape)if(Rt(n.shape[s],r))return!0;return!1}case"union":{for(const s of n.options)if(Rt(s,r))return!0;return!1}case"intersection":return Rt(n.left,r)||Rt(n.right,r);case"tuple":{for(const s of n.items)if(Rt(s,r))return!0;return!!(n.rest&&Rt(n.rest,r))}case"record":return Rt(n.keyType,r)||Rt(n.valueType,r);case"map":return Rt(n.keyType,r)||Rt(n.valueType,r);case"set":return Rt(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Rt(n.innerType,r);case"lazy":return Rt(n.getter(),r);case"default":return Rt(n.innerType,r);case"prefault":return Rt(n.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Rt(n.in,r)||Rt(n.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${n.type}`)}const c2=B("ZodISODateTime",(t,e)=>{RR.init(t,e),ft.init(t,e)});function u2(t){return DO(c2,t)}const d2=B("ZodISODate",(t,e)=>{OR.init(t,e),ft.init(t,e)});function p2(t){return LO(d2,t)}const f2=B("ZodISOTime",(t,e)=>{NR.init(t,e),ft.init(t,e)});function h2(t){return zO(f2,t)}const m2=B("ZodISODuration",(t,e)=>{AR.init(t,e),ft.init(t,e)});function v2(t){return UO(m2,t)}const pl=B("ZodError",(t,e)=>{bg.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>IC(t,r)},flatten:{value:r=>kC(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),g2=xC(pl),y2=TC(pl),_2=Sg(pl),Xg=$g(pl),ot=B("ZodType",(t,e)=>(et.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),t.clone=(r,a)=>na(t,r,a),t.brand=()=>t,t.register=(r,a)=>(r.add(t,a),t),t.parse=(r,a)=>g2(t,r,a,{callee:t.parse}),t.safeParse=(r,a)=>_2(t,r,a),t.parseAsync=async(r,a)=>y2(t,r,a,{callee:t.parseAsync}),t.safeParseAsync=async(r,a)=>Xg(t,r,a),t.spa=t.safeParseAsync,t.refine=(r,a)=>t.check(fN(r,a)),t.superRefine=r=>t.check(hN(r)),t.overwrite=r=>t.check(oo(r)),t.optional=()=>It(t),t.nullable=()=>ly(t),t.nullish=()=>It(ly(t)),t.nonoptional=r=>aN(t,r),t.array=()=>oe(t),t.or=r=>He([t,r]),t.and=r=>G2(t,r),t.transform=r=>uy(t,Y2(r)),t.default=r=>tN(t,r),t.prefault=r=>nN(t,r),t.catch=r=>oN(t,r),t.pipe=r=>uy(t,r),t.readonly=()=>cN(t),t.describe=r=>{const a=t.clone();return so.add(a,{description:r}),a},Object.defineProperty(t,"description",{get(){var r;return(r=so.get(t))==null?void 0:r.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return so.get(t);const a=t.clone();return so.add(a,r[0]),a},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),ey=B("_ZodString",(t,e)=>{Nd.init(t,e),ot.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...a)=>t.check(KO(...a)),t.includes=(...a)=>t.check(YO(...a)),t.startsWith=(...a)=>t.check(XO(...a)),t.endsWith=(...a)=>t.check(e2(...a)),t.min=(...a)=>t.check(dl(...a)),t.max=(...a)=>t.check(Wg(...a)),t.length=(...a)=>t.check(Qg(...a)),t.nonempty=(...a)=>t.check(dl(1,...a)),t.lowercase=a=>t.check(WO(a)),t.uppercase=a=>t.check(QO(a)),t.trim=()=>t.check(r2()),t.normalize=(...a)=>t.check(t2(...a)),t.toLowerCase=()=>t.check(n2()),t.toUpperCase=()=>t.check(a2())}),w2=B("ZodString",(t,e)=>{Nd.init(t,e),ey.init(t,e),t.email=r=>t.check(gO(b2,r)),t.url=r=>t.check(EO(E2,r)),t.jwt=r=>t.check(jO(j2,r)),t.emoji=r=>t.check(SO(S2,r)),t.guid=r=>t.check(Hg(ty,r)),t.uuid=r=>t.check(yO(fl,r)),t.uuidv4=r=>t.check(_O(fl,r)),t.uuidv6=r=>t.check(wO(fl,r)),t.uuidv7=r=>t.check(bO(fl,r)),t.nanoid=r=>t.check($O($2,r)),t.guid=r=>t.check(Hg(ty,r)),t.cuid=r=>t.check(PO(P2,r)),t.cuid2=r=>t.check(kO(k2,r)),t.ulid=r=>t.check(IO(I2,r)),t.base64=r=>t.check(Bg(ry,r)),t.base64url=r=>t.check(AO(A2,r)),t.xid=r=>t.check(xO(x2,r)),t.ksuid=r=>t.check(TO(T2,r)),t.ipv4=r=>t.check(CO(C2,r)),t.ipv6=r=>t.check(RO(R2,r)),t.cidrv4=r=>t.check(OO(O2,r)),t.cidrv6=r=>t.check(NO(N2,r)),t.e164=r=>t.check(MO(M2,r)),t.datetime=r=>t.check(u2(r)),t.date=r=>t.check(p2(r)),t.time=r=>t.check(h2(r)),t.duration=r=>t.check(v2(r))});function E(t){return vO(w2,t)}const ft=B("ZodStringFormat",(t,e)=>{ct.init(t,e),ey.init(t,e)}),b2=B("ZodEmail",(t,e)=>{ER.init(t,e),ft.init(t,e)}),ty=B("ZodGUID",(t,e)=>{wR.init(t,e),ft.init(t,e)}),fl=B("ZodUUID",(t,e)=>{bR.init(t,e),ft.init(t,e)}),E2=B("ZodURL",(t,e)=>{SR.init(t,e),ft.init(t,e)}),S2=B("ZodEmoji",(t,e)=>{$R.init(t,e),ft.init(t,e)}),$2=B("ZodNanoID",(t,e)=>{PR.init(t,e),ft.init(t,e)}),P2=B("ZodCUID",(t,e)=>{kR.init(t,e),ft.init(t,e)}),k2=B("ZodCUID2",(t,e)=>{IR.init(t,e),ft.init(t,e)}),I2=B("ZodULID",(t,e)=>{xR.init(t,e),ft.init(t,e)}),x2=B("ZodXID",(t,e)=>{TR.init(t,e),ft.init(t,e)}),T2=B("ZodKSUID",(t,e)=>{CR.init(t,e),ft.init(t,e)}),C2=B("ZodIPv4",(t,e)=>{MR.init(t,e),ft.init(t,e)}),R2=B("ZodIPv6",(t,e)=>{jR.init(t,e),ft.init(t,e)}),O2=B("ZodCIDRv4",(t,e)=>{DR.init(t,e),ft.init(t,e)}),N2=B("ZodCIDRv6",(t,e)=>{LR.init(t,e),ft.init(t,e)}),ry=B("ZodBase64",(t,e)=>{zR.init(t,e),ft.init(t,e)});function ny(t){return Bg(ry,t)}const A2=B("ZodBase64URL",(t,e)=>{qR.init(t,e),ft.init(t,e)}),M2=B("ZodE164",(t,e)=>{FR.init(t,e),ft.init(t,e)}),j2=B("ZodJWT",(t,e)=>{VR.init(t,e),ft.init(t,e)}),Dd=B("ZodNumber",(t,e)=>{Ng.init(t,e),ot.init(t,e),t.gt=(a,n)=>t.check(Gg(a,n)),t.gte=(a,n)=>t.check(jd(a,n)),t.min=(a,n)=>t.check(jd(a,n)),t.lt=(a,n)=>t.check(Jg(a,n)),t.lte=(a,n)=>t.check(Md(a,n)),t.max=(a,n)=>t.check(Md(a,n)),t.int=a=>t.check(ay(a)),t.safe=a=>t.check(ay(a)),t.positive=a=>t.check(Gg(0,a)),t.nonnegative=a=>t.check(jd(0,a)),t.negative=a=>t.check(Jg(0,a)),t.nonpositive=a=>t.check(Md(0,a)),t.multipleOf=(a,n)=>t.check(Kg(a,n)),t.step=(a,n)=>t.check(Kg(a,n)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function Z(t){return qO(Dd,t)}const D2=B("ZodNumberFormat",(t,e)=>{HR.init(t,e),Dd.init(t,e)});function ay(t){return ZO(D2,t)}const L2=B("ZodBoolean",(t,e)=>{BR.init(t,e),ot.init(t,e)});function Pt(t){return VO(L2,t)}const z2=B("ZodNull",(t,e)=>{JR.init(t,e),ot.init(t,e)});function U2(t){return HO(z2,t)}const q2=B("ZodAny",(t,e)=>{GR.init(t,e),ot.init(t,e)});function wr(){return BO(q2)}const F2=B("ZodUnknown",(t,e)=>{KR.init(t,e),ot.init(t,e)});function jr(){return JO(F2)}const Z2=B("ZodNever",(t,e)=>{WR.init(t,e),ot.init(t,e)});function V2(t){return GO(Z2,t)}const H2=B("ZodArray",(t,e)=>{QR.init(t,e),ot.init(t,e),t.element=e.element,t.min=(r,a)=>t.check(dl(r,a)),t.nonempty=r=>t.check(dl(1,r)),t.max=(r,a)=>t.check(Wg(r,a)),t.length=(r,a)=>t.check(Qg(r,a)),t.unwrap=()=>t.element});function oe(t,e){return s2(H2,t,e)}const sy=B("ZodObject",(t,e)=>{YR.init(t,e),ot.init(t,e),Ge(t,"shape",()=>e.shape),t.keyof=()=>ht(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:jr()}),t.loose=()=>t.clone({...t._zod.def,catchall:jr()}),t.strict=()=>t.clone({...t._zod.def,catchall:V2()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>EC(t,r),t.merge=r=>SC(t,r),t.pick=r=>wC(t,r),t.omit=r=>bC(t,r),t.partial=(...r)=>$C(iy,t,r[0]),t.required=(...r)=>PC(cy,t,r[0])});function x(t,e){const r={type:"object",get shape(){return sl(this,"shape",{...t}),this.shape},...fe(e)};return new sy(r)}function Ya(t,e){return new sy({type:"object",get shape(){return sl(this,"shape",{...t}),this.shape},catchall:jr(),...fe(e)})}const oy=B("ZodUnion",(t,e)=>{Dg.init(t,e),ot.init(t,e),t.options=e.options});function He(t,e){return new oy({type:"union",options:t,...fe(e)})}const B2=B("ZodDiscriminatedUnion",(t,e)=>{oy.init(t,e),XR.init(t,e)});function ar(t,e,r){return new B2({type:"union",options:e,discriminator:t,...fe(r)})}const J2=B("ZodIntersection",(t,e)=>{eO.init(t,e),ot.init(t,e)});function G2(t,e){return new J2({type:"intersection",left:t,right:e})}const K2=B("ZodRecord",(t,e)=>{tO.init(t,e),ot.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function kt(t,e,r){return new K2({type:"record",keyType:t,valueType:e,...fe(r)})}const Ld=B("ZodEnum",(t,e)=>{rO.init(t,e),ot.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(a,n)=>{const s={};for(const o of a)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ld({...e,checks:[],...fe(n),entries:s})},t.exclude=(a,n)=>{const s={...e.entries};for(const o of a)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Ld({...e,checks:[],...fe(n),entries:s})}});function ht(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(a=>[a,a])):t;return new Ld({type:"enum",entries:r,...fe(e)})}const W2=B("ZodLiteral",(t,e)=>{nO.init(t,e),ot.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function W(t,e){return new W2({type:"literal",values:Array.isArray(t)?t:[t],...fe(e)})}const Q2=B("ZodTransform",(t,e)=>{aO.init(t,e),ot.init(t,e),t._zod.parse=(r,a)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ao(s,r.value,e));else{const o=s;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=!0),r.issues.push(ao(o))}};const n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r)):(r.value=n,r)}});function Y2(t){return new Q2({type:"transform",transform:t})}const iy=B("ZodOptional",(t,e)=>{sO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function It(t){return new iy({type:"optional",innerType:t})}const X2=B("ZodNullable",(t,e)=>{oO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ly(t){return new X2({type:"nullable",innerType:t})}const eN=B("ZodDefault",(t,e)=>{iO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function tN(t,e){return new eN({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const rN=B("ZodPrefault",(t,e)=>{lO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function nN(t,e){return new rN({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const cy=B("ZodNonOptional",(t,e)=>{cO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function aN(t,e){return new cy({type:"nonoptional",innerType:t,...fe(e)})}const sN=B("ZodCatch",(t,e)=>{uO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function oN(t,e){return new sN({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const iN=B("ZodPipe",(t,e)=>{dO.init(t,e),ot.init(t,e),t.in=e.in,t.out=e.out});function uy(t,e){return new iN({type:"pipe",in:t,out:e})}const lN=B("ZodReadonly",(t,e)=>{pO.init(t,e),ot.init(t,e)});function cN(t){return new lN({type:"readonly",innerType:t})}const uN=B("ZodLazy",(t,e)=>{fO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.getter()});function dy(t){return new uN({type:"lazy",getter:t})}const zd=B("ZodCustom",(t,e)=>{hO.init(t,e),ot.init(t,e)});function dN(t){const e=new nr({check:"custom"});return e._zod.check=t,e}function pN(t,e){return o2(zd,t??(()=>!0),e)}function fN(t,e={}){return i2(zd,t,e)}function hN(t){const e=dN(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(ao(a,r.value,e._zod.def));else{const n=a;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),n.continue??(n.continue=!e._zod.def.abort),r.issues.push(ao(n))}},t(r.value,r)));return e}function hl(t,e={error:`Input not instance of ${t.name}`}){const r=new zd({type:"custom",check:"custom",fn:a=>a instanceof t,abort:!0,...fe(e)});return r._zod.bag.Class=t,r}function mN(t){return FO(Dd,t)}function Kt(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function vN(t,e){if(t==null)return Promise.resolve();const r=e==null?void 0:e.abortSignal;return new Promise((a,n)=>{if(r!=null&&r.aborted){n(py());return}const s=setTimeout(()=>{o(),a()},t),o=()=>{clearTimeout(s),r==null||r.removeEventListener("abort",i)},i=()=>{o(),n(py())};r==null||r.addEventListener("abort",i)})}function py(){return new DOMException("Delay was aborted","AbortError")}function Xa(t){return Object.fromEntries([...t.headers])}var io=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{const n=()=>{const s=r.length,o=new Array(e);for(let i=0;i<e;i++)o[i]=r[Math.random()*s|0];return o.join("")};if(t==null)return n;if(r.includes(a))throw new Bv({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${t}${a}${n()}`},sr=io();function Ud(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function sa(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var gN=["fetch failed","failed to fetch"];function fy({error:t,url:e,requestBodyValues:r}){if(sa(t))return t;if(t instanceof TypeError&&gN.includes(t.message.toLowerCase())){const a=t.cause;if(a!=null)return new Nt({message:`Cannot connect to API: ${a.message}`,cause:a,url:e,requestBodyValues:r,isRetryable:!0})}return t}function lo(t=globalThis){var e,r,a;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(a=(r=t.process)==null?void 0:r.versions)!=null&&a.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function yN(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function wn(t,...e){const r=yN(t??{}),a=new Headers(r),n=a.get("user-agent")||"";return a.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(a)}var hy="3.0.12",_N=()=>globalThis.fetch,my=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:a,abortSignal:n,fetch:s=_N()})=>{try{const o=await s(t,{method:"GET",headers:wn(e,`ai-sdk/provider-utils/${hy}`,lo()),signal:n}),i=Xa(o);if(!o.ok){let l;try{l=await a({response:o,url:t,requestBodyValues:{}})}catch(c){throw sa(c)||Nt.isInstance(c)?c:new Nt({message:"Failed to process error response",cause:c,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:o,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(sa(l)||Nt.isInstance(l))?l:new Nt({message:"Failed to process successful response",cause:l,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(o){throw fy({error:o,url:t,requestBodyValues:{}})}};function wN({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([a,n])=>{const s=a.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:n}:{mediaTypePrefix:s.replace(/\*/,""),regexes:n}}).filter(({mediaTypePrefix:a})=>t.startsWith(a)).flatMap(({regexes:a})=>a).some(a=>a.test(e))}function vy({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:a}){if(typeof t=="string")return t;if(t!=null)throw new al({message:`${a} API key must be a string.`});if(typeof process>"u")throw new al({message:`${a} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new al({message:`${a} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new al({message:`${a} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}function co({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}function bN(t){var e;const[r,a=""]=t.toLowerCase().split("/");return(e={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[a])!=null?e:a}var EN=/"__proto__"\s*:/,SN=/"constructor"\s*:/;function $N(t){const e=JSON.parse(t);return e===null||typeof e!="object"||EN.test(t)===!1&&SN.test(t)===!1?e:PN(e)}function PN(t){let e=[t];for(;e.length;){const r=e;e=[];for(const a of r){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in a){const s=a[n];s&&typeof s=="object"&&e.push(s)}}}return t}function qd(t){const{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return $N(t)}finally{Error.stackTraceLimit=e}}var ml=Symbol.for("vercel.ai.validator");function kN(t){return{[ml]:!0,validate:t}}function IN(t){return typeof t=="object"&&t!==null&&ml in t&&t[ml]===!0&&"validate"in t}function _t(t){let e;return()=>(e==null&&(e=t()),e)}function xN(t){return IN(t)?t:typeof t=="function"?t():TN(t)}function TN(t){return kN(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Xs({value:e,cause:r.issues})}})}async function tn({value:t,schema:e}){const r=await Dr({value:t,schema:e});if(!r.success)throw Xs.wrap({value:t,cause:r.error});return r.value}async function Dr({value:t,schema:e}){const r=xN(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const a=await r.validate(t);return a.success?{success:!0,value:a.value,rawValue:t}:{success:!1,error:Xs.wrap({value:t,cause:a.error}),rawValue:t}}catch(a){return{success:!1,error:Xs.wrap({value:t,cause:a}),rawValue:t}}}async function CN({text:t,schema:e}){try{const r=qd(t);return e==null?r:tn({value:r,schema:e})}catch(r){throw nl.isInstance(r)||Xs.isInstance(r)?r:new nl({text:t,cause:r})}}async function oa({text:t,schema:e}){try{const r=qd(t);return e==null?{success:!0,value:r,rawValue:r}:await Dr({value:r,schema:e})}catch(r){return{success:!1,error:nl.isInstance(r)?r:new nl({text:t,cause:r}),rawValue:void 0}}}function vl(t){try{return qd(t),!0}catch{return!1}}function RN({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new rd).pipeThrough(new TransformStream({async transform({data:r},a){r!=="[DONE]"&&a.enqueue(await oa({text:r,schema:e}))}}))}async function rn({provider:t,providerOptions:e,schema:r}){if((e==null?void 0:e[t])==null)return;const a=await Dr({value:e[t],schema:r});if(!a.success)throw new Bv({argument:"providerOptions",message:`invalid ${t} provider options`,cause:a.error});return a.value}var ON=()=>globalThis.fetch,or=async({url:t,headers:e,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>gy({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),NN=async({url:t,headers:e,formData:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>gy({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),gy=async({url:t,headers:e={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:s,fetch:o=ON()})=>{try{const i=await o(t,{method:"POST",headers:wn(e,`ai-sdk/provider-utils/${hy}`,lo()),body:r.content,signal:s}),l=Xa(i);if(!i.ok){let c;try{c=await n({response:i,url:t,requestBodyValues:r.values})}catch(u){throw sa(u)||Nt.isInstance(u)?u:new Nt({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await a({response:i,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(sa(c)||Nt.isInstance(c))?c:new Nt({message:"Failed to process successful response",cause:c,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw fy({error:i,url:t,requestBodyValues:r.values})}};function Z3(t){return t}function yy(t){return{...t,type:"dynamic"}}function es({id:t,name:e,inputSchema:r,outputSchema:a}){return({execute:n,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider-defined",id:t,name:e,args:c,inputSchema:r,outputSchema:a,execute:n,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l})}async function zn(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var ia=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:a,url:n,requestBodyValues:s})=>{const o=await a.text(),i=Xa(a);if(o.trim()==="")return{responseHeaders:i,value:new Nt({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})};try{const l=await CN({text:o,schema:t});return{responseHeaders:i,value:new Nt({message:e(l),url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,data:l,isRetryable:r==null?void 0:r(a,l)})}}catch{return{responseHeaders:i,value:new Nt({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})}}},uo=t=>async({response:e})=>{const r=Xa(e);if(e.body==null)throw new rC({});return{responseHeaders:r,value:RN({stream:e.body,schema:t})}},Lr=t=>async({response:e,url:r,requestBodyValues:a})=>{const n=await e.text(),s=await oa({text:n,schema:t}),o=Xa(e);if(!s.success)throw new Nt({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:o,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},AN=()=>async({response:t,url:e,requestBodyValues:r})=>{const a=Xa(t);if(!t.body)throw new Nt({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0});try{const n=await t.arrayBuffer();return{responseHeaders:a,value:new Uint8Array(n)}}catch(n){throw new Nt({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0,cause:n})}},MN=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},jN=Symbol("Let zodToJsonSchema decide on which parser to use"),_y={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"},DN=t=>typeof t=="string"?{..._y,name:t}:{..._y,...t};function fr(){return{}}function LN(t,e){var r,a,n;const s={type:"array"};return(r=t.type)!=null&&r._def&&((n=(a=t.type)==null?void 0:a._def)==null?void 0:n.typeName)!==V.ZodAny&&(s.items=We(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(s.minItems=t.minLength.value),t.maxLength&&(s.maxItems=t.maxLength.value),t.exactLength&&(s.minItems=t.exactLength.value,s.maxItems=t.exactLength.value),s}function zN(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function UN(){return{type:"boolean"}}function wy(t,e){return We(t.type._def,e)}var qN=(t,e)=>We(t.innerType._def,e);function by(t,e,r){const a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,s)=>by(t,e,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return FN(t)}}var FN=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function ZN(t,e){return{...We(t.innerType._def,e),default:t.defaultValue()}}function VN(t,e){return e.effectStrategy==="input"?We(t.schema._def,e):fr()}function HN(t){return{type:"string",enum:Array.from(t.values)}}var BN=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function JN(t,e){const r=[We(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),We(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(n=>!!n),a=[];return r.forEach(n=>{if(BN(n))a.push(...n.allOf);else{let s=n;if("additionalProperties"in n&&n.additionalProperties===!1){const{additionalProperties:o,...i}=n;s=i}a.push(s)}}),a.length?{allOf:a}:void 0}function GN(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var Fd=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:()=>(Fd===void 0&&(Fd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Fd),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 Ey(t,e){const r={type:"string"};if(t.checks)for(const a of t.checks)switch(a.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"email":switch(e.emailStrategy){case"format:email":Ur(r,"email",a.message,e);break;case"format:idn-email":Ur(r,"idn-email",a.message,e);break;case"pattern:zod":Wt(r,zr.email,a.message,e);break}break;case"url":Ur(r,"uri",a.message,e);break;case"uuid":Ur(r,"uuid",a.message,e);break;case"regex":Wt(r,a.regex,a.message,e);break;case"cuid":Wt(r,zr.cuid,a.message,e);break;case"cuid2":Wt(r,zr.cuid2,a.message,e);break;case"startsWith":Wt(r,RegExp(`^${Zd(a.value,e)}`),a.message,e);break;case"endsWith":Wt(r,RegExp(`${Zd(a.value,e)}$`),a.message,e);break;case"datetime":Ur(r,"date-time",a.message,e);break;case"date":Ur(r,"date",a.message,e);break;case"time":Ur(r,"time",a.message,e);break;case"duration":Ur(r,"duration",a.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"includes":{Wt(r,RegExp(Zd(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&Ur(r,"ipv4",a.message,e),a.version!=="v4"&&Ur(r,"ipv6",a.message,e);break}case"base64url":Wt(r,zr.base64url,a.message,e);break;case"jwt":Wt(r,zr.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&Wt(r,zr.ipv4Cidr,a.message,e),a.version!=="v4"&&Wt(r,zr.ipv6Cidr,a.message,e);break}case"emoji":Wt(r,zr.emoji(),a.message,e);break;case"ulid":{Wt(r,zr.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ur(r,"binary",a.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Wt(r,zr.base64,a.message,e);break}}break}case"nanoid":Wt(r,zr.nanoid,a.message,e)}return r}function Zd(t,e){return e.patternStrategy==="escape"?WN(t):t}var KN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function WN(t){let e="";for(let r=0;r<t.length;r++)KN.has(t[r])||(e+="\\"),e+=t[r];return e}function Ur(t,e,r,a){var n;t.format||(n=t.anyOf)!=null&&n.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&a.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function Wt(t,e,r,a){var n;t.pattern||(n=t.allOf)!=null&&n.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Sy(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Sy(e,a)}function Sy(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const a={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=a.i?t.source.toLowerCase():t.source;let s="",o=!1,i=!1,l=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(a.i){if(i){if(n[c].match(/[a-z]/)){l?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),l=!1):n[c+1]==="-"&&((r=n[c+2])!=null&&r.match(/[a-z]/))?(s+=n[c],l=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(a.m){if(n[c]==="^"){s+=`(^|(?<=[\r
502
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const m of this.seen.entries()){const p=m[1];if(e===m[0]){o(m);continue}if(a.external){const _=(h=a.external.registry.get(m[0]))==null?void 0:h.id;if(e!==m[0]&&_){o(m);continue}}if((g=this.metadataRegistry.get(m[0]))==null?void 0:g.id){o(m);continue}if(p.cycle){o(m);continue}if(p.count>1&&a.reused==="ref"){o(m);continue}}const i=(m,p)=>{const y=this.seen.get(m),_=y.def??y.schema,w={..._};if(y.ref===null)return;const E=y.ref;if(y.ref=null,E){i(E,p);const P=this.seen.get(E).schema;P.$ref&&p.target==="draft-7"?(_.allOf=_.allOf??[],_.allOf.push(P)):(Object.assign(_,P),Object.assign(_,w))}y.isParent||this.override({zodSchema:m,jsonSchema:_,path:y.path??[]})};for(const m of[...this.seen.entries()].reverse())i(m[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}`),(d=a.external)!=null&&d.uri){const m=(f=a.external.registry.get(e))==null?void 0:f.id;if(!m)throw new Error("Schema is missing an `id` property");l.$id=a.external.uri(m)}Object.assign(l,n.def);const c=((v=a.external)==null?void 0:v.defs)??{};for(const m of this.seen.entries()){const p=m[1];p.def&&p.defId&&(c[p.defId]=p.def)}a.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 m2(t,e){if(t instanceof Jg){const a=new ty(e),n={};for(const i of t._idmap.entries()){const[l,c]=i;a.process(c)}const s={},o={registry:t,uri:e==null?void 0:e.uri,defs:n};for(const i of t._idmap.entries()){const[l,c]=i;s[l]=a.emit(c,{...e,external:o})}if(Object.keys(n).length>0){const i=a.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[i]:n}}return{schemas:s}}const r=new ty(e);return r.process(t),r.emit(t,e)}function kt(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const n=t._zod.def;switch(n.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 kt(n.element,r);case"object":{for(const s in n.shape)if(kt(n.shape[s],r))return!0;return!1}case"union":{for(const s of n.options)if(kt(s,r))return!0;return!1}case"intersection":return kt(n.left,r)||kt(n.right,r);case"tuple":{for(const s of n.items)if(kt(s,r))return!0;return!!(n.rest&&kt(n.rest,r))}case"record":return kt(n.keyType,r)||kt(n.valueType,r);case"map":return kt(n.keyType,r)||kt(n.valueType,r);case"set":return kt(n.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return kt(n.innerType,r);case"lazy":return kt(n.getter(),r);case"default":return kt(n.innerType,r);case"prefault":return kt(n.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return kt(n.in,r)||kt(n.out,r);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${n.type}`)}const v2=B("ZodISODateTime",(t,e)=>{LR.init(t,e),pt.init(t,e)});function g2(t){return VO(v2,t)}const y2=B("ZodISODate",(t,e)=>{zR.init(t,e),pt.init(t,e)});function _2(t){return HO(y2,t)}const w2=B("ZodISOTime",(t,e)=>{UR.init(t,e),pt.init(t,e)});function b2(t){return BO(w2,t)}const E2=B("ZodISODuration",(t,e)=>{qR.init(t,e),pt.init(t,e)});function $2(t){return JO(E2,t)}const tl=B("ZodError",(t,e)=>{Sg.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>NC(t,r)},flatten:{value:r=>AC(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},{Parent:Error}),S2=MC(tl),P2=jC(tl),T2=Tg(tl),ry=xg(tl),ot=B("ZodType",(t,e)=>(et.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),t.clone=(r,a)=>Wn(t,r,a),t.brand=()=>t,t.register=(r,a)=>(r.add(t,a),t),t.parse=(r,a)=>S2(t,r,a,{callee:t.parse}),t.safeParse=(r,a)=>T2(t,r,a),t.parseAsync=async(r,a)=>P2(t,r,a,{callee:t.parseAsync}),t.safeParseAsync=async(r,a)=>ry(t,r,a),t.spa=t.safeParseAsync,t.refine=(r,a)=>t.check(wA(r,a)),t.superRefine=r=>t.check(bA(r)),t.overwrite=r=>t.check(eo(r)),t.optional=()=>St(t),t.nullable=()=>dy(t),t.nullish=()=>St(dy(t)),t.nonoptional=r=>dA(t,r),t.array=()=>ce(t),t.or=r=>Ve([t,r]),t.and=r=>tA(t,r),t.transform=r=>py(t,sA(r)),t.default=r=>lA(t,r),t.prefault=r=>uA(t,r),t.catch=r=>pA(t,r),t.pipe=r=>py(t,r),t.readonly=()=>vA(t),t.describe=r=>{const a=t.clone();return Xs.add(a,{description:r}),a},Object.defineProperty(t,"description",{get(){var r;return(r=Xs.get(t))==null?void 0:r.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Xs.get(t);const a=t.clone();return Xs.add(a,r[0]),a},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),ny=B("_ZodString",(t,e)=>{Pd.init(t,e),ot.init(t,e);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...a)=>t.check(r2(...a)),t.includes=(...a)=>t.check(s2(...a)),t.startsWith=(...a)=>t.check(o2(...a)),t.endsWith=(...a)=>t.check(i2(...a)),t.min=(...a)=>t.check(el(...a)),t.max=(...a)=>t.check(Xg(...a)),t.length=(...a)=>t.check(ey(...a)),t.nonempty=(...a)=>t.check(el(1,...a)),t.lowercase=a=>t.check(n2(a)),t.uppercase=a=>t.check(a2(a)),t.trim=()=>t.check(c2()),t.normalize=(...a)=>t.check(l2(...a)),t.toLowerCase=()=>t.check(u2()),t.toUpperCase=()=>t.check(d2())}),x2=B("ZodString",(t,e)=>{Pd.init(t,e),ny.init(t,e),t.email=r=>t.check(SO(k2,r)),t.url=r=>t.check(IO(I2,r)),t.jwt=r=>t.check(ZO(Z2,r)),t.emoji=r=>t.check(CO(C2,r)),t.guid=r=>t.check(Gg(ay,r)),t.uuid=r=>t.check(PO(rl,r)),t.uuidv4=r=>t.check(TO(rl,r)),t.uuidv6=r=>t.check(xO(rl,r)),t.uuidv7=r=>t.check(kO(rl,r)),t.nanoid=r=>t.check(RO(R2,r)),t.guid=r=>t.check(Gg(ay,r)),t.cuid=r=>t.check(OO(O2,r)),t.cuid2=r=>t.check(AO(A2,r)),t.ulid=r=>t.check(NO(N2,r)),t.base64=r=>t.check(Kg(sy,r)),t.base64url=r=>t.check(qO(q2,r)),t.xid=r=>t.check(MO(M2,r)),t.ksuid=r=>t.check(jO(j2,r)),t.ipv4=r=>t.check(DO(D2,r)),t.ipv6=r=>t.check(LO(L2,r)),t.cidrv4=r=>t.check(zO(z2,r)),t.cidrv6=r=>t.check(UO(U2,r)),t.e164=r=>t.check(FO(F2,r)),t.datetime=r=>t.check(g2(r)),t.date=r=>t.check(_2(r)),t.time=r=>t.check(b2(r)),t.duration=r=>t.check($2(r))});function S(t){return $O(x2,t)}const pt=B("ZodStringFormat",(t,e)=>{ct.init(t,e),ny.init(t,e)}),k2=B("ZodEmail",(t,e)=>{IR.init(t,e),pt.init(t,e)}),ay=B("ZodGUID",(t,e)=>{xR.init(t,e),pt.init(t,e)}),rl=B("ZodUUID",(t,e)=>{kR.init(t,e),pt.init(t,e)}),I2=B("ZodURL",(t,e)=>{CR.init(t,e),pt.init(t,e)}),C2=B("ZodEmoji",(t,e)=>{RR.init(t,e),pt.init(t,e)}),R2=B("ZodNanoID",(t,e)=>{OR.init(t,e),pt.init(t,e)}),O2=B("ZodCUID",(t,e)=>{AR.init(t,e),pt.init(t,e)}),A2=B("ZodCUID2",(t,e)=>{NR.init(t,e),pt.init(t,e)}),N2=B("ZodULID",(t,e)=>{MR.init(t,e),pt.init(t,e)}),M2=B("ZodXID",(t,e)=>{jR.init(t,e),pt.init(t,e)}),j2=B("ZodKSUID",(t,e)=>{DR.init(t,e),pt.init(t,e)}),D2=B("ZodIPv4",(t,e)=>{FR.init(t,e),pt.init(t,e)}),L2=B("ZodIPv6",(t,e)=>{ZR.init(t,e),pt.init(t,e)}),z2=B("ZodCIDRv4",(t,e)=>{VR.init(t,e),pt.init(t,e)}),U2=B("ZodCIDRv6",(t,e)=>{HR.init(t,e),pt.init(t,e)}),sy=B("ZodBase64",(t,e)=>{BR.init(t,e),pt.init(t,e)});function oy(t){return Kg(sy,t)}const q2=B("ZodBase64URL",(t,e)=>{GR.init(t,e),pt.init(t,e)}),F2=B("ZodE164",(t,e)=>{KR.init(t,e),pt.init(t,e)}),Z2=B("ZodJWT",(t,e)=>{QR.init(t,e),pt.init(t,e)}),Id=B("ZodNumber",(t,e)=>{jg.init(t,e),ot.init(t,e),t.gt=(a,n)=>t.check(Qg(a,n)),t.gte=(a,n)=>t.check(kd(a,n)),t.min=(a,n)=>t.check(kd(a,n)),t.lt=(a,n)=>t.check(Wg(a,n)),t.lte=(a,n)=>t.check(xd(a,n)),t.max=(a,n)=>t.check(xd(a,n)),t.int=a=>t.check(iy(a)),t.safe=a=>t.check(iy(a)),t.positive=a=>t.check(Qg(0,a)),t.nonnegative=a=>t.check(kd(0,a)),t.negative=a=>t.check(Wg(0,a)),t.nonpositive=a=>t.check(xd(0,a)),t.multipleOf=(a,n)=>t.check(Yg(a,n)),t.step=(a,n)=>t.check(Yg(a,n)),t.finite=()=>t;const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function K(t){return GO(Id,t)}const V2=B("ZodNumberFormat",(t,e)=>{YR.init(t,e),Id.init(t,e)});function iy(t){return WO(V2,t)}const H2=B("ZodBoolean",(t,e)=>{XR.init(t,e),ot.init(t,e)});function $t(t){return QO(H2,t)}const B2=B("ZodNull",(t,e)=>{eO.init(t,e),ot.init(t,e)});function J2(t){return YO(B2,t)}const G2=B("ZodAny",(t,e)=>{tO.init(t,e),ot.init(t,e)});function pr(){return XO(G2)}const K2=B("ZodUnknown",(t,e)=>{rO.init(t,e),ot.init(t,e)});function Cn(){return e2(K2)}const W2=B("ZodNever",(t,e)=>{nO.init(t,e),ot.init(t,e)});function Q2(t){return t2(W2,t)}const Y2=B("ZodArray",(t,e)=>{aO.init(t,e),ot.init(t,e),t.element=e.element,t.min=(r,a)=>t.check(el(r,a)),t.nonempty=r=>t.check(el(1,r)),t.max=(r,a)=>t.check(Xg(r,a)),t.length=(r,a)=>t.check(ey(r,a)),t.unwrap=()=>t.element});function ce(t,e){return f2(Y2,t,e)}const ly=B("ZodObject",(t,e)=>{sO.init(t,e),ot.init(t,e),Je(t,"shape",()=>e.shape),t.keyof=()=>zt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Cn()}),t.loose=()=>t.clone({...t._zod.def,catchall:Cn()}),t.strict=()=>t.clone({...t._zod.def,catchall:Q2()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>IC(t,r),t.merge=r=>CC(t,r),t.pick=r=>xC(t,r),t.omit=r=>kC(t,r),t.partial=(...r)=>RC(uy,t,r[0]),t.required=(...r)=>OC(fy,t,r[0])});function R(t,e){const r={type:"object",get shape(){return Gi(this,"shape",{...t}),this.shape},...de(e)};return new ly(r)}function Ba(t,e){return new ly({type:"object",get shape(){return Gi(this,"shape",{...t}),this.shape},catchall:Cn(),...de(e)})}const cy=B("ZodUnion",(t,e)=>{Ug.init(t,e),ot.init(t,e),t.options=e.options});function Ve(t,e){return new cy({type:"union",options:t,...de(e)})}const X2=B("ZodDiscriminatedUnion",(t,e)=>{cy.init(t,e),oO.init(t,e)});function Ja(t,e,r){return new X2({type:"union",options:e,discriminator:t,...de(r)})}const eA=B("ZodIntersection",(t,e)=>{iO.init(t,e),ot.init(t,e)});function tA(t,e){return new eA({type:"intersection",left:t,right:e})}const rA=B("ZodRecord",(t,e)=>{lO.init(t,e),ot.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Qt(t,e,r){return new rA({type:"record",keyType:t,valueType:e,...de(r)})}const Cd=B("ZodEnum",(t,e)=>{cO.init(t,e),ot.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(a,n)=>{const s={};for(const o of a)if(r.has(o))s[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Cd({...e,checks:[],...de(n),entries:s})},t.exclude=(a,n)=>{const s={...e.entries};for(const o of a)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new Cd({...e,checks:[],...de(n),entries:s})}});function zt(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(a=>[a,a])):t;return new Cd({type:"enum",entries:r,...de(e)})}const nA=B("ZodLiteral",(t,e)=>{uO.init(t,e),ot.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ne(t,e){return new nA({type:"literal",values:Array.isArray(t)?t:[t],...de(e)})}const aA=B("ZodTransform",(t,e)=>{dO.init(t,e),ot.init(t,e),t._zod.parse=(r,a)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(Ys(s,r.value,e));else{const o=s;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=!0),r.issues.push(Ys(o))}};const n=e.transform(r.value,r);return n instanceof Promise?n.then(s=>(r.value=s,r)):(r.value=n,r)}});function sA(t){return new aA({type:"transform",transform:t})}const uy=B("ZodOptional",(t,e)=>{fO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function St(t){return new uy({type:"optional",innerType:t})}const oA=B("ZodNullable",(t,e)=>{pO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function dy(t){return new oA({type:"nullable",innerType:t})}const iA=B("ZodDefault",(t,e)=>{hO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function lA(t,e){return new iA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const cA=B("ZodPrefault",(t,e)=>{mO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function uA(t,e){return new cA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}const fy=B("ZodNonOptional",(t,e)=>{vO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType});function dA(t,e){return new fy({type:"nonoptional",innerType:t,...de(e)})}const fA=B("ZodCatch",(t,e)=>{gO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function pA(t,e){return new fA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const hA=B("ZodPipe",(t,e)=>{yO.init(t,e),ot.init(t,e),t.in=e.in,t.out=e.out});function py(t,e){return new hA({type:"pipe",in:t,out:e})}const mA=B("ZodReadonly",(t,e)=>{_O.init(t,e),ot.init(t,e)});function vA(t){return new mA({type:"readonly",innerType:t})}const gA=B("ZodLazy",(t,e)=>{wO.init(t,e),ot.init(t,e),t.unwrap=()=>t._zod.def.getter()});function hy(t){return new gA({type:"lazy",getter:t})}const Rd=B("ZodCustom",(t,e)=>{bO.init(t,e),ot.init(t,e)});function yA(t){const e=new Wt({check:"custom"});return e._zod.check=t,e}function _A(t,e){return p2(Rd,t??(()=>!0),e)}function wA(t,e={}){return h2(Rd,t,e)}function bA(t){const e=yA(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(Ys(a,r.value,e._zod.def));else{const n=a;n.fatal&&(n.continue=!1),n.code??(n.code="custom"),n.input??(n.input=r.value),n.inst??(n.inst=e),n.continue??(n.continue=!e._zod.def.abort),r.issues.push(Ys(n))}},t(r.value,r)));return e}function nl(t,e={error:`Input not instance of ${t.name}`}){const r=new Rd({type:"custom",check:"custom",fn:a=>a instanceof t,abort:!0,...de(e)});return r._zod.bag.Class=t,r}function EA(t){return KO(Id,t)}function Od(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}async function $A(t,e){if(t==null)return Promise.resolve();const r=e==null?void 0:e.abortSignal;return new Promise((a,n)=>{if(r!=null&&r.aborted){n(my());return}const s=setTimeout(()=>{o(),a()},t),o=()=>{clearTimeout(s),r==null||r.removeEventListener("abort",i)},i=()=>{o(),n(my())};r==null||r.addEventListener("abort",i)})}function my(){return new DOMException("Delay was aborted","AbortError")}function to(t){return Object.fromEntries([...t.headers])}var ro=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{const n=()=>{const s=r.length,o=new Array(e);for(let i=0;i<e;i++)o[i]=r[Math.random()*s|0];return o.join("")};if(t==null)return n;if(r.includes(a))throw new yd({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${t}${a}${n()}`},SA=ro();function Ad(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}function Yn(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var PA=["fetch failed","failed to fetch"];function vy({error:t,url:e,requestBodyValues:r}){if(Yn(t))return t;if(t instanceof TypeError&&PA.includes(t.message.toLowerCase())){const a=t.cause;if(a!=null)return new Xe({message:`Cannot connect to API: ${a.message}`,cause:a,url:e,requestBodyValues:r,isRetryable:!0})}return t}function Nd(t=globalThis){var e,r,a;return t.window?"runtime/browser":(e=t.navigator)!=null&&e.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(a=(r=t.process)==null?void 0:r.versions)!=null&&a.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function TA(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function no(t,...e){const r=TA(t??{}),a=new Headers(r),n=a.get("user-agent")||"";return a.set("user-agent",[n,...e].filter(Boolean).join(" ")),Object.fromEntries(a)}var gy="3.0.12",xA=()=>globalThis.fetch,yy=async({url:t,headers:e={},successfulResponseHandler:r,failedResponseHandler:a,abortSignal:n,fetch:s=xA()})=>{try{const o=await s(t,{method:"GET",headers:no(e,`ai-sdk/provider-utils/${gy}`,Nd()),signal:n}),i=to(o);if(!o.ok){let l;try{l=await a({response:o,url:t,requestBodyValues:{}})}catch(c){throw Yn(c)||Xe.isInstance(c)?c:new Xe({message:"Failed to process error response",cause:c,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}throw l.value}try{return await r({response:o,url:t,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Yn(l)||Xe.isInstance(l))?l:new Xe({message:"Failed to process successful response",cause:l,statusCode:o.status,url:t,responseHeaders:i,requestBodyValues:{}})}}catch(o){throw vy({error:o,url:t,requestBodyValues:{}})}};function kA({mediaType:t,url:e,supportedUrls:r}){return e=e.toLowerCase(),t=t.toLowerCase(),Object.entries(r).map(([a,n])=>{const s=a.toLowerCase();return s==="*"||s==="*/*"?{mediaTypePrefix:"",regexes:n}:{mediaTypePrefix:s.replace(/\*/,""),regexes:n}}).filter(({mediaTypePrefix:a})=>t.startsWith(a)).flatMap(({regexes:a})=>a).some(a=>a.test(e))}function al({settingValue:t,environmentVariableName:e}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[e],!(t==null||typeof t!="string")))return t}var IA=/"__proto__"\s*:/,CA=/"constructor"\s*:/;function RA(t){const e=JSON.parse(t);return e===null||typeof e!="object"||IA.test(t)===!1&&CA.test(t)===!1?e:OA(e)}function OA(t){let e=[t];for(;e.length;){const r=e;e=[];for(const a of r){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in a){const s=a[n];s&&typeof s=="object"&&e.push(s)}}}return t}function _y(t){const{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return RA(t)}finally{Error.stackTraceLimit=e}}var sl=Symbol.for("vercel.ai.validator");function AA(t){return{[sl]:!0,validate:t}}function NA(t){return typeof t=="object"&&t!==null&&sl in t&&t[sl]===!0&&"validate"in t}function Ga(t){let e;return()=>(e==null&&(e=t()),e)}function MA(t){return NA(t)?t:typeof t=="function"?t():jA(t)}function jA(t){return AA(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Br({value:e,cause:r.issues})}})}async function Md({value:t,schema:e}){const r=await Rn({value:t,schema:e});if(!r.success)throw Br.wrap({value:t,cause:r.error});return r.value}async function Rn({value:t,schema:e}){const r=MA(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const a=await r.validate(t);return a.success?{success:!0,value:a.value,rawValue:t}:{success:!1,error:Br.wrap({value:t,cause:a.error}),rawValue:t}}catch(a){return{success:!1,error:Br.wrap({value:t,cause:a}),rawValue:t}}}async function DA({text:t,schema:e}){try{const r=_y(t);return e==null?r:Md({value:r,schema:e})}catch(r){throw xn.isInstance(r)||Br.isInstance(r)?r:new xn({text:t,cause:r})}}async function Xn({text:t,schema:e}){try{const r=_y(t);return e==null?{success:!0,value:r,rawValue:r}:await Rn({value:r,schema:e})}catch(r){return{success:!1,error:xn.isInstance(r)?r:new xn({text:t,cause:r}),rawValue:void 0}}}function LA({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new wC).pipeThrough(new TransformStream({async transform({data:r},a){r!=="[DONE]"&&a.enqueue(await Xn({text:r,schema:e}))}}))}var zA=()=>globalThis.fetch,jd=async({url:t,headers:e,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>UA({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),UA=async({url:t,headers:e={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:s,fetch:o=zA()})=>{try{const i=await o(t,{method:"POST",headers:no(e,`ai-sdk/provider-utils/${gy}`,Nd()),body:r.content,signal:s}),l=to(i);if(!i.ok){let c;try{c=await n({response:i,url:t,requestBodyValues:r.values})}catch(u){throw Yn(u)||Xe.isInstance(u)?u:new Xe({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await a({response:i,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(Yn(c)||Xe.isInstance(c))?c:new Xe({message:"Failed to process successful response",cause:c,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw vy({error:i,url:t,requestBodyValues:r.values})}};function qA(t){return{...t,type:"dynamic"}}async function On(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var ao=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:a,url:n,requestBodyValues:s})=>{const o=await a.text(),i=to(a);if(o.trim()==="")return{responseHeaders:i,value:new Xe({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})};try{const l=await DA({text:o,schema:t});return{responseHeaders:i,value:new Xe({message:e(l),url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,data:l,isRetryable:r==null?void 0:r(a,l)})}}catch{return{responseHeaders:i,value:new Xe({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})}}},FA=t=>async({response:e})=>{const r=to(e);if(e.body==null)throw new Hv({});return{responseHeaders:r,value:LA({stream:e.body,schema:t})}},ol=t=>async({response:e,url:r,requestBodyValues:a})=>{const n=await e.text(),s=await Xn({text:n,schema:t}),o=to(e);if(!s.success)throw new Xe({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:o,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},ZA=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},VA=Symbol("Let zodToJsonSchema decide on which parser to use"),wy={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"},HA=t=>typeof t=="string"?{...wy,name:t}:{...wy,...t};function ar(){return{}}function BA(t,e){var r,a,n;const s={type:"array"};return(r=t.type)!=null&&r._def&&((n=(a=t.type)==null?void 0:a._def)==null?void 0:n.typeName)!==V.ZodAny&&(s.items=Ke(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&(s.minItems=t.minLength.value),t.maxLength&&(s.maxItems=t.maxLength.value),t.exactLength&&(s.minItems=t.exactLength.value,s.maxItems=t.exactLength.value),s}function JA(t){const e={type:"integer",format:"int64"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function GA(){return{type:"boolean"}}function by(t,e){return Ke(t.type._def,e)}var KA=(t,e)=>Ke(t.innerType._def,e);function Ey(t,e,r){const a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((n,s)=>Ey(t,e,n))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return WA(t)}}var WA=t=>{const e={type:"integer",format:"unix-time"};for(const r of t.checks)switch(r.kind){case"min":e.minimum=r.value;break;case"max":e.maximum=r.value;break}return e};function QA(t,e){return{...Ke(t.innerType._def,e),default:t.defaultValue()}}function YA(t,e){return e.effectStrategy==="input"?Ke(t.schema._def,e):ar()}function XA(t){return{type:"string",enum:Array.from(t.values)}}var eN=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function tN(t,e){const r=[Ke(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Ke(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(n=>!!n),a=[];return r.forEach(n=>{if(eN(n))a.push(...n.allOf);else{let s=n;if("additionalProperties"in n&&n.additionalProperties===!1){const{additionalProperties:o,...i}=n;s=i}a.push(s)}}),a.length?{allOf:a}:void 0}function rN(t){const e=typeof t.value;return e!=="bigint"&&e!=="number"&&e!=="boolean"&&e!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:e==="bigint"?"integer":e,const:t.value}}var Dd=void 0,Ir={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:()=>(Dd===void 0&&(Dd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Dd),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 $y(t,e){const r={type:"string"};if(t.checks)for(const a of t.checks)switch(a.kind){case"min":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value;break;case"max":r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"email":switch(e.emailStrategy){case"format:email":Cr(r,"email",a.message,e);break;case"format:idn-email":Cr(r,"idn-email",a.message,e);break;case"pattern:zod":Zt(r,Ir.email,a.message,e);break}break;case"url":Cr(r,"uri",a.message,e);break;case"uuid":Cr(r,"uuid",a.message,e);break;case"regex":Zt(r,a.regex,a.message,e);break;case"cuid":Zt(r,Ir.cuid,a.message,e);break;case"cuid2":Zt(r,Ir.cuid2,a.message,e);break;case"startsWith":Zt(r,RegExp(`^${Ld(a.value,e)}`),a.message,e);break;case"endsWith":Zt(r,RegExp(`${Ld(a.value,e)}$`),a.message,e);break;case"datetime":Cr(r,"date-time",a.message,e);break;case"date":Cr(r,"date",a.message,e);break;case"time":Cr(r,"time",a.message,e);break;case"duration":Cr(r,"duration",a.message,e);break;case"length":r.minLength=typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,r.maxLength=typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value;break;case"includes":{Zt(r,RegExp(Ld(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&Cr(r,"ipv4",a.message,e),a.version!=="v4"&&Cr(r,"ipv6",a.message,e);break}case"base64url":Zt(r,Ir.base64url,a.message,e);break;case"jwt":Zt(r,Ir.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&Zt(r,Ir.ipv4Cidr,a.message,e),a.version!=="v4"&&Zt(r,Ir.ipv6Cidr,a.message,e);break}case"emoji":Zt(r,Ir.emoji(),a.message,e);break;case"ulid":{Zt(r,Ir.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Cr(r,"binary",a.message,e);break}case"contentEncoding:base64":{r.contentEncoding="base64";break}case"pattern:zod":{Zt(r,Ir.base64,a.message,e);break}}break}case"nanoid":Zt(r,Ir.nanoid,a.message,e)}return r}function Ld(t,e){return e.patternStrategy==="escape"?aN(t):t}var nN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function aN(t){let e="";for(let r=0;r<t.length;r++)nN.has(t[r])||(e+="\\"),e+=t[r];return e}function Cr(t,e,r,a){var n;t.format||(n=t.anyOf)!=null&&n.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:e,...r&&a.errorMessages&&{errorMessage:{format:r}}})):t.format=e}function Zt(t,e,r,a){var n;t.pattern||(n=t.allOf)!=null&&n.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Sy(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):t.pattern=Sy(e,a)}function Sy(t,e){var r;if(!e.applyRegexFlags||!t.flags)return t.source;const a={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=a.i?t.source.toLowerCase():t.source;let s="",o=!1,i=!1,l=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(a.i){if(i){if(n[c].match(/[a-z]/)){l?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),l=!1):n[c+1]==="-"&&((r=n[c+2])!=null&&r.match(/[a-z]/))?(s+=n[c],l=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(a.m){if(n[c]==="^"){s+=`(^|(?<=[\r
499
503
  ]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
500
504
  ]))`;continue}}if(a.s&&n[c]==="."){s+=i?`${n[c]}\r
501
505
  `:`[${n[c]}\r
502
- ]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function $y(t,e){var r,a,n,s,o,i;const l={type:"object",additionalProperties:(r=We(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((a=t.keyType)==null?void 0:a._def.typeName)===V.ZodString&&((n=t.keyType._def.checks)!=null&&n.length)){const{type:c,...u}=Ey(t.keyType._def,e);return{...l,propertyNames:u}}else{if(((s=t.keyType)==null?void 0:s._def.typeName)===V.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===V.ZodBranded&&t.keyType._def.type._def.typeName===V.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=wy(t.keyType._def,e);return{...l,propertyNames:u}}}return l}function QN(t,e){if(e.mapStrategy==="record")return $y(t,e);const r=We(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||fr(),a=We(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||fr();return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function YN(t){const e=t.values,a=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(a.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}function XN(){return{not:fr()}}function eA(){return{type:"null"}}var Vd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function tA(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(a=>a._def.typeName in Vd&&(!a._def.checks||!a._def.checks.length))){const a=r.reduce((n,s)=>{const o=Vd[s._def.typeName];return o&&!n.includes(o)?[...n,o]:n},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=r.reduce((n,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...n,o];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(a.length===r.length){const n=a.filter((s,o,i)=>i.indexOf(s)===o);return{type:n.length>1?n:n[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,n)=>[...a,...n._def.values.filter(s=>!a.includes(s))],[])};return rA(t,e)}var rA=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,n)=>We(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function nA(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Vd[t.innerType._def.typeName],"null"]};const r=We(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function aA(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function sA(t,e){const r={type:"object",properties:{}},a=[],n=t.shape();for(const o in n){let i=n[o];if(i===void 0||i._def===void 0)continue;const l=iA(i),c=We(i._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});c!==void 0&&(r.properties[o]=c,l||a.push(o))}a.length&&(r.required=a);const s=oA(t,e);return s!==void 0&&(r.additionalProperties=s),r}function oA(t,e){if(t.catchall._def.typeName!=="ZodNever")return We(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function iA(t){try{return t.isOptional()}catch{return!0}}var lA=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return We(t.innerType._def,e);const a=We(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return a?{anyOf:[{not:fr()},a]}:fr()},cA=(t,e)=>{if(e.pipeStrategy==="input")return We(t.in._def,e);if(e.pipeStrategy==="output")return We(t.out._def,e);const r=We(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=We(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(n=>n!==void 0)}};function uA(t,e){return We(t.type._def,e)}function dA(t,e){const a={type:"array",uniqueItems:!0,items:We(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(a.minItems=t.minSize.value),t.maxSize&&(a.maxItems=t.maxSize.value),a}function pA(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,a)=>We(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),additionalItems:We(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,a)=>We(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function fA(){return{not:fr()}}function hA(){return fr()}var mA=(t,e)=>We(t.innerType._def,e),vA=(t,e,r)=>{switch(e){case V.ZodString:return Ey(t,r);case V.ZodNumber:return aA(t);case V.ZodObject:return sA(t,r);case V.ZodBigInt:return zN(t);case V.ZodBoolean:return UN();case V.ZodDate:return by(t,r);case V.ZodUndefined:return fA();case V.ZodNull:return eA();case V.ZodArray:return LN(t,r);case V.ZodUnion:case V.ZodDiscriminatedUnion:return tA(t,r);case V.ZodIntersection:return JN(t,r);case V.ZodTuple:return pA(t,r);case V.ZodRecord:return $y(t,r);case V.ZodLiteral:return GN(t);case V.ZodEnum:return HN(t);case V.ZodNativeEnum:return YN(t);case V.ZodNullable:return nA(t,r);case V.ZodOptional:return lA(t,r);case V.ZodMap:return QN(t,r);case V.ZodSet:return dA(t,r);case V.ZodLazy:return()=>t.getter()._def;case V.ZodPromise:return uA(t,r);case V.ZodNaN:case V.ZodNever:return XN();case V.ZodEffects:return VN(t,r);case V.ZodAny:return fr();case V.ZodUnknown:return hA();case V.ZodDefault:return ZN(t,r);case V.ZodBranded:return wy(t,r);case V.ZodReadonly:return mA(t,r);case V.ZodCatch:return qN(t,r);case V.ZodPipeline:return cA(t,r);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return(a=>{})()}};function We(t,e,r=!1){var a;const n=e.seen.get(t);if(e.override){const l=(a=e.override)==null?void 0:a.call(e,t,e,n,r);if(l!==jN)return l}if(n&&!r){const l=gA(n,e);if(l!==void 0)return l}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=vA(t,t.typeName,e),i=typeof o=="function"?We(o(),e):o;if(i&&yA(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var gA=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:MN(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),fr()):e.$refStrategy==="seen"?fr():void 0}},yA=(t,e,r)=>(t.description&&(r.description=t.description),r),_A=t=>{const e=DN(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}},wA=(t,e)=>{var r;const a=_A(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,f])=>{var g;return{...c,[u]:(g=We(f._def,{...a,currentPath:[...a.basePath,a.definitionPath,u]},!0))!=null?g:fr()}},{}):void 0;const s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,o=(r=We(t._def,s===void 0?a:{...a,currentPath:[...a.basePath,a.definitionPath,s]},!1))!=null?r:fr(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);const l=s===void 0?n?{...o,[a.definitionPath]:n}:o:{$ref:[...a.$refStrategy==="relative"?[]:a.basePath,a.definitionPath,s].join("/"),[a.definitionPath]:{...n,[s]:o}};return l.$schema="http://json-schema.org/draft-07/schema#",l},bA=wA;function EA(t,e){var r;const a=(r=void 0)!=null?r:!1;return po(()=>bA(t,{$refStrategy:a?"root":"none"}),{validate:async n=>{const s=await t.safeParseAsync(n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function SA(t,e){var r;const a=(r=void 0)!=null?r:!1;return po(()=>l2(t,{target:"draft-7",io:"output",reused:a?"ref":"inline"}),{validate:async n=>{const s=await Xg(t,n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function $A(t){return"_zod"in t}function De(t,e){return $A(t)?SA(t):EA(t)}var Hd=Symbol.for("vercel.ai.schema");function Ht(t){let e;return()=>(e==null&&(e=t()),e)}function po(t,{validate:e}={}){return{[Hd]:!0,_type:void 0,[ml]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function PA(t){return typeof t=="object"&&t!==null&&Hd in t&&t[Hd]===!0&&"jsonSchema"in t&&"validate"in t}function gl(t){return t==null?po({properties:{},additionalProperties:!1}):PA(t)?t:typeof t=="function"?t():De(t)}var{btoa:kA,atob:IA}=globalThis;function yl(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=IA(e);return Uint8Array.from(r,a=>a.codePointAt(0))}function _l(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return kA(e)}function la(t){return t instanceof Uint8Array?_l(t):t}function Bd(t){return t==null?void 0:t.replace(/\/$/,"")}function xA(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*Py({execute:t,input:e,options:r}){const a=t(e,r);if(xA(a)){let n;for await(const s of a)n=s,yield{type:"preliminary",output:s};yield{type:"final",output:n}}else yield{type:"final",output:await a}}var Jd=Object.defineProperty,TA=Object.getOwnPropertyDescriptor,CA=Object.getOwnPropertyNames,RA=Object.prototype.hasOwnProperty,OA=(t,e)=>{for(var r in e)Jd(t,r,{get:e[r],enumerable:!0})},NA=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of CA(e))!RA.call(t,n)&&n!==r&&Jd(t,n,{get:()=>e[n],enumerable:!(a=TA(e,n))||a.enumerable});return t},AA=t=>NA(Jd({},"__esModule",{value:!0}),t),ky={};OA(ky,{SYMBOL_FOR_REQ_CONTEXT:()=>Iy,getContext:()=>jA});var MA=AA(ky);const Iy=Symbol.for("@vercel/request-context");function jA(){var e,r;return((r=(e=globalThis[Iy])==null?void 0:e.get)==null?void 0:r.call(e))??{}}var Gd=Object.defineProperty,DA=Object.getOwnPropertyDescriptor,LA=Object.getOwnPropertyNames,zA=Object.prototype.hasOwnProperty,UA=(t,e)=>{for(var r in e)Gd(t,r,{get:e[r],enumerable:!0})},qA=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of LA(e))!zA.call(t,n)&&n!==r&&Gd(t,n,{get:()=>e[n],enumerable:!(a=DA(e,n))||a.enumerable});return t},FA=t=>qA(Gd({},"__esModule",{value:!0}),t),xy={};UA(xy,{getContext:()=>ZA.getContext,getVercelOidcToken:()=>VA,getVercelOidcTokenSync:()=>HA});var Ty=FA(xy),ZA=MA;async function VA(){return""}function HA(){return""}var BA="vercel.ai.gateway.error",Kd=Symbol.for(BA),Cy,Ry,hr=class iw extends(Ry=Error,Cy=Kd,Ry){constructor({message:e,statusCode:r=500,cause:a}){super(e),this[Cy]=!0,this.statusCode=r,this.cause=a}static isInstance(e){return iw.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&Kd in e&&e[Kd]===!0}},Oy="GatewayAuthenticationError",JA=`vercel.ai.gateway.error.${Oy}`,Ny=Symbol.for(JA),Ay,My,Wd=class lw extends(My=hr,Ay=Ny,My){constructor({message:e="Authentication failed",statusCode:r=401,cause:a}={}){super({message:e,statusCode:r,cause:a}),this[Ay]=!0,this.name=Oy,this.type="authentication_error"}static isInstance(e){return hr.hasMarker(e)&&Ny in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:a="Authentication failed",statusCode:n=401,cause:s}){let o;return e?o=`AI Gateway authentication failed: Invalid API key.
506
+ ]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function Py(t,e){var r,a,n,s,o,i;const l={type:"object",additionalProperties:(r=Ke(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]}))!=null?r:e.allowedAdditionalProperties};if(((a=t.keyType)==null?void 0:a._def.typeName)===V.ZodString&&((n=t.keyType._def.checks)!=null&&n.length)){const{type:c,...u}=$y(t.keyType._def,e);return{...l,propertyNames:u}}else{if(((s=t.keyType)==null?void 0:s._def.typeName)===V.ZodEnum)return{...l,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===V.ZodBranded&&t.keyType._def.type._def.typeName===V.ZodString&&((i=t.keyType._def.type._def.checks)!=null&&i.length)){const{type:c,...u}=by(t.keyType._def,e);return{...l,propertyNames:u}}}return l}function sN(t,e){if(e.mapStrategy==="record")return Py(t,e);const r=Ke(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ar(),a=Ke(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ar();return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function oN(t){const e=t.values,a=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),n=Array.from(new Set(a.map(s=>typeof s)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:a}}function iN(){return{not:ar()}}function lN(){return{type:"null"}}var zd={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function cN(t,e){const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(a=>a._def.typeName in zd&&(!a._def.checks||!a._def.checks.length))){const a=r.reduce((n,s)=>{const o=zd[s._def.typeName];return o&&!n.includes(o)?[...n,o]:n},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=r.reduce((n,s)=>{const o=typeof s._def.value;switch(o){case"string":case"number":case"boolean":return[...n,o];case"bigint":return[...n,"integer"];case"object":if(s._def.value===null)return[...n,"null"];case"symbol":case"undefined":case"function":default:return n}},[]);if(a.length===r.length){const n=a.filter((s,o,i)=>i.indexOf(s)===o);return{type:n.length>1?n:n[0],enum:r.reduce((s,o)=>s.includes(o._def.value)?s:[...s,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,n)=>[...a,...n._def.values.filter(s=>!a.includes(s))],[])};return uN(t,e)}var uN=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,n)=>Ke(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function dN(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[zd[t.innerType._def.typeName],"null"]};const r=Ke(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function fN(t){const e={type:"number"};if(!t.checks)return e;for(const r of t.checks)switch(r.kind){case"int":e.type="integer";break;case"min":r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value;break;case"max":r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value;break;case"multipleOf":e.multipleOf=r.value;break}return e}function pN(t,e){const r={type:"object",properties:{}},a=[],n=t.shape();for(const o in n){let i=n[o];if(i===void 0||i._def===void 0)continue;const l=mN(i),c=Ke(i._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});c!==void 0&&(r.properties[o]=c,l||a.push(o))}a.length&&(r.required=a);const s=hN(t,e);return s!==void 0&&(r.additionalProperties=s),r}function hN(t,e){if(t.catchall._def.typeName!=="ZodNever")return Ke(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function mN(t){try{return t.isOptional()}catch{return!0}}var vN=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return Ke(t.innerType._def,e);const a=Ke(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return a?{anyOf:[{not:ar()},a]}:ar()},gN=(t,e)=>{if(e.pipeStrategy==="input")return Ke(t.in._def,e);if(e.pipeStrategy==="output")return Ke(t.out._def,e);const r=Ke(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=Ke(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(n=>n!==void 0)}};function yN(t,e){return Ke(t.type._def,e)}function _N(t,e){const a={type:"array",uniqueItems:!0,items:Ke(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&(a.minItems=t.minSize.value),t.maxSize&&(a.maxItems=t.maxSize.value),a}function wN(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,a)=>Ke(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),additionalItems:Ke(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,a)=>Ke(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function bN(){return{not:ar()}}function EN(){return ar()}var $N=(t,e)=>Ke(t.innerType._def,e),SN=(t,e,r)=>{switch(e){case V.ZodString:return $y(t,r);case V.ZodNumber:return fN(t);case V.ZodObject:return pN(t,r);case V.ZodBigInt:return JA(t);case V.ZodBoolean:return GA();case V.ZodDate:return Ey(t,r);case V.ZodUndefined:return bN();case V.ZodNull:return lN();case V.ZodArray:return BA(t,r);case V.ZodUnion:case V.ZodDiscriminatedUnion:return cN(t,r);case V.ZodIntersection:return tN(t,r);case V.ZodTuple:return wN(t,r);case V.ZodRecord:return Py(t,r);case V.ZodLiteral:return rN(t);case V.ZodEnum:return XA(t);case V.ZodNativeEnum:return oN(t);case V.ZodNullable:return dN(t,r);case V.ZodOptional:return vN(t,r);case V.ZodMap:return sN(t,r);case V.ZodSet:return _N(t,r);case V.ZodLazy:return()=>t.getter()._def;case V.ZodPromise:return yN(t,r);case V.ZodNaN:case V.ZodNever:return iN();case V.ZodEffects:return YA(t,r);case V.ZodAny:return ar();case V.ZodUnknown:return EN();case V.ZodDefault:return QA(t,r);case V.ZodBranded:return by(t,r);case V.ZodReadonly:return $N(t,r);case V.ZodCatch:return KA(t,r);case V.ZodPipeline:return gN(t,r);case V.ZodFunction:case V.ZodVoid:case V.ZodSymbol:return;default:return(a=>{})()}};function Ke(t,e,r=!1){var a;const n=e.seen.get(t);if(e.override){const l=(a=e.override)==null?void 0:a.call(e,t,e,n,r);if(l!==VA)return l}if(n&&!r){const l=PN(n,e);if(l!==void 0)return l}const s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);const o=SN(t,t.typeName,e),i=typeof o=="function"?Ke(o(),e):o;if(i&&TN(t,e,i),e.postProcess){const l=e.postProcess(i,t,e);return s.jsonSchema=i,l}return s.jsonSchema=i,i}var PN=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ZA(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ar()):e.$refStrategy==="seen"?ar():void 0}},TN=(t,e,r)=>(t.description&&(r.description=t.description),r),xN=t=>{const e=HA(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,n])=>[n._def,{def:n._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}},kN=(t,e)=>{var r;const a=xN(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,h])=>{var g;return{...c,[u]:(g=Ke(h._def,{...a,currentPath:[...a.basePath,a.definitionPath,u]},!0))!=null?g:ar()}},{}):void 0;const s=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,o=(r=Ke(t._def,s===void 0?a:{...a,currentPath:[...a.basePath,a.definitionPath,s]},!1))!=null?r:ar(),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);const l=s===void 0?n?{...o,[a.definitionPath]:n}:o:{$ref:[...a.$refStrategy==="relative"?[]:a.basePath,a.definitionPath,s].join("/"),[a.definitionPath]:{...n,[s]:o}};return l.$schema="http://json-schema.org/draft-07/schema#",l},IN=kN;function CN(t,e){var r;const a=(r=void 0)!=null?r:!1;return il(()=>IN(t,{$refStrategy:a?"root":"none"}),{validate:async n=>{const s=await t.safeParseAsync(n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function RN(t,e){var r;const a=(r=void 0)!=null?r:!1;return il(()=>m2(t,{target:"draft-7",io:"output",reused:a?"ref":"inline"}),{validate:async n=>{const s=await ry(t,n);return s.success?{success:!0,value:s.data}:{success:!1,error:s.error}}})}function ON(t){return"_zod"in t}function ea(t,e){return ON(t)?RN(t):CN(t)}var Ud=Symbol.for("vercel.ai.schema");function il(t,{validate:e}={}){return{[Ud]:!0,_type:void 0,[sl]:!0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:e}}function AN(t){return typeof t=="object"&&t!==null&&Ud in t&&t[Ud]===!0&&"jsonSchema"in t&&"validate"in t}function ll(t){return t==null?il({properties:{},additionalProperties:!1}):AN(t)?t:typeof t=="function"?t():ea(t)}var{btoa:NN,atob:MN}=globalThis;function qd(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=MN(e);return Uint8Array.from(r,a=>a.codePointAt(0))}function Fd(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return NN(e)}function jN(t){return t==null?void 0:t.replace(/\/$/,"")}function DN(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}async function*Ty({execute:t,input:e,options:r}){const a=t(e,r);if(DN(a)){let n;for await(const s of a)n=s,yield{type:"preliminary",output:s};yield{type:"final",output:n}}else yield{type:"final",output:await a}}var Zd=Object.defineProperty,LN=Object.getOwnPropertyDescriptor,zN=Object.getOwnPropertyNames,UN=Object.prototype.hasOwnProperty,qN=(t,e)=>{for(var r in e)Zd(t,r,{get:e[r],enumerable:!0})},FN=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of zN(e))!UN.call(t,n)&&n!==r&&Zd(t,n,{get:()=>e[n],enumerable:!(a=LN(e,n))||a.enumerable});return t},ZN=t=>FN(Zd({},"__esModule",{value:!0}),t),xy={};qN(xy,{SYMBOL_FOR_REQ_CONTEXT:()=>ky,getContext:()=>HN});var VN=ZN(xy);const ky=Symbol.for("@vercel/request-context");function HN(){var e,r;return((r=(e=globalThis[ky])==null?void 0:e.get)==null?void 0:r.call(e))??{}}var Vd=Object.defineProperty,BN=Object.getOwnPropertyDescriptor,JN=Object.getOwnPropertyNames,GN=Object.prototype.hasOwnProperty,KN=(t,e)=>{for(var r in e)Vd(t,r,{get:e[r],enumerable:!0})},WN=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of JN(e))!GN.call(t,n)&&n!==r&&Vd(t,n,{get:()=>e[n],enumerable:!(a=BN(e,n))||a.enumerable});return t},QN=t=>WN(Vd({},"__esModule",{value:!0}),t),Iy={};KN(Iy,{getContext:()=>YN.getContext,getVercelOidcToken:()=>XN,getVercelOidcTokenSync:()=>e4});var Cy=QN(Iy),YN=VN;async function XN(){return""}function e4(){return""}var t4="vercel.ai.gateway.error",Hd=Symbol.for(t4),Ry,Oy,sr=class vw extends(Oy=Error,Ry=Hd,Oy){constructor({message:e,statusCode:r=500,cause:a}){super(e),this[Ry]=!0,this.statusCode=r,this.cause=a}static isInstance(e){return vw.hasMarker(e)}static hasMarker(e){return typeof e=="object"&&e!==null&&Hd in e&&e[Hd]===!0}},Ay="GatewayAuthenticationError",r4=`vercel.ai.gateway.error.${Ay}`,Ny=Symbol.for(r4),My,jy,Bd=class gw extends(jy=sr,My=Ny,jy){constructor({message:e="Authentication failed",statusCode:r=401,cause:a}={}){super({message:e,statusCode:r,cause:a}),this[My]=!0,this.name=Ay,this.type="authentication_error"}static isInstance(e){return sr.hasMarker(e)&&Ny in e}static createContextualError({apiKeyProvided:e,oidcTokenProvided:r,message:a="Authentication failed",statusCode:n=401,cause:s}){let o;return e?o=`AI Gateway authentication failed: Invalid API key.
503
507
 
504
508
  Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
505
509
 
@@ -514,18 +518,18 @@ Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
514
518
  Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
515
519
 
516
520
  Option 2 - OIDC token:
517
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new lw({message:o,statusCode:n,cause:s})}},jy="GatewayInvalidRequestError",GA=`vercel.ai.gateway.error.${jy}`,Dy=Symbol.for(GA),Ly,zy,KA=class extends(zy=hr,Ly=Dy,zy){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Ly]=!0,this.name=jy,this.type="invalid_request_error"}static isInstance(t){return hr.hasMarker(t)&&Dy in t}},Uy="GatewayRateLimitError",WA=`vercel.ai.gateway.error.${Uy}`,qy=Symbol.for(WA),Fy,Zy,QA=class extends(Zy=hr,Fy=qy,Zy){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Fy]=!0,this.name=Uy,this.type="rate_limit_exceeded"}static isInstance(t){return hr.hasMarker(t)&&qy in t}},Vy="GatewayModelNotFoundError",YA=`vercel.ai.gateway.error.${Vy}`,Hy=Symbol.for(YA),XA=_t(()=>De(x({modelId:E()}))),By,Jy,Gy=class extends(Jy=hr,By=Hy,Jy){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:a}={}){super({message:t,statusCode:e,cause:a}),this[By]=!0,this.name=Vy,this.type="model_not_found",this.modelId=r}static isInstance(t){return hr.hasMarker(t)&&Hy in t}},Ky="GatewayInternalServerError",e4=`vercel.ai.gateway.error.${Ky}`,Wy=Symbol.for(e4),Qy,Yy,Xy=class extends(Yy=hr,Qy=Wy,Yy){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Qy]=!0,this.name=Ky,this.type="internal_server_error"}static isInstance(t){return hr.hasMarker(t)&&Wy in t}},e_="GatewayResponseError",t4=`vercel.ai.gateway.error.${e_}`,t_=Symbol.for(t4),r_,n_,r4=class extends(n_=hr,r_=t_,n_){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:a,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[r_]=!0,this.name=e_,this.type="response_error",this.response=r,this.validationError=a}static isInstance(t){return hr.hasMarker(t)&&t_ in t}};async function a_({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:a,authMethod:n}){const s=await Dr({value:t,schema:n4});if(!s.success)return new r4({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:s.error,cause:a});const o=s.value,i=o.error.type,l=o.error.message;switch(i){case"authentication_error":return Wd.createContextualError({apiKeyProvided:n==="api-key",oidcTokenProvided:n==="oidc",statusCode:e,cause:a});case"invalid_request_error":return new KA({message:l,statusCode:e,cause:a});case"rate_limit_exceeded":return new QA({message:l,statusCode:e,cause:a});case"model_not_found":{const c=await Dr({value:o.error.param,schema:XA});return new Gy({message:l,statusCode:e,modelId:c.success?c.value.modelId:void 0,cause:a})}case"internal_server_error":return new Xy({message:l,statusCode:e,cause:a});default:return new Xy({message:l,statusCode:e,cause:a})}}var n4=_t(()=>De(x({error:x({message:E(),type:E().nullish(),param:jr().nullish(),code:He([E(),Z()]).nullish()})})));function ca(t,e){var r;return hr.isInstance(t)?t:Nt.isInstance(t)?a_({response:a4(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):a_({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function a4(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var s_="ai-gateway-auth-method";async function fo(t){const e=await Dr({value:t[s_],schema:s4});return e.success?e.value:void 0}var s4=_t(()=>De(He([W("api-key"),W("oidc")]))),o_=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await my({url:`${this.config.baseURL}/config`,headers:await zn(this.config.headers()),successfulResponseHandler:Lr(o4),failedResponseHandler:ia({errorSchema:wr(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await ca(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await my({url:`${t.origin}/v1/credits`,headers:await zn(this.config.headers()),successfulResponseHandler:Lr(i4),failedResponseHandler:ia({errorSchema:wr(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await ca(t)}}},o4=_t(()=>De(x({models:oe(x({id:E(),name:E(),description:E().nullish(),pricing:x({input:E(),output:E(),input_cache_read:E().nullish(),input_cache_write:E().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:a})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:x({specificationVersion:W("v2"),provider:E(),modelId:E()}),modelType:ht(["language","embedding","image"]).nullish()}))}))),i4=_t(()=>De(x({balance:E(),total_used:E()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),l4=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await zn(this.config.headers());try{const{responseHeaders:s,value:o,rawValue:i}=await or({url:this.getUrl(),headers:Kt(n,t.headers,this.getModelConfigHeaders(this.modelId,!1),await zn(this.config.o11yHeaders)),body:e,successfulResponseHandler:Lr(wr()),failedResponseHandler:ia({errorSchema:wr(),errorToMessage:l=>l}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...o,request:{body:e},response:{headers:s,body:i},warnings:r}}catch(s){throw await ca(s,await fo(n))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await zn(this.config.headers());try{const{value:s,responseHeaders:o}=await or({url:this.getUrl(),headers:Kt(n,t.headers,this.getModelConfigHeaders(this.modelId,!0),await zn(this.config.o11yHeaders)),body:e,successfulResponseHandler:uo(wr()),failedResponseHandler:ia({errorSchema:wr(),errorToMessage:i=>i}),...a&&{abortSignal:a},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"&&!t.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:e},response:{headers:o}}}catch(s){throw await ca(s,await fo(n))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const a=r;if(a.data instanceof Uint8Array){const n=Uint8Array.from(a.data),s=Buffer.from(n).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${s}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},c4=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;const s=await zn(this.config.headers());try{const{responseHeaders:o,value:i,rawValue:l}=await or({url:this.getUrl(),headers:Kt(s,e??{},this.getModelConfigHeaders(),await zn(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...a?{providerOptions:a}:{}},successfulResponseHandler:Lr(u4),failedResponseHandler:ia({errorSchema:wr(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(n=i.usage)!=null?n:void 0,providerMetadata:i.providerMetadata,response:{headers:o,body:l}}}catch(o){throw await ca(o,await fo(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},u4=_t(()=>De(x({embeddings:oe(oe(Z())),usage:x({tokens:Z()}).nullish(),providerMetadata:kt(E(),kt(E(),jr())).optional()})));async function d4(){var t;return(t=Ty.getContext().headers)==null?void 0:t["x-vercel-id"]}var p4="2.0.0",f4="0.0.1";function h4(t={}){var e,r;let a=null,n=null;const s=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let o=0;const i=(r=Bd(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const h=await v4(t);if(h)return wn({Authorization:`Bearer ${h.token}`,"ai-gateway-protocol-version":f4,[s_]:h.authMethod,...t.headers},`ai-sdk/gateway/${p4}`);throw Wd.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const h=co({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=co({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=co({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const p=await d4();return{...h&&{"ai-o11y-deployment-id":h},...v&&{"ai-o11y-environment":v},...m&&{"ai-o11y-region":m},...p&&{"ai-o11y-request-id":p}}}},u=h=>new l4(h,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),f=async()=>{var h,v,m;const p=(m=(v=(h=t._internal)==null?void 0:h.currentDate)==null?void 0:v.call(h).getTime())!=null?m:Date.now();return(!a||p-o>s)&&(o=p,a=new o_({baseURL:i,headers:l,fetch:t.fetch}).getAvailableModels().then(_=>(n=_,_)).catch(async _=>{throw await ca(_,await fo(await l()))})),n?Promise.resolve(n):a},g=async()=>new o_({baseURL:i,headers:l,fetch:t.fetch}).getCredits().catch(async h=>{throw await ca(h,await fo(await l()))}),d=function(h){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(h)};return d.getAvailableModels=f,d.getCredits=g,d.imageModel=h=>{throw new xd({modelId:h,modelType:"imageModel"})},d.languageModel=u,d.textEmbeddingModel=h=>new c4(h,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),d}var m4=h4();async function v4(t){const e=co({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await Ty.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var g4=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},ua="1.9.0",i_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function y4(t){var e=new Set([t]),r=new Set,a=t.match(i_);if(!a)return function(){return!1};var n={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(n.prerelease!=null)return function(l){return l===t};function s(i){return r.add(i),!1}function o(i){return e.add(i),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(i_);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||n.major!==u.major?s(l):n.major===0?n.minor===u.minor&&n.patch<=u.patch?o(l):s(l):n.minor<=u.minor?o(l):s(l)}}var _4=y4(ua),w4=ua.split(".")[0],ho=Symbol.for("opentelemetry.js.api."+w4),mo=g4;function vo(t,e,r,a){var n;a===void 0&&(a=!1);var s=mo[ho]=(n=mo[ho])!==null&&n!==void 0?n:{version:ua};if(!a&&s[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(s.version!==ua){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+ua);return r.error(o.stack||o.message),!1}return s[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+ua+"."),!0}function da(t){var e,r,a=(e=mo[ho])===null||e===void 0?void 0:e.version;if(!(!a||!_4(a)))return(r=mo[ho])===null||r===void 0?void 0:r[t]}function go(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+ua+".");var r=mo[ho];r&&delete r[t]}var b4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},E4=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},S4=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return yo("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return yo("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return yo("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return yo("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return yo("verbose",this._namespace,e)},t}();function yo(t,e,r){var a=da("diag");if(a)return r.unshift(e),a[t].apply(a,E4([],b4(r),!1))}var mr;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(mr||(mr={}));function $4(t,e){t<mr.NONE?t=mr.NONE:t>mr.ALL&&(t=mr.ALL),e=e||{};function r(a,n){var s=e[a];return typeof s=="function"&&t>=n?s.bind(e):function(){}}return{error:r("error",mr.ERROR),warn:r("warn",mr.WARN),info:r("info",mr.INFO),debug:r("debug",mr.DEBUG),verbose:r("verbose",mr.VERBOSE)}}var P4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},k4=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},I4="diag",nn=function(){function t(){function e(n){return function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var i=da("diag");if(i)return i[n].apply(i,k4([],P4(s),!1))}}var r=this,a=function(n,s){var o,i,l;if(s===void 0&&(s={logLevel:mr.INFO}),n===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((o=c.stack)!==null&&o!==void 0?o:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=da("diag"),f=$4((i=s.logLevel)!==null&&i!==void 0?i:mr.INFO,n);if(u&&!s.suppressOverrideMessage){var g=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+g),f.warn("Current logger will overwrite one already registered from "+g)}return vo("diag",f,r,!0)};r.setLogger=a,r.disable=function(){go(I4,r)},r.createComponentLogger=function(n){return new S4(n)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}(),x4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},T4=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],a=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&a>=t.length&&(t=void 0),{value:t&&t[a++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},C4=function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=x4(e,2),a=r[0],n=r[1];return[a,n]})},t.prototype.setEntry=function(e,r){var a=new t(this._entries);return a._entries.set(e,r),a},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,a=[],n=0;n<arguments.length;n++)a[n]=arguments[n];var s=new t(this._entries);try{for(var o=T4(a),i=o.next();!i.done;i=o.next()){var l=i.value;s._entries.delete(l)}}catch(c){e={error:c}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return s},t.prototype.clear=function(){return new t},t}();nn.instance();function R4(t){return t===void 0&&(t={}),new C4(new Map(Object.entries(t)))}function l_(t){return Symbol.for(t)}var O4=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(a){return r._currentContext.get(a)},r.setValue=function(a,n){var s=new t(r._currentContext);return s._currentContext.set(a,n),s},r.deleteValue=function(a){var n=new t(r._currentContext);return n._currentContext.delete(a),n}}return t}(),N4=new O4,pa=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,n){a.__proto__=n}||function(a,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(a[s]=n[s])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function a(){this.constructor=e}e.prototype=r===null?Object.create(r):(a.prototype=r.prototype,new a)}}(),A4=function(){function t(){}return t.prototype.createGauge=function(e,r){return V4},t.prototype.createHistogram=function(e,r){return H4},t.prototype.createCounter=function(e,r){return Z4},t.prototype.createUpDownCounter=function(e,r){return B4},t.prototype.createObservableGauge=function(e,r){return G4},t.prototype.createObservableCounter=function(e,r){return J4},t.prototype.createObservableUpDownCounter=function(e,r){return K4},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),wl=function(){function t(){}return t}(),M4=function(t){pa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(wl),j4=function(t){pa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(wl),D4=function(t){pa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(wl),L4=function(t){pa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(wl),Qd=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),z4=function(t){pa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Qd),U4=function(t){pa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Qd),q4=function(t){pa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Qd),F4=new A4,Z4=new M4,V4=new D4,H4=new L4,B4=new j4,J4=new z4,G4=new U4,K4=new q4,W4={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},Q4={set:function(t,e,r){t!=null&&(t[e]=r)}},Y4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},X4=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},eM=function(){function t(){}return t.prototype.active=function(){return N4},t.prototype.with=function(e,r,a){for(var n=[],s=3;s<arguments.length;s++)n[s-3]=arguments[s];return r.call.apply(r,X4([a],Y4(n),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),tM=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},rM=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},Yd="context",nM=new eM,bl=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return vo(Yd,e,nn.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,a){for(var n,s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return(n=this._getContextManager()).with.apply(n,rM([e,r,a],tM(s),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return da(Yd)||nM},t.prototype.disable=function(){this._getContextManager().disable(),go(Yd,nn.instance())},t}(),Xd;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Xd||(Xd={}));var c_="0000000000000000",u_="00000000000000000000000000000000",aM={traceId:u_,spanId:c_,traceFlags:Xd.NONE},_o=function(){function t(e){e===void 0&&(e=aM),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t}(),ep=l_("OpenTelemetry Context Key SPAN");function tp(t){return t.getValue(ep)||void 0}function sM(){return tp(bl.getInstance().active())}function rp(t,e){return t.setValue(ep,e)}function oM(t){return t.deleteValue(ep)}function iM(t,e){return rp(t,new _o(e))}function d_(t){var e;return(e=tp(t))===null||e===void 0?void 0:e.spanContext()}var lM=/^([0-9a-f]{32})$/i,cM=/^[0-9a-f]{16}$/i;function uM(t){return lM.test(t)&&t!==u_}function dM(t){return cM.test(t)&&t!==c_}function p_(t){return uM(t.traceId)&&dM(t.spanId)}function pM(t){return new _o(t)}var np=bl.getInstance(),f_=function(){function t(){}return t.prototype.startSpan=function(e,r,a){a===void 0&&(a=np.active());var n=!!(r!=null&&r.root);if(n)return new _o;var s=a&&d_(a);return fM(s)&&p_(s)?new _o(s):new _o},t.prototype.startActiveSpan=function(e,r,a,n){var s,o,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=a):(s=r,o=a,i=n);var l=o??np.active(),c=this.startSpan(e,s,l),u=rp(l,c);return np.with(u,i,void 0,c)}},t}();function fM(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var hM=new f_,mM=function(){function t(e,r,a,n){this._provider=e,this.name=r,this.version=a,this.options=n}return t.prototype.startSpan=function(e,r,a){return this._getTracer().startSpan(e,r,a)},t.prototype.startActiveSpan=function(e,r,a,n){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):hM},t}(),vM=function(){function t(){}return t.prototype.getTracer=function(e,r,a){return new f_},t}(),gM=new vM,h_=function(){function t(){}return t.prototype.getTracer=function(e,r,a){var n;return(n=this.getDelegateTracer(e,r,a))!==null&&n!==void 0?n:new mM(this,e,r,a)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:gM},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,a){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(e,r,a)},t}(),El;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(El||(El={})),bl.getInstance(),nn.instance();var yM=function(){function t(){}return t.prototype.getMeter=function(e,r,a){return F4},t}(),_M=new yM,ap="metrics",wM=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return vo(ap,e,nn.instance())},t.prototype.getMeterProvider=function(){return da(ap)||_M},t.prototype.getMeter=function(e,r,a){return this.getMeterProvider().getMeter(e,r,a)},t.prototype.disable=function(){go(ap,nn.instance())},t}();wM.getInstance();var bM=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),sp=l_("OpenTelemetry Baggage Key");function m_(t){return t.getValue(sp)||void 0}function EM(){return m_(bl.getInstance().active())}function SM(t,e){return t.setValue(sp,e)}function $M(t){return t.deleteValue(sp)}var op="propagation",PM=new bM,kM=function(){function t(){this.createBaggage=R4,this.getBaggage=m_,this.getActiveBaggage=EM,this.setBaggage=SM,this.deleteBaggage=$M}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return vo(op,e,nn.instance())},t.prototype.inject=function(e,r,a){return a===void 0&&(a=Q4),this._getGlobalPropagator().inject(e,r,a)},t.prototype.extract=function(e,r,a){return a===void 0&&(a=W4),this._getGlobalPropagator().extract(e,r,a)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){go(op,nn.instance())},t.prototype._getGlobalPropagator=function(){return da(op)||PM},t}();kM.getInstance();var ip="trace",IM=function(){function t(){this._proxyTracerProvider=new h_,this.wrapSpanContext=pM,this.isSpanContextValid=p_,this.deleteSpan=oM,this.getSpan=tp,this.getActiveSpan=sM,this.getSpanContext=d_,this.setSpan=rp,this.setSpanContext=iM}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=vo(ip,this._proxyTracerProvider,nn.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return da(ip)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){go(ip,nn.instance()),this._proxyTracerProvider=new h_},t}(),xM=IM.getInstance(),TM=Object.defineProperty,CM=(t,e)=>{for(var r in e)TM(t,r,{get:e[r],enumerable:!0})},v_="AI_NoOutputSpecifiedError",g_=`vercel.ai.error.${v_}`,RM=Symbol.for(g_),y_,__=class extends $e{constructor({message:t="No output specified."}={}){super({name:v_,message:t}),this[y_]=!0}static isInstance(t){return $e.hasMarker(t,g_)}};y_=RM;function OM(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let a=`${e} The tool "${r}" is not supported by this model`;return t.details&&(a+=` - ${t.details}`),a}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var NM="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",w_=!1,b_=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}w_||(w_=!0,console.info(NM));for(const r of t)console.warn(OM(r))}},E_="AI_InvalidArgumentError",S_=`vercel.ai.error.${E_}`,AM=Symbol.for(S_),$_,an=class extends $e{constructor({parameter:t,value:e,message:r}){super({name:E_,message:`Invalid argument for parameter ${t}: ${r}`}),this[$_]=!0,this.parameter=t,this.value=e}static isInstance(t){return $e.hasMarker(t,S_)}};$_=AM;var P_="AI_InvalidToolInputError",k_=`vercel.ai.error.${P_}`,MM=Symbol.for(k_),I_,x_=class extends $e{constructor({toolInput:t,toolName:e,cause:r,message:a=`Invalid input for tool ${e}: ${Qa(r)}`}){super({name:P_,message:a,cause:r}),this[I_]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return $e.hasMarker(t,k_)}};I_=MM;var jM="AI_MCPClientError",T_=`vercel.ai.error.${jM}`,DM=Symbol.for(T_),C_,At=class extends $e{constructor({name:t="MCPClientError",message:e,cause:r,data:a,code:n}){super({name:t,message:e,cause:r}),this[C_]=!0,this.data=a,this.code=n}static isInstance(t){return $e.hasMarker(t,T_)}};C_=DM;var R_="AI_NoObjectGeneratedError",O_=`vercel.ai.error.${R_}`,LM=Symbol.for(O_),N_,A_=class extends $e{constructor({message:t="No object generated.",cause:e,text:r,response:a,usage:n,finishReason:s}){super({name:R_,message:t,cause:e}),this[N_]=!0,this.text=r,this.response=a,this.usage=n,this.finishReason=s}static isInstance(t){return $e.hasMarker(t,O_)}};N_=LM;var M_="AI_NoOutputGeneratedError",j_=`vercel.ai.error.${M_}`,zM=Symbol.for(j_),D_,UM=class extends $e{constructor({message:t="No output generated.",cause:e}={}){super({name:M_,message:t,cause:e}),this[D_]=!0}static isInstance(t){return $e.hasMarker(t,j_)}};D_=zM;var L_="AI_NoSuchToolError",z_=`vercel.ai.error.${L_}`,qM=Symbol.for(z_),U_,lp=class extends $e{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:L_,message:r}),this[U_]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return $e.hasMarker(t,z_)}};U_=qM;var q_="AI_ToolCallRepairError",F_=`vercel.ai.error.${q_}`,FM=Symbol.for(F_),Z_,ZM=class extends $e{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${Qa(t)}`}){super({name:q_,message:r,cause:t}),this[Z_]=!0,this.originalError=e}static isInstance(t){return $e.hasMarker(t,F_)}};Z_=FM;var VM=class extends $e{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},V_="AI_InvalidMessageRoleError",H_=`vercel.ai.error.${V_}`,HM=Symbol.for(H_),B_,BM=class extends $e{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:V_,message:e}),this[B_]=!0,this.role=t}static isInstance(t){return $e.hasMarker(t,H_)}};B_=HM;var J_="AI_DownloadError",G_=`vercel.ai.error.${J_}`,JM=Symbol.for(G_),K_,cp=class extends $e{constructor({url:t,statusCode:e,statusText:r,cause:a,message:n=a==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${a}`}){super({name:J_,message:n,cause:a}),this[K_]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return $e.hasMarker(t,G_)}};K_=JM;var W_="AI_RetryError",Q_=`vercel.ai.error.${W_}`,GM=Symbol.for(Q_),Y_,X_=class extends $e{constructor({message:t,reason:e,errors:r}){super({name:W_,message:t}),this[Y_]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return $e.hasMarker(t,Q_)}};Y_=GM;function Sl(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new VM({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return KM().languageModel(t)}function KM(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:m4}var WM=[{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]}],QM=t=>{const e=typeof t=="string"?yl(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function YM(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?QM(t):t}function XM({data:t,signatures:e}){const r=YM(t),a=typeof r=="string"?yl(r.substring(0,Math.min(r.length,24))):r;for(const n of e)if(a.length>=n.bytesPrefix.length&&n.bytesPrefix.every((s,o)=>s===null||a[o]===s))return n.mediaType}var $l="5.0.76",ej=async({url:t})=>{var e;const r=t.toString();try{const a=await fetch(r,{headers:wn({},`ai-sdk/${$l}`,lo())});if(!a.ok)throw new cp({url:r,statusCode:a.status,statusText:a.statusText});return{data:new Uint8Array(await a.arrayBuffer()),mediaType:(e=a.headers.get("content-type"))!=null?e:void 0}}catch(a){throw cp.isInstance(a)?a:new cp({url:r,cause:a})}},tj=(t=ej)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function rj(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var e0=He([E(),hl(Uint8Array),hl(ArrayBuffer),pN(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function t0(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=rj(t.toString());if(e==null||r==null)throw new $e({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function nj(t){return typeof t=="string"?t:t instanceof ArrayBuffer?_l(new Uint8Array(t)):_l(t)}async function r0({prompt:t,supportedUrls:e,download:r=tj()}){const a=await sj(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(n=>aj({message:n,downloadedAssets:a}))]}function aj({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(a=>oj(a,e)).filter(a=>a.type!=="text"||a.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(a=>a.type!=="text"||a.text!==""||a.providerOptions!=null).map(a=>{const n=a.providerOptions;switch(a.type){case"file":{const{data:s,mediaType:o}=t0(a.data);return{type:"file",data:s,filename:a.filename,mediaType:o??a.mediaType,providerOptions:n}}case"reasoning":return{type:"reasoning",text:a.text,providerOptions:n};case"text":return{type:"text",text:a.text,providerOptions:n};case"tool-call":return{type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:n};case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:n}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(a=>({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:a.providerOptions})),providerOptions:t.providerOptions};default:{const a=r;throw new BM({role:a})}}}async function sj(t,e,r){const a=t.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 o;const i=(o=s.mediaType)!=null?o: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&&wN({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),n=await e(a);return Object.fromEntries(n.map((s,o)=>s==null?null:[a[o].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function oj(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let a;const n=t.type;switch(n){case"image":a=t.image;break;case"file":a=t.data;break;default:throw new Error(`Unsupported part type: ${n}`)}const{data:s,mediaType:o}=t0(a);let i=o??t.mediaType,l=s;if(l instanceof URL){const c=e[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(n){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=XM({data:l,signatures:WM}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:l,providerOptions:t.providerOptions}}}}function up({maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,seed:o,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new an({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new an({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new an({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new an({parameter:"topP",value:r,message:"topP must be a number"});if(a!=null&&typeof a!="number")throw new an({parameter:"topK",value:a,message:"topK must be a number"});if(n!=null&&typeof n!="number")throw new an({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new an({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new an({parameter:"seed",value:o,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,stopSequences:i,seed:o}}function ij(t){return t!=null&&Object.keys(t).length>0}function n0({tools:t,toolChoice:e,activeTools:r}){return ij(t)?{tools:(r!=null?Object.entries(t).filter(([n])=>r.includes(n)):Object.entries(t)).map(([n,s])=>{const o=s.type;switch(o){case void 0:case"dynamic":case"function":return{type:"function",name:n,description:s.description,inputSchema:gl(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:n,id:s.id,args:s.args};default:{const i=o;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var wo=dy(()=>He([U2(),E(),Z(),Pt(),kt(E(),wo),oe(wo)])),sn=kt(E(),kt(E(),wo)),a0=x({type:W("text"),text:E(),providerOptions:sn.optional()}),lj=x({type:W("image"),image:He([e0,hl(URL)]),mediaType:E().optional(),providerOptions:sn.optional()}),s0=x({type:W("file"),data:He([e0,hl(URL)]),filename:E().optional(),mediaType:E(),providerOptions:sn.optional()}),cj=x({type:W("reasoning"),text:E(),providerOptions:sn.optional()}),uj=x({type:W("tool-call"),toolCallId:E(),toolName:E(),input:jr(),providerOptions:sn.optional(),providerExecuted:Pt().optional()}),dj=ar("type",[x({type:W("text"),value:E()}),x({type:W("json"),value:wo}),x({type:W("error-text"),value:E()}),x({type:W("error-json"),value:wo}),x({type:W("content"),value:oe(He([x({type:W("text"),text:E()}),x({type:W("media"),data:E(),mediaType:E()})]))})]),o0=x({type:W("tool-result"),toolCallId:E(),toolName:E(),output:dj,providerOptions:sn.optional()}),pj=x({role:W("system"),content:E(),providerOptions:sn.optional()}),fj=x({role:W("user"),content:He([E(),oe(He([a0,lj,s0]))]),providerOptions:sn.optional()}),hj=x({role:W("assistant"),content:He([E(),oe(He([a0,s0,cj,uj,o0]))]),providerOptions:sn.optional()}),mj=x({role:W("tool"),content:oe(o0),providerOptions:sn.optional()}),vj=He([pj,fj,hj,mj]);async function i0(t){if(t.prompt==null&&t.messages==null)throw new ra({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new ra({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new ra({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new ra({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new ra({prompt:t,message:"messages must not be empty"});const r=await Dr({value:e,schema:oe(vj)});if(!r.success)throw new ra({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function l0(t){return Wd.isInstance(t)||Gy.isInstance(t)?new $e({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function ts({operationId:t,telemetry:e}){return{"operation.name":`${t}${(e==null?void 0:e.functionId)!=null?` ${e.functionId}`:""}`,"resource.name":e==null?void 0:e.functionId,"ai.operationId":t,"ai.telemetry.functionId":e==null?void 0:e.functionId}}function c0({model:t,settings:e,telemetry:r,headers:a}){var n;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((s,[o,i])=>(s[`ai.settings.${o}`]=i,s),{}),...Object.entries((n=r==null?void 0:r.metadata)!=null?n:{}).reduce((s,[o,i])=>(s[`ai.telemetry.metadata.${o}`]=i,s),{}),...Object.entries(a??{}).reduce((s,[o,i])=>(i!==void 0&&(s[`ai.request.headers.${o}`]=i),s),{})}}var gj={startSpan(){return Pl},startActiveSpan(t,e,r,a){if(typeof e=="function")return e(Pl);if(typeof r=="function")return r(Pl);if(typeof a=="function")return a(Pl)}},Pl={spanContext(){return yj},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}},yj={traceId:"",spanId:"",traceFlags:0};function u0({isEnabled:t=!1,tracer:e}={}){return t?e||xM.getTracer("ai"):gj}function rs({name:t,tracer:e,attributes:r,fn:a,endWhenDone:n=!0}){return e.startActiveSpan(t,{attributes:r},async s=>{try{const o=await a(s);return n&&s.end(),o}catch(o){try{dp(s,o)}finally{s.end()}throw o}})}function dp(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:El.ERROR,message:e.message})):t.setStatus({code:El.ERROR})}function br({telemetry:t,attributes:e}){return(t==null?void 0:t.isEnabled)!==!0?{}:Object.entries(e).reduce((r,[a,n])=>{if(n==null)return r;if(typeof n=="object"&&"input"in n&&typeof n.input=="function"){if((t==null?void 0:t.recordInputs)===!1)return r;const s=n.input();return s==null?r:{...r,[a]:s}}if(typeof n=="object"&&"output"in n&&typeof n.output=="function"){if((t==null?void 0:t.recordOutputs)===!1)return r;const s=n.output();return s==null?r:{...r,[a]:s}}return{...r,[a]:n}},{})}function d0(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?nj(r.data):r.data}:r)})))}function p0(t,e){return{inputTokens:bo(t.inputTokens,e.inputTokens),outputTokens:bo(t.outputTokens,e.outputTokens),totalTokens:bo(t.totalTokens,e.totalTokens),reasoningTokens:bo(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:bo(t.cachedInputTokens,e.cachedInputTokens)}}function bo(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function pp(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function _j({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let a;const n=r["retry-after-ms"];if(n){const o=parseFloat(n);Number.isNaN(o)||(a=o)}const s=r["retry-after"];if(s&&a===void 0){const o=parseFloat(s);Number.isNaN(o)?a=Date.parse(s)-Date.now():a=o*1e3}return a!=null&&!Number.isNaN(a)&&0<=a&&(a<60*1e3||a<e)?a:e}var wj=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:a}={})=>async n=>f0(n,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:a});async function f0(t,{maxRetries:e,delayInMs:r,backoffFactor:a,abortSignal:n},s=[]){try{return await t()}catch(o){if(sa(o)||e===0)throw o;const i=Ud(o),l=[...s,o],c=l.length;if(c>e)throw new X_({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(o instanceof Error&&Nt.isInstance(o)&&o.isRetryable===!0&&c<=e)return await vN(_j({error:o,exponentialBackoffDelay:r}),{abortSignal:n}),f0(t,{maxRetries:e,delayInMs:a*r,backoffFactor:a,abortSignal:n},l);throw c===1?o:new X_({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function h0({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new an({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new an({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:wj({maxRetries:r,abortSignal:e})}}function m0(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var v0=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=_l(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=yl(this.base64Data)),this.uint8ArrayData}},bj=class extends v0{constructor(t){super(t),this.type="file"}};async function g0({toolCall:t,tools:e,repairToolCall:r,system:a,messages:n}){try{if(e==null)throw new lp({toolName:t.toolName});try{return await y0({toolCall:t,tools:e})}catch(s){if(r==null||!(lp.isInstance(s)||x_.isInstance(s)))throw s;let o=null;try{o=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:l}=e[i];return gl(l).jsonSchema},system:a,messages:n,error:s})}catch(i){throw new ZM({cause:i,originalError:s})}if(o==null)throw s;return await y0({toolCall:o,tools:e})}}catch(s){const o=await oa({text:t.input}),i=o.success?o.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:s}}}async function y0({toolCall:t,tools:e}){const r=t.toolName,a=e[r];if(a==null)throw new lp({toolName:t.toolName,availableTools:Object.keys(e)});const n=gl(a.inputSchema),s=t.input.trim()===""?await Dr({value:{},schema:n}):await oa({text:t.input,schema:n});if(s.success===!1)throw new x_({toolName:r,toolInput:t.input,cause:s.error});return a.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var _0=class{constructor({content:t,finishReason:e,usage:r,warnings:a,request:n,response:s,providerMetadata:o}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=a,this.request=n,this.response=s,this.providerMetadata=o}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function fp(t){return({steps:e})=>e.length===t}async function w0({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function hp({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:Qa(t)}:r==="json"?{type:"error-json",value:b0(t)}:e!=null&&e.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:b0(t)}}function b0(t){return t===void 0?null:t}function mp({content:t,tools:e}){const r=[],a=t.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:hp({tool:e==null?void 0:e[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:hp({tool:e==null?void 0:e[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});a.length>0&&r.push({role:"assistant",content:a});const n=t.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:hp({tool:e==null?void 0:e[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return n.length>0&&r.push({role:"tool",content:n}),r}var Ej=io({prefix:"aitxt",size:24});async function Sj({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:c=fp(1),experimental_output:u,experimental_telemetry:f,providerOptions:g,experimental_activeTools:d,activeTools:h=d,experimental_prepareStep:v,prepareStep:m=v,experimental_repairToolCall:p,experimental_download:_,experimental_context:w,_internal:{generateId:b=Ej,currentDate:S=()=>new Date}={},onStepFinish:I,...k}){const A=Sl(t),O=pp(c),{maxRetries:H,retry:J}=h0({maxRetries:o,abortSignal:i}),K=up(k),z=wn(l??{},`ai/${$l}`),U=c0({model:A,telemetry:f,headers:z,settings:{...K,maxRetries:H}}),G=await i0({system:a,prompt:n,messages:s}),se=u0(f);try{return await rs({name:"ai.generateText",attributes:br({telemetry:f,attributes:{...ts({operationId:"ai.generateText",telemetry:f}),...U,"ai.model.provider":A.provider,"ai.model.id":A.modelId,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:n,messages:s})}}}),tracer:se,fn:async ne=>{var ce,pe,M,R,D,N,y;const P=up(k);let j,Q=[],ee=[];const Se=[],de=[];do{const Te=[...G.messages,...Se],me=await(m==null?void 0:m({model:A,steps:de,stepNumber:de.length,messages:Te})),Ne=Sl((ce=me==null?void 0:me.model)!=null?ce:A),Ae=await r0({prompt:{system:(pe=me==null?void 0:me.system)!=null?pe:G.system,messages:(M=me==null?void 0:me.messages)!=null?M:Te},supportedUrls:await Ne.supportedUrls,download:_}),{toolChoice:ke,tools:tt}=n0({tools:e,toolChoice:(R=me==null?void 0:me.toolChoice)!=null?R:r,activeTools:(D=me==null?void 0:me.activeTools)!=null?D:h});j=await J(()=>{var Ee;return rs({name:"ai.generateText.doGenerate",attributes:br({telemetry:f,attributes:{...ts({operationId:"ai.generateText.doGenerate",telemetry:f}),...U,"ai.model.provider":Ne.provider,"ai.model.id":Ne.modelId,"ai.prompt.messages":{input:()=>d0(Ae)},"ai.prompt.tools":{input:()=>tt==null?void 0:tt.map(Qe=>JSON.stringify(Qe))},"ai.prompt.toolChoice":{input:()=>ke!=null?JSON.stringify(ke):void 0},"gen_ai.system":Ne.provider,"gen_ai.request.model":Ne.modelId,"gen_ai.request.frequency_penalty":k.frequencyPenalty,"gen_ai.request.max_tokens":k.maxOutputTokens,"gen_ai.request.presence_penalty":k.presencePenalty,"gen_ai.request.stop_sequences":k.stopSequences,"gen_ai.request.temperature":(Ee=k.temperature)!=null?Ee:void 0,"gen_ai.request.top_k":k.topK,"gen_ai.request.top_p":k.topP}}),tracer:se,fn:async Qe=>{var ir,Mt,wt,lr,jt,cr,bn,fa;const ut=await Ne.doGenerate({...P,tools:tt,toolChoice:ke,responseFormat:u==null?void 0:u.responseFormat,prompt:Ae,providerOptions:g,abortSignal:i,headers:z}),Er={id:(Mt=(ir=ut.response)==null?void 0:ir.id)!=null?Mt:b(),timestamp:(lr=(wt=ut.response)==null?void 0:wt.timestamp)!=null?lr:S(),modelId:(cr=(jt=ut.response)==null?void 0:jt.modelId)!=null?cr:Ne.modelId,headers:(bn=ut.response)==null?void 0:bn.headers,body:(fa=ut.response)==null?void 0:fa.body};return Qe.setAttributes(br({telemetry:f,attributes:{"ai.response.finishReason":ut.finishReason,"ai.response.text":{output:()=>m0(ut.content)},"ai.response.toolCalls":{output:()=>{const qr=E0(ut.content);return qr==null?void 0:JSON.stringify(qr)}},"ai.response.id":Er.id,"ai.response.model":Er.modelId,"ai.response.timestamp":Er.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ut.providerMetadata),"ai.usage.promptTokens":ut.usage.inputTokens,"ai.usage.completionTokens":ut.usage.outputTokens,"gen_ai.response.finish_reasons":[ut.finishReason],"gen_ai.response.id":Er.id,"gen_ai.response.model":Er.modelId,"gen_ai.usage.input_tokens":ut.usage.inputTokens,"gen_ai.usage.output_tokens":ut.usage.outputTokens}})),{...ut,response:Er}}})});const Ze=await Promise.all(j.content.filter(Ee=>Ee.type==="tool-call").map(Ee=>g0({toolCall:Ee,tools:e,repairToolCall:p,system:a,messages:Te})));for(const Ee of Ze){if(Ee.invalid)continue;const Qe=e[Ee.toolName];(Qe==null?void 0:Qe.onInputAvailable)!=null&&await Qe.onInputAvailable({input:Ee.input,toolCallId:Ee.toolCallId,messages:Te,abortSignal:i,experimental_context:w})}const re=Ze.filter(Ee=>Ee.invalid&&Ee.dynamic);ee=[];for(const Ee of re)ee.push({type:"tool-error",toolCallId:Ee.toolCallId,toolName:Ee.toolName,input:Ee.input,error:Ud(Ee.error),dynamic:!0});Q=Ze.filter(Ee=>!Ee.providerExecuted),e!=null&&ee.push(...await $j({toolCalls:Q.filter(Ee=>!Ee.invalid),tools:e,tracer:se,telemetry:f,messages:Te,abortSignal:i,experimental_context:w}));const ze=kj({content:j.content,toolCalls:Ze,toolOutputs:ee});Se.push(...mp({content:ze,tools:e}));const Be=new _0({content:ze,finishReason:j.finishReason,usage:j.usage,warnings:j.warnings,providerMetadata:j.providerMetadata,request:(N=j.request)!=null?N:{},response:{...j.response,messages:structuredClone(Se)}});b_((y=j.warnings)!=null?y:[]),de.push(Be),await(I==null?void 0:I(Be))}while(Q.length>0&&ee.length===Q.length&&!await w0({stopConditions:O,steps:de}));ne.setAttributes(br({telemetry:f,attributes:{"ai.response.finishReason":j.finishReason,"ai.response.text":{output:()=>m0(j.content)},"ai.response.toolCalls":{output:()=>{const Te=E0(j.content);return Te==null?void 0:JSON.stringify(Te)}},"ai.response.providerMetadata":JSON.stringify(j.providerMetadata),"ai.usage.promptTokens":j.usage.inputTokens,"ai.usage.completionTokens":j.usage.outputTokens}}));const ge=de[de.length-1];let vt;return ge.finishReason==="stop"&&(vt=await(u==null?void 0:u.parseOutput({text:ge.text},{response:ge.response,usage:ge.usage,finishReason:ge.finishReason}))),new Pj({steps:de,resolvedOutput:vt})}})}catch(ne){throw l0(ne)}}async function $j({toolCalls:t,tools:e,tracer:r,telemetry:a,messages:n,abortSignal:s,experimental_context:o}){return(await Promise.all(t.map(async({toolCallId:l,toolName:c,input:u})=>{const f=e[c];if((f==null?void 0:f.execute)!=null)return rs({name:"ai.toolCall",attributes:br({telemetry:a,attributes:{...ts({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async g=>{try{const d=Py({execute:f.execute.bind(f),input:u,options:{toolCallId:l,messages:n,abortSignal:s,experimental_context:o}});let h;for await(const v of d)v.type==="final"&&(h=v.output);try{g.setAttributes(br({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(h)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:h,dynamic:f.type==="dynamic"}}catch(d){return dp(g,d),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:d,dynamic:f.type==="dynamic"}}}})}))).filter(l=>l!=null)}var Pj=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>p0(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new __;return this.resolvedOutput}};function E0(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function kj({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(a=>{switch(a.type){case"text":case"reasoning":case"source":return a;case"file":return{type:"file",file:new v0(a)};case"tool-call":return e.find(n=>n.toolCallId===a.toolCallId);case"tool-result":{const n=e.find(s=>s.toolCallId===a.toolCallId);if(n==null)throw new Error(`Tool call ${a.toolCallId} not found.`);return a.isError?{type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,error:a.result,providerExecuted:!0,dynamic:n.dynamic}:{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,output:a.result,providerExecuted:!0,dynamic:n.dynamic}}}}),...r]}function kl(t,e){const r=new Headers(t??{});for(const[a,n]of Object.entries(e))r.has(a)||r.set(a,n);return r}function Ij({status:t,statusText:e,headers:r,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:kl(r,{"content-type":"text/plain; charset=utf-8"})})}function S0({response:t,status:e,statusText:r,headers:a,stream:n}){t.writeHead(e??200,r,a);const s=n.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;t.write(l)||await new Promise(u=>{t.once("drain",u)})}}catch(i){throw i}finally{t.end()}})()}function xj({response:t,status:e,statusText:r,headers:a,textStream:n}){S0({response:t,status:e,statusText:r,headers:Object.fromEntries(kl(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})}var $0=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
521
+ Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`,new gw({message:o,statusCode:n,cause:s})}},Dy="GatewayInvalidRequestError",n4=`vercel.ai.gateway.error.${Dy}`,Ly=Symbol.for(n4),zy,Uy,a4=class extends(Uy=sr,zy=Ly,Uy){constructor({message:t="Invalid request",statusCode:e=400,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[zy]=!0,this.name=Dy,this.type="invalid_request_error"}static isInstance(t){return sr.hasMarker(t)&&Ly in t}},qy="GatewayRateLimitError",s4=`vercel.ai.gateway.error.${qy}`,Fy=Symbol.for(s4),Zy,Vy,o4=class extends(Vy=sr,Zy=Fy,Vy){constructor({message:t="Rate limit exceeded",statusCode:e=429,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Zy]=!0,this.name=qy,this.type="rate_limit_exceeded"}static isInstance(t){return sr.hasMarker(t)&&Fy in t}},Hy="GatewayModelNotFoundError",i4=`vercel.ai.gateway.error.${Hy}`,By=Symbol.for(i4),l4=Ga(()=>ea(R({modelId:S()}))),Jy,Gy,Ky=class extends(Gy=sr,Jy=By,Gy){constructor({message:t="Model not found",statusCode:e=404,modelId:r,cause:a}={}){super({message:t,statusCode:e,cause:a}),this[Jy]=!0,this.name=Hy,this.type="model_not_found",this.modelId=r}static isInstance(t){return sr.hasMarker(t)&&By in t}},Wy="GatewayInternalServerError",c4=`vercel.ai.gateway.error.${Wy}`,Qy=Symbol.for(c4),Yy,Xy,e_=class extends(Xy=sr,Yy=Qy,Xy){constructor({message:t="Internal server error",statusCode:e=500,cause:r}={}){super({message:t,statusCode:e,cause:r}),this[Yy]=!0,this.name=Wy,this.type="internal_server_error"}static isInstance(t){return sr.hasMarker(t)&&Qy in t}},t_="GatewayResponseError",u4=`vercel.ai.gateway.error.${t_}`,r_=Symbol.for(u4),n_,a_,d4=class extends(a_=sr,n_=r_,a_){constructor({message:t="Invalid response from Gateway",statusCode:e=502,response:r,validationError:a,cause:n}={}){super({message:t,statusCode:e,cause:n}),this[n_]=!0,this.name=t_,this.type="response_error",this.response=r,this.validationError=a}static isInstance(t){return sr.hasMarker(t)&&r_ in t}};async function s_({response:t,statusCode:e,defaultMessage:r="Gateway request failed",cause:a,authMethod:n}){const s=await Rn({value:t,schema:f4});if(!s.success)return new d4({message:`Invalid error response format: ${r}`,statusCode:e,response:t,validationError:s.error,cause:a});const o=s.value,i=o.error.type,l=o.error.message;switch(i){case"authentication_error":return Bd.createContextualError({apiKeyProvided:n==="api-key",oidcTokenProvided:n==="oidc",statusCode:e,cause:a});case"invalid_request_error":return new a4({message:l,statusCode:e,cause:a});case"rate_limit_exceeded":return new o4({message:l,statusCode:e,cause:a});case"model_not_found":{const c=await Rn({value:o.error.param,schema:l4});return new Ky({message:l,statusCode:e,modelId:c.success?c.value.modelId:void 0,cause:a})}case"internal_server_error":return new e_({message:l,statusCode:e,cause:a});default:return new e_({message:l,statusCode:e,cause:a})}}var f4=Ga(()=>ea(R({error:R({message:S(),type:S().nullish(),param:Cn().nullish(),code:Ve([S(),K()]).nullish()})})));function ta(t,e){var r;return sr.isInstance(t)?t:Xe.isInstance(t)?s_({response:p4(t),statusCode:(r=t.statusCode)!=null?r:500,defaultMessage:"Gateway request failed",cause:t,authMethod:e}):s_({response:{},statusCode:500,defaultMessage:t instanceof Error?`Gateway request failed: ${t.message}`:"Unknown Gateway error",cause:t,authMethod:e})}function p4(t){if(t.data!==void 0)return t.data;if(t.responseBody!=null)try{return JSON.parse(t.responseBody)}catch{return t.responseBody}return{}}var o_="ai-gateway-auth-method";async function so(t){const e=await Rn({value:t[o_],schema:h4});return e.success?e.value:void 0}var h4=Ga(()=>ea(Ve([ne("api-key"),ne("oidc")]))),i_=class{constructor(t){this.config=t}async getAvailableModels(){try{const{value:t}=await yy({url:`${this.config.baseURL}/config`,headers:await On(this.config.headers()),successfulResponseHandler:ol(m4),failedResponseHandler:ao({errorSchema:pr(),errorToMessage:e=>e}),fetch:this.config.fetch});return t}catch(t){throw await ta(t)}}async getCredits(){try{const t=new URL(this.config.baseURL),{value:e}=await yy({url:`${t.origin}/v1/credits`,headers:await On(this.config.headers()),successfulResponseHandler:ol(v4),failedResponseHandler:ao({errorSchema:pr(),errorToMessage:r=>r}),fetch:this.config.fetch});return e}catch(t){throw await ta(t)}}},m4=Ga(()=>ea(R({models:ce(R({id:S(),name:S(),description:S().nullish(),pricing:R({input:S(),output:S(),input_cache_read:S().nullish(),input_cache_write:S().nullish()}).transform(({input:t,output:e,input_cache_read:r,input_cache_write:a})=>({input:t,output:e,...r?{cachedInputTokens:r}:{},...a?{cacheCreationInputTokens:a}:{}})).nullish(),specification:R({specificationVersion:ne("v2"),provider:S(),modelId:S()}),modelType:zt(["language","embedding","image"]).nullish()}))}))),v4=Ga(()=>ea(R({balance:S(),total_used:S()}).transform(({balance:t,total_used:e})=>({balance:t,totalUsed:e})))),g4=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(t){const{abortSignal:e,...r}=t;return{args:this.maybeEncodeFileParts(r),warnings:[]}}async doGenerate(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await On(this.config.headers());try{const{responseHeaders:s,value:o,rawValue:i}=await jd({url:this.getUrl(),headers:Od(n,t.headers,this.getModelConfigHeaders(this.modelId,!1),await On(this.config.o11yHeaders)),body:e,successfulResponseHandler:ol(pr()),failedResponseHandler:ao({errorSchema:pr(),errorToMessage:l=>l}),...a&&{abortSignal:a},fetch:this.config.fetch});return{...o,request:{body:e},response:{headers:s,body:i},warnings:r}}catch(s){throw await ta(s,await so(n))}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{abortSignal:a}=t,n=await On(this.config.headers());try{const{value:s,responseHeaders:o}=await jd({url:this.getUrl(),headers:Od(n,t.headers,this.getModelConfigHeaders(this.modelId,!0),await On(this.config.o11yHeaders)),body:e,successfulResponseHandler:FA(pr()),failedResponseHandler:ao({errorSchema:pr(),errorToMessage:i=>i}),...a&&{abortSignal:a},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"&&!t.includeRawChunks)return;c.type==="response-metadata"&&c.timestamp&&typeof c.timestamp=="string"&&(c.timestamp=new Date(c.timestamp)),l.enqueue(c)}else l.error(i.error)}})),request:{body:e},response:{headers:o}}}catch(s){throw await ta(s,await so(n))}}isFilePart(t){return t&&typeof t=="object"&&"type"in t&&t.type==="file"}maybeEncodeFileParts(t){for(const e of t.prompt)for(const r of e.content)if(this.isFilePart(r)){const a=r;if(a.data instanceof Uint8Array){const n=Uint8Array.from(a.data),s=Buffer.from(n).toString("base64");a.data=new URL(`data:${a.mediaType||"application/octet-stream"};base64,${s}`)}}return t}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(t,e){return{"ai-language-model-specification-version":"2","ai-language-model-id":t,"ai-language-model-streaming":String(e)}}},y4=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;const s=await On(this.config.headers());try{const{responseHeaders:o,value:i,rawValue:l}=await jd({url:this.getUrl(),headers:Od(s,e??{},this.getModelConfigHeaders(),await On(this.config.o11yHeaders)),body:{input:t.length===1?t[0]:t,...a?{providerOptions:a}:{}},successfulResponseHandler:ol(_4),failedResponseHandler:ao({errorSchema:pr(),errorToMessage:c=>c}),...r&&{abortSignal:r},fetch:this.config.fetch});return{embeddings:i.embeddings,usage:(n=i.usage)!=null?n:void 0,providerMetadata:i.providerMetadata,response:{headers:o,body:l}}}catch(o){throw await ta(o,await so(s))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":"2","ai-model-id":this.modelId}}},_4=Ga(()=>ea(R({embeddings:ce(ce(K())),usage:R({tokens:K()}).nullish(),providerMetadata:Qt(S(),Qt(S(),Cn())).optional()})));async function w4(){var t;return(t=Cy.getContext().headers)==null?void 0:t["x-vercel-id"]}var b4="2.0.0",E4="0.0.1";function $4(t={}){var e,r;let a=null,n=null;const s=(e=t.metadataCacheRefreshMillis)!=null?e:1e3*60*5;let o=0;const i=(r=jN(t.baseURL))!=null?r:"https://ai-gateway.vercel.sh/v1/ai",l=async()=>{const f=await P4(t);if(f)return no({Authorization:`Bearer ${f.token}`,"ai-gateway-protocol-version":E4,[o_]:f.authMethod,...t.headers},`ai-sdk/gateway/${b4}`);throw Bd.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},c=()=>{const f=al({settingValue:void 0,environmentVariableName:"VERCEL_DEPLOYMENT_ID"}),v=al({settingValue:void 0,environmentVariableName:"VERCEL_ENV"}),m=al({settingValue:void 0,environmentVariableName:"VERCEL_REGION"});return async()=>{const p=await w4();return{...f&&{"ai-o11y-deployment-id":f},...v&&{"ai-o11y-environment":v},...m&&{"ai-o11y-region":m},...p&&{"ai-o11y-request-id":p}}}},u=f=>new g4(f,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),h=async()=>{var f,v,m;const p=(m=(v=(f=t._internal)==null?void 0:f.currentDate)==null?void 0:v.call(f).getTime())!=null?m:Date.now();return(!a||p-o>s)&&(o=p,a=new i_({baseURL:i,headers:l,fetch:t.fetch}).getAvailableModels().then(y=>(n=y,y)).catch(async y=>{throw await ta(y,await so(await l()))})),n?Promise.resolve(n):a},g=async()=>new i_({baseURL:i,headers:l,fetch:t.fetch}).getCredits().catch(async f=>{throw await ta(f,await so(await l()))}),d=function(f){if(new.target)throw new Error("The Gateway Provider model function cannot be called with the new keyword.");return u(f)};return d.getAvailableModels=h,d.getCredits=g,d.imageModel=f=>{throw new _d({modelId:f,modelType:"imageModel"})},d.languageModel=u,d.textEmbeddingModel=f=>new y4(f,{provider:"gateway",baseURL:i,headers:l,fetch:t.fetch,o11yHeaders:c()}),d}var S4=$4();async function P4(t){const e=al({settingValue:t.apiKey,environmentVariableName:"AI_GATEWAY_API_KEY"});if(e)return{token:e,authMethod:"api-key"};try{return{token:await Cy.getVercelOidcToken(),authMethod:"oidc"}}catch{return null}}var T4=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},ra="1.9.0",l_=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function x4(t){var e=new Set([t]),r=new Set,a=t.match(l_);if(!a)return function(){return!1};var n={major:+a[1],minor:+a[2],patch:+a[3],prerelease:a[4]};if(n.prerelease!=null)return function(l){return l===t};function s(i){return r.add(i),!1}function o(i){return e.add(i),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(l_);if(!c)return s(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||n.major!==u.major?s(l):n.major===0?n.minor===u.minor&&n.patch<=u.patch?o(l):s(l):n.minor<=u.minor?o(l):s(l)}}var k4=x4(ra),I4=ra.split(".")[0],oo=Symbol.for("opentelemetry.js.api."+I4),io=T4;function lo(t,e,r,a){var n;a===void 0&&(a=!1);var s=io[oo]=(n=io[oo])!==null&&n!==void 0?n:{version:ra};if(!a&&s[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(s.version!==ra){var o=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+t+" does not match previously registered API v"+ra);return r.error(o.stack||o.message),!1}return s[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+ra+"."),!0}function na(t){var e,r,a=(e=io[oo])===null||e===void 0?void 0:e.version;if(!(!a||!k4(a)))return(r=io[oo])===null||r===void 0?void 0:r[t]}function co(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+ra+".");var r=io[oo];r&&delete r[t]}var C4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},R4=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},O4=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return uo("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return uo("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return uo("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return uo("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return uo("verbose",this._namespace,e)},t}();function uo(t,e,r){var a=na("diag");if(a)return r.unshift(e),a[t].apply(a,R4([],C4(r),!1))}var or;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(or||(or={}));function A4(t,e){t<or.NONE?t=or.NONE:t>or.ALL&&(t=or.ALL),e=e||{};function r(a,n){var s=e[a];return typeof s=="function"&&t>=n?s.bind(e):function(){}}return{error:r("error",or.ERROR),warn:r("warn",or.WARN),info:r("info",or.INFO),debug:r("debug",or.DEBUG),verbose:r("verbose",or.VERBOSE)}}var N4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},M4=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},j4="diag",Jr=function(){function t(){function e(n){return function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var i=na("diag");if(i)return i[n].apply(i,M4([],N4(s),!1))}}var r=this,a=function(n,s){var o,i,l;if(s===void 0&&(s={logLevel:or.INFO}),n===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((o=c.stack)!==null&&o!==void 0?o:c.message),!1}typeof s=="number"&&(s={logLevel:s});var u=na("diag"),h=A4((i=s.logLevel)!==null&&i!==void 0?i:or.INFO,n);if(u&&!s.suppressOverrideMessage){var g=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+g),h.warn("Current logger will overwrite one already registered from "+g)}return lo("diag",h,r,!0)};r.setLogger=a,r.disable=function(){co(j4,r)},r.createComponentLogger=function(n){return new O4(n)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}(),D4=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},L4=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],a=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&a>=t.length&&(t=void 0),{value:t&&t[a++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},z4=function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=D4(e,2),a=r[0],n=r[1];return[a,n]})},t.prototype.setEntry=function(e,r){var a=new t(this._entries);return a._entries.set(e,r),a},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,a=[],n=0;n<arguments.length;n++)a[n]=arguments[n];var s=new t(this._entries);try{for(var o=L4(a),i=o.next();!i.done;i=o.next()){var l=i.value;s._entries.delete(l)}}catch(c){e={error:c}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return s},t.prototype.clear=function(){return new t},t}();Jr.instance();function U4(t){return t===void 0&&(t={}),new z4(new Map(Object.entries(t)))}function c_(t){return Symbol.for(t)}var q4=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(a){return r._currentContext.get(a)},r.setValue=function(a,n){var s=new t(r._currentContext);return s._currentContext.set(a,n),s},r.deleteValue=function(a){var n=new t(r._currentContext);return n._currentContext.delete(a),n}}return t}(),F4=new q4,aa=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,n){a.__proto__=n}||function(a,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(a[s]=n[s])},t(e,r)};return function(e,r){if(typeof r!="function"&&r!==null)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");t(e,r);function a(){this.constructor=e}e.prototype=r===null?Object.create(r):(a.prototype=r.prototype,new a)}}(),Z4=function(){function t(){}return t.prototype.createGauge=function(e,r){return X4},t.prototype.createHistogram=function(e,r){return eM},t.prototype.createCounter=function(e,r){return Y4},t.prototype.createUpDownCounter=function(e,r){return tM},t.prototype.createObservableGauge=function(e,r){return nM},t.prototype.createObservableCounter=function(e,r){return rM},t.prototype.createObservableUpDownCounter=function(e,r){return aM},t.prototype.addBatchObservableCallback=function(e,r){},t.prototype.removeBatchObservableCallback=function(e){},t}(),cl=function(){function t(){}return t}(),V4=function(t){aa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(cl),H4=function(t){aa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.add=function(r,a){},e}(cl),B4=function(t){aa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(cl),J4=function(t){aa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.record=function(r,a){},e}(cl),Jd=function(){function t(){}return t.prototype.addCallback=function(e){},t.prototype.removeCallback=function(e){},t}(),G4=function(t){aa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Jd),K4=function(t){aa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Jd),W4=function(t){aa(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e}(Jd),Q4=new Z4,Y4=new V4,X4=new B4,eM=new J4,tM=new H4,rM=new G4,nM=new K4,aM=new W4,sM={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},oM={set:function(t,e,r){t!=null&&(t[e]=r)}},iM=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},lM=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},cM=function(){function t(){}return t.prototype.active=function(){return F4},t.prototype.with=function(e,r,a){for(var n=[],s=3;s<arguments.length;s++)n[s-3]=arguments[s];return r.call.apply(r,lM([a],iM(n),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),uM=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var a=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=a.next()).done;)s.push(n.value)}catch(i){o={error:i}}finally{try{n&&!n.done&&(r=a.return)&&r.call(a)}finally{if(o)throw o.error}}return s},dM=function(t,e,r){if(r||arguments.length===2)for(var a=0,n=e.length,s;a<n;a++)(s||!(a in e))&&(s||(s=Array.prototype.slice.call(e,0,a)),s[a]=e[a]);return t.concat(s||Array.prototype.slice.call(e))},Gd="context",fM=new cM,ul=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return lo(Gd,e,Jr.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,a){for(var n,s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return(n=this._getContextManager()).with.apply(n,dM([e,r,a],uM(s),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return na(Gd)||fM},t.prototype.disable=function(){this._getContextManager().disable(),co(Gd,Jr.instance())},t}(),Kd;(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(Kd||(Kd={}));var u_="0000000000000000",d_="00000000000000000000000000000000",pM={traceId:d_,spanId:u_,traceFlags:Kd.NONE},fo=function(){function t(e){e===void 0&&(e=pM),this._spanContext=e}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(e,r){return this},t.prototype.setAttributes=function(e){return this},t.prototype.addEvent=function(e,r){return this},t.prototype.addLink=function(e){return this},t.prototype.addLinks=function(e){return this},t.prototype.setStatus=function(e){return this},t.prototype.updateName=function(e){return this},t.prototype.end=function(e){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(e,r){},t}(),Wd=c_("OpenTelemetry Context Key SPAN");function Qd(t){return t.getValue(Wd)||void 0}function hM(){return Qd(ul.getInstance().active())}function Yd(t,e){return t.setValue(Wd,e)}function mM(t){return t.deleteValue(Wd)}function vM(t,e){return Yd(t,new fo(e))}function f_(t){var e;return(e=Qd(t))===null||e===void 0?void 0:e.spanContext()}var gM=/^([0-9a-f]{32})$/i,yM=/^[0-9a-f]{16}$/i;function _M(t){return gM.test(t)&&t!==d_}function wM(t){return yM.test(t)&&t!==u_}function p_(t){return _M(t.traceId)&&wM(t.spanId)}function bM(t){return new fo(t)}var Xd=ul.getInstance(),h_=function(){function t(){}return t.prototype.startSpan=function(e,r,a){a===void 0&&(a=Xd.active());var n=!!(r!=null&&r.root);if(n)return new fo;var s=a&&f_(a);return EM(s)&&p_(s)?new fo(s):new fo},t.prototype.startActiveSpan=function(e,r,a,n){var s,o,i;if(!(arguments.length<2)){arguments.length===2?i=r:arguments.length===3?(s=r,i=a):(s=r,o=a,i=n);var l=o??Xd.active(),c=this.startSpan(e,s,l),u=Yd(l,c);return Xd.with(u,i,void 0,c)}},t}();function EM(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var $M=new h_,SM=function(){function t(e,r,a,n){this._provider=e,this.name=r,this.version=a,this.options=n}return t.prototype.startSpan=function(e,r,a){return this._getTracer().startSpan(e,r,a)},t.prototype.startActiveSpan=function(e,r,a,n){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):$M},t}(),PM=function(){function t(){}return t.prototype.getTracer=function(e,r,a){return new h_},t}(),TM=new PM,m_=function(){function t(){}return t.prototype.getTracer=function(e,r,a){var n;return(n=this.getDelegateTracer(e,r,a))!==null&&n!==void 0?n:new SM(this,e,r,a)},t.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:TM},t.prototype.setDelegate=function(e){this._delegate=e},t.prototype.getDelegateTracer=function(e,r,a){var n;return(n=this._delegate)===null||n===void 0?void 0:n.getTracer(e,r,a)},t}(),dl;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(dl||(dl={})),ul.getInstance(),Jr.instance();var xM=function(){function t(){}return t.prototype.getMeter=function(e,r,a){return Q4},t}(),kM=new xM,ef="metrics",IM=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(e){return lo(ef,e,Jr.instance())},t.prototype.getMeterProvider=function(){return na(ef)||kM},t.prototype.getMeter=function(e,r,a){return this.getMeterProvider().getMeter(e,r,a)},t.prototype.disable=function(){co(ef,Jr.instance())},t}();IM.getInstance();var CM=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),tf=c_("OpenTelemetry Baggage Key");function v_(t){return t.getValue(tf)||void 0}function RM(){return v_(ul.getInstance().active())}function OM(t,e){return t.setValue(tf,e)}function AM(t){return t.deleteValue(tf)}var rf="propagation",NM=new CM,MM=function(){function t(){this.createBaggage=U4,this.getBaggage=v_,this.getActiveBaggage=RM,this.setBaggage=OM,this.deleteBaggage=AM}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return lo(rf,e,Jr.instance())},t.prototype.inject=function(e,r,a){return a===void 0&&(a=oM),this._getGlobalPropagator().inject(e,r,a)},t.prototype.extract=function(e,r,a){return a===void 0&&(a=sM),this._getGlobalPropagator().extract(e,r,a)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){co(rf,Jr.instance())},t.prototype._getGlobalPropagator=function(){return na(rf)||NM},t}();MM.getInstance();var nf="trace",jM=function(){function t(){this._proxyTracerProvider=new m_,this.wrapSpanContext=bM,this.isSpanContextValid=p_,this.deleteSpan=mM,this.getSpan=Qd,this.getActiveSpan=hM,this.getSpanContext=f_,this.setSpan=Yd,this.setSpanContext=vM}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(e){var r=lo(nf,this._proxyTracerProvider,Jr.instance());return r&&this._proxyTracerProvider.setDelegate(e),r},t.prototype.getTracerProvider=function(){return na(nf)||this._proxyTracerProvider},t.prototype.getTracer=function(e,r){return this.getTracerProvider().getTracer(e,r)},t.prototype.disable=function(){co(nf,Jr.instance()),this._proxyTracerProvider=new m_},t}(),DM=jM.getInstance(),LM=Object.defineProperty,zM=(t,e)=>{for(var r in e)LM(t,r,{get:e[r],enumerable:!0})},g_="AI_NoOutputSpecifiedError",y_=`vercel.ai.error.${g_}`,UM=Symbol.for(y_),__,w_=class extends Pe{constructor({message:t="No output specified."}={}){super({name:g_,message:t}),this[__]=!0}static isInstance(t){return Pe.hasMarker(t,y_)}};__=UM;function qM(t){const e="AI SDK Warning:";switch(t.type){case"unsupported-setting":{let r=`${e} The "${t.setting}" setting is not supported by this model`;return t.details&&(r+=` - ${t.details}`),r}case"unsupported-tool":{const r="name"in t.tool?t.tool.name:"unknown tool";let a=`${e} The tool "${r}" is not supported by this model`;return t.details&&(a+=` - ${t.details}`),a}case"other":return`${e} ${t.message}`;default:return`${e} ${JSON.stringify(t,null,2)}`}}var FM="AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.",b_=!1,E_=t=>{if(t.length===0)return;const e=globalThis.AI_SDK_LOG_WARNINGS;if(e!==!1){if(typeof e=="function"){e(t);return}b_||(b_=!0,console.info(FM));for(const r of t)console.warn(qM(r))}},$_="AI_InvalidArgumentError",S_=`vercel.ai.error.${$_}`,ZM=Symbol.for(S_),P_,Gr=class extends Pe{constructor({parameter:t,value:e,message:r}){super({name:$_,message:`Invalid argument for parameter ${t}: ${r}`}),this[P_]=!0,this.parameter=t,this.value=e}static isInstance(t){return Pe.hasMarker(t,S_)}};P_=ZM;var T_="AI_InvalidToolInputError",x_=`vercel.ai.error.${T_}`,VM=Symbol.for(x_),k_,I_=class extends Pe{constructor({toolInput:t,toolName:e,cause:r,message:a=`Invalid input for tool ${e}: ${Ha(r)}`}){super({name:T_,message:a,cause:r}),this[k_]=!0,this.toolInput=t,this.toolName=e}static isInstance(t){return Pe.hasMarker(t,x_)}};k_=VM;var C_="AI_NoObjectGeneratedError",R_=`vercel.ai.error.${C_}`,HM=Symbol.for(R_),O_,A_=class extends Pe{constructor({message:t="No object generated.",cause:e,text:r,response:a,usage:n,finishReason:s}){super({name:C_,message:t,cause:e}),this[O_]=!0,this.text=r,this.response=a,this.usage=n,this.finishReason=s}static isInstance(t){return Pe.hasMarker(t,R_)}};O_=HM;var N_="AI_NoOutputGeneratedError",M_=`vercel.ai.error.${N_}`,BM=Symbol.for(M_),j_,JM=class extends Pe{constructor({message:t="No output generated.",cause:e}={}){super({name:N_,message:t,cause:e}),this[j_]=!0}static isInstance(t){return Pe.hasMarker(t,M_)}};j_=BM;var D_="AI_NoSuchToolError",L_=`vercel.ai.error.${D_}`,GM=Symbol.for(L_),z_,af=class extends Pe{constructor({toolName:t,availableTools:e=void 0,message:r=`Model tried to call unavailable tool '${t}'. ${e===void 0?"No tools are available.":`Available tools: ${e.join(", ")}.`}`}){super({name:D_,message:r}),this[z_]=!0,this.toolName=t,this.availableTools=e}static isInstance(t){return Pe.hasMarker(t,L_)}};z_=GM;var U_="AI_ToolCallRepairError",q_=`vercel.ai.error.${U_}`,KM=Symbol.for(q_),F_,WM=class extends Pe{constructor({cause:t,originalError:e,message:r=`Error repairing tool call: ${Ha(t)}`}){super({name:U_,message:r,cause:t}),this[F_]=!0,this.originalError=e}static isInstance(t){return Pe.hasMarker(t,q_)}};F_=KM;var QM=class extends Pe{constructor(t){super({name:"AI_UnsupportedModelVersionError",message:`Unsupported model version ${t.version} for provider "${t.provider}" and model "${t.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=t.version,this.provider=t.provider,this.modelId=t.modelId}},Z_="AI_InvalidMessageRoleError",V_=`vercel.ai.error.${Z_}`,YM=Symbol.for(V_),H_,XM=class extends Pe{constructor({role:t,message:e=`Invalid message role: '${t}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:Z_,message:e}),this[H_]=!0,this.role=t}static isInstance(t){return Pe.hasMarker(t,V_)}};H_=YM;var B_="AI_DownloadError",J_=`vercel.ai.error.${B_}`,ej=Symbol.for(J_),G_,sf=class extends Pe{constructor({url:t,statusCode:e,statusText:r,cause:a,message:n=a==null?`Failed to download ${t}: ${e} ${r}`:`Failed to download ${t}: ${a}`}){super({name:B_,message:n,cause:a}),this[G_]=!0,this.url=t,this.statusCode=e,this.statusText=r}static isInstance(t){return Pe.hasMarker(t,J_)}};G_=ej;var K_="AI_RetryError",W_=`vercel.ai.error.${K_}`,tj=Symbol.for(W_),Q_,Y_=class extends Pe{constructor({message:t,reason:e,errors:r}){super({name:K_,message:t}),this[Q_]=!0,this.reason=e,this.errors=r,this.lastError=r[r.length-1]}static isInstance(t){return Pe.hasMarker(t,W_)}};Q_=tj;function fl(t){if(typeof t!="string"){if(t.specificationVersion!=="v2")throw new QM({version:t.specificationVersion,provider:t.provider,modelId:t.modelId});return t}return rj().languageModel(t)}function rj(){var t;return(t=globalThis.AI_SDK_DEFAULT_PROVIDER)!=null?t:S4}var nj=[{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]}],aj=t=>{const e=typeof t=="string"?qd(t):t,r=(e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127;return e.slice(r+10)};function sj(t){return typeof t=="string"&&t.startsWith("SUQz")||typeof t!="string"&&t.length>10&&t[0]===73&&t[1]===68&&t[2]===51?aj(t):t}function oj({data:t,signatures:e}){const r=sj(t),a=typeof r=="string"?qd(r.substring(0,Math.min(r.length,24))):r;for(const n of e)if(a.length>=n.bytesPrefix.length&&n.bytesPrefix.every((s,o)=>s===null||a[o]===s))return n.mediaType}var X_="5.0.76",ij=async({url:t})=>{var e;const r=t.toString();try{const a=await fetch(r,{headers:no({},`ai-sdk/${X_}`,Nd())});if(!a.ok)throw new sf({url:r,statusCode:a.status,statusText:a.statusText});return{data:new Uint8Array(await a.arrayBuffer()),mediaType:(e=a.headers.get("content-type"))!=null?e:void 0}}catch(a){throw sf.isInstance(a)?a:new sf({url:r,cause:a})}},lj=(t=ij)=>e=>Promise.all(e.map(async r=>r.isUrlSupportedByModel?null:t(r)));function cj(t){try{const[e,r]=t.split(",");return{mediaType:e.split(";")[0].split(":")[1],base64Content:r}}catch{return{mediaType:void 0,base64Content:void 0}}}var e0=Ve([S(),nl(Uint8Array),nl(ArrayBuffer),_A(t=>{var e,r;return(r=(e=globalThis.Buffer)==null?void 0:e.isBuffer(t))!=null?r:!1},{message:"Must be a Buffer"})]);function t0(t){if(t instanceof Uint8Array)return{data:t,mediaType:void 0};if(t instanceof ArrayBuffer)return{data:new Uint8Array(t),mediaType:void 0};if(typeof t=="string")try{t=new URL(t)}catch{}if(t instanceof URL&&t.protocol==="data:"){const{mediaType:e,base64Content:r}=cj(t.toString());if(e==null||r==null)throw new Pe({name:"InvalidDataContentError",message:`Invalid data URL format in content ${t.toString()}`});return{data:r,mediaType:e}}return{data:t,mediaType:void 0}}function uj(t){return typeof t=="string"?t:t instanceof ArrayBuffer?Fd(new Uint8Array(t)):Fd(t)}async function r0({prompt:t,supportedUrls:e,download:r=lj()}){const a=await fj(t.messages,r,e);return[...t.system!=null?[{role:"system",content:t.system}]:[],...t.messages.map(n=>dj({message:n,downloadedAssets:a}))]}function dj({message:t,downloadedAssets:e}){const r=t.role;switch(r){case"system":return{role:"system",content:t.content,providerOptions:t.providerOptions};case"user":return typeof t.content=="string"?{role:"user",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"user",content:t.content.map(a=>pj(a,e)).filter(a=>a.type!=="text"||a.text!==""),providerOptions:t.providerOptions};case"assistant":return typeof t.content=="string"?{role:"assistant",content:[{type:"text",text:t.content}],providerOptions:t.providerOptions}:{role:"assistant",content:t.content.filter(a=>a.type!=="text"||a.text!==""||a.providerOptions!=null).map(a=>{const n=a.providerOptions;switch(a.type){case"file":{const{data:s,mediaType:o}=t0(a.data);return{type:"file",data:s,filename:a.filename,mediaType:o??a.mediaType,providerOptions:n}}case"reasoning":return{type:"reasoning",text:a.text,providerOptions:n};case"text":return{type:"text",text:a.text,providerOptions:n};case"tool-call":return{type:"tool-call",toolCallId:a.toolCallId,toolName:a.toolName,input:a.input,providerExecuted:a.providerExecuted,providerOptions:n};case"tool-result":return{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:n}}}),providerOptions:t.providerOptions};case"tool":return{role:"tool",content:t.content.map(a=>({type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,output:a.output,providerOptions:a.providerOptions})),providerOptions:t.providerOptions};default:{const a=r;throw new XM({role:a})}}}async function fj(t,e,r){const a=t.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 o;const i=(o=s.mediaType)!=null?o: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&&kA({url:s.data.toString(),mediaType:s.mediaType,supportedUrls:r})})),n=await e(a);return Object.fromEntries(n.map((s,o)=>s==null?null:[a[o].url.toString(),{data:s.data,mediaType:s.mediaType}]).filter(s=>s!=null))}function pj(t,e){var r;if(t.type==="text")return{type:"text",text:t.text,providerOptions:t.providerOptions};let a;const n=t.type;switch(n){case"image":a=t.image;break;case"file":a=t.data;break;default:throw new Error(`Unsupported part type: ${n}`)}const{data:s,mediaType:o}=t0(a);let i=o??t.mediaType,l=s;if(l instanceof URL){const c=e[l.toString()];c&&(l=c.data,i??(i=c.mediaType))}switch(n){case"image":return(l instanceof Uint8Array||typeof l=="string")&&(i=(r=oj({data:l,signatures:nj}))!=null?r:i),{type:"file",mediaType:i??"image/*",filename:void 0,data:l,providerOptions:t.providerOptions};case"file":{if(i==null)throw new Error("Media type is missing for file part");return{type:"file",mediaType:i,filename:t.filename,data:l,providerOptions:t.providerOptions}}}}function of({maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,seed:o,stopSequences:i}){if(t!=null){if(!Number.isInteger(t))throw new Gr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be an integer"});if(t<1)throw new Gr({parameter:"maxOutputTokens",value:t,message:"maxOutputTokens must be >= 1"})}if(e!=null&&typeof e!="number")throw new Gr({parameter:"temperature",value:e,message:"temperature must be a number"});if(r!=null&&typeof r!="number")throw new Gr({parameter:"topP",value:r,message:"topP must be a number"});if(a!=null&&typeof a!="number")throw new Gr({parameter:"topK",value:a,message:"topK must be a number"});if(n!=null&&typeof n!="number")throw new Gr({parameter:"presencePenalty",value:n,message:"presencePenalty must be a number"});if(s!=null&&typeof s!="number")throw new Gr({parameter:"frequencyPenalty",value:s,message:"frequencyPenalty must be a number"});if(o!=null&&!Number.isInteger(o))throw new Gr({parameter:"seed",value:o,message:"seed must be an integer"});return{maxOutputTokens:t,temperature:e,topP:r,topK:a,presencePenalty:n,frequencyPenalty:s,stopSequences:i,seed:o}}function hj(t){return t!=null&&Object.keys(t).length>0}function n0({tools:t,toolChoice:e,activeTools:r}){return hj(t)?{tools:(r!=null?Object.entries(t).filter(([n])=>r.includes(n)):Object.entries(t)).map(([n,s])=>{const o=s.type;switch(o){case void 0:case"dynamic":case"function":return{type:"function",name:n,description:s.description,inputSchema:ll(s.inputSchema).jsonSchema,providerOptions:s.providerOptions};case"provider-defined":return{type:"provider-defined",name:n,id:s.id,args:s.args};default:{const i=o;throw new Error(`Unsupported tool type: ${i}`)}}}),toolChoice:e==null?{type:"auto"}:typeof e=="string"?{type:e}:{type:"tool",toolName:e.toolName}}:{tools:void 0,toolChoice:void 0}}var po=hy(()=>Ve([J2(),S(),K(),$t(),Qt(S(),po),ce(po)])),Kr=Qt(S(),Qt(S(),po)),a0=R({type:ne("text"),text:S(),providerOptions:Kr.optional()}),mj=R({type:ne("image"),image:Ve([e0,nl(URL)]),mediaType:S().optional(),providerOptions:Kr.optional()}),s0=R({type:ne("file"),data:Ve([e0,nl(URL)]),filename:S().optional(),mediaType:S(),providerOptions:Kr.optional()}),vj=R({type:ne("reasoning"),text:S(),providerOptions:Kr.optional()}),gj=R({type:ne("tool-call"),toolCallId:S(),toolName:S(),input:Cn(),providerOptions:Kr.optional(),providerExecuted:$t().optional()}),yj=Ja("type",[R({type:ne("text"),value:S()}),R({type:ne("json"),value:po}),R({type:ne("error-text"),value:S()}),R({type:ne("error-json"),value:po}),R({type:ne("content"),value:ce(Ve([R({type:ne("text"),text:S()}),R({type:ne("media"),data:S(),mediaType:S()})]))})]),o0=R({type:ne("tool-result"),toolCallId:S(),toolName:S(),output:yj,providerOptions:Kr.optional()}),_j=R({role:ne("system"),content:S(),providerOptions:Kr.optional()}),wj=R({role:ne("user"),content:Ve([S(),ce(Ve([a0,mj,s0]))]),providerOptions:Kr.optional()}),bj=R({role:ne("assistant"),content:Ve([S(),ce(Ve([a0,s0,vj,gj,o0]))]),providerOptions:Kr.optional()}),Ej=R({role:ne("tool"),content:ce(o0),providerOptions:Kr.optional()}),$j=Ve([_j,wj,bj,Ej]);async function i0(t){if(t.prompt==null&&t.messages==null)throw new Kn({prompt:t,message:"prompt or messages must be defined"});if(t.prompt!=null&&t.messages!=null)throw new Kn({prompt:t,message:"prompt and messages cannot be defined at the same time"});if(t.system!=null&&typeof t.system!="string")throw new Kn({prompt:t,message:"system must be a string"});let e;if(t.prompt!=null&&typeof t.prompt=="string")e=[{role:"user",content:t.prompt}];else if(t.prompt!=null&&Array.isArray(t.prompt))e=t.prompt;else if(t.messages!=null)e=t.messages;else throw new Kn({prompt:t,message:"prompt or messages must be defined"});if(e.length===0)throw new Kn({prompt:t,message:"messages must not be empty"});const r=await Rn({value:e,schema:ce($j)});if(!r.success)throw new Kn({prompt:t,message:"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.",cause:r.error});return{messages:e,system:t.system}}function l0(t){return Bd.isInstance(t)||Ky.isInstance(t)?new Pe({name:"GatewayError",message:"Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.",cause:t}):t}function Ka({operationId:t,telemetry:e}){return{"operation.name":`${t}${(e==null?void 0:e.functionId)!=null?` ${e.functionId}`:""}`,"resource.name":e==null?void 0:e.functionId,"ai.operationId":t,"ai.telemetry.functionId":e==null?void 0:e.functionId}}function c0({model:t,settings:e,telemetry:r,headers:a}){var n;return{"ai.model.provider":t.provider,"ai.model.id":t.modelId,...Object.entries(e).reduce((s,[o,i])=>(s[`ai.settings.${o}`]=i,s),{}),...Object.entries((n=r==null?void 0:r.metadata)!=null?n:{}).reduce((s,[o,i])=>(s[`ai.telemetry.metadata.${o}`]=i,s),{}),...Object.entries(a??{}).reduce((s,[o,i])=>(i!==void 0&&(s[`ai.request.headers.${o}`]=i),s),{})}}var Sj={startSpan(){return pl},startActiveSpan(t,e,r,a){if(typeof e=="function")return e(pl);if(typeof r=="function")return r(pl);if(typeof a=="function")return a(pl)}},pl={spanContext(){return Pj},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}},Pj={traceId:"",spanId:"",traceFlags:0};function u0({isEnabled:t=!1,tracer:e}={}){return t?e||DM.getTracer("ai"):Sj}function Wa({name:t,tracer:e,attributes:r,fn:a,endWhenDone:n=!0}){return e.startActiveSpan(t,{attributes:r},async s=>{try{const o=await a(s);return n&&s.end(),o}catch(o){try{lf(s,o)}finally{s.end()}throw o}})}function lf(t,e){e instanceof Error?(t.recordException({name:e.name,message:e.message,stack:e.stack}),t.setStatus({code:dl.ERROR,message:e.message})):t.setStatus({code:dl.ERROR})}function hr({telemetry:t,attributes:e}){return(t==null?void 0:t.isEnabled)!==!0?{}:Object.entries(e).reduce((r,[a,n])=>{if(n==null)return r;if(typeof n=="object"&&"input"in n&&typeof n.input=="function"){if((t==null?void 0:t.recordInputs)===!1)return r;const s=n.input();return s==null?r:{...r,[a]:s}}if(typeof n=="object"&&"output"in n&&typeof n.output=="function"){if((t==null?void 0:t.recordOutputs)===!1)return r;const s=n.output();return s==null?r:{...r,[a]:s}}return{...r,[a]:n}},{})}function d0(t){return JSON.stringify(t.map(e=>({...e,content:typeof e.content=="string"?e.content:e.content.map(r=>r.type==="file"?{...r,data:r.data instanceof Uint8Array?uj(r.data):r.data}:r)})))}function f0(t,e){return{inputTokens:ho(t.inputTokens,e.inputTokens),outputTokens:ho(t.outputTokens,e.outputTokens),totalTokens:ho(t.totalTokens,e.totalTokens),reasoningTokens:ho(t.reasoningTokens,e.reasoningTokens),cachedInputTokens:ho(t.cachedInputTokens,e.cachedInputTokens)}}function ho(t,e){return t==null&&e==null?void 0:(t??0)+(e??0)}function cf(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function Tj({error:t,exponentialBackoffDelay:e}){const r=t.responseHeaders;if(!r)return e;let a;const n=r["retry-after-ms"];if(n){const o=parseFloat(n);Number.isNaN(o)||(a=o)}const s=r["retry-after"];if(s&&a===void 0){const o=parseFloat(s);Number.isNaN(o)?a=Date.parse(s)-Date.now():a=o*1e3}return a!=null&&!Number.isNaN(a)&&0<=a&&(a<60*1e3||a<e)?a:e}var xj=({maxRetries:t=2,initialDelayInMs:e=2e3,backoffFactor:r=2,abortSignal:a}={})=>async n=>p0(n,{maxRetries:t,delayInMs:e,backoffFactor:r,abortSignal:a});async function p0(t,{maxRetries:e,delayInMs:r,backoffFactor:a,abortSignal:n},s=[]){try{return await t()}catch(o){if(Yn(o)||e===0)throw o;const i=Ad(o),l=[...s,o],c=l.length;if(c>e)throw new Y_({message:`Failed after ${c} attempts. Last error: ${i}`,reason:"maxRetriesExceeded",errors:l});if(o instanceof Error&&Xe.isInstance(o)&&o.isRetryable===!0&&c<=e)return await $A(Tj({error:o,exponentialBackoffDelay:r}),{abortSignal:n}),p0(t,{maxRetries:e,delayInMs:a*r,backoffFactor:a,abortSignal:n},l);throw c===1?o:new Y_({message:`Failed after ${c} attempts with non-retryable error: '${i}'`,reason:"errorNotRetryable",errors:l})}}function h0({maxRetries:t,abortSignal:e}){if(t!=null){if(!Number.isInteger(t))throw new Gr({parameter:"maxRetries",value:t,message:"maxRetries must be an integer"});if(t<0)throw new Gr({parameter:"maxRetries",value:t,message:"maxRetries must be >= 0"})}const r=t??2;return{maxRetries:r,retry:xj({maxRetries:r,abortSignal:e})}}function m0(t){const e=t.filter(r=>r.type==="text");if(e.length!==0)return e.map(r=>r.text).join("")}var v0=class{constructor({data:t,mediaType:e}){const r=t instanceof Uint8Array;this.base64Data=r?void 0:t,this.uint8ArrayData=r?t:void 0,this.mediaType=e}get base64(){return this.base64Data==null&&(this.base64Data=Fd(this.uint8ArrayData)),this.base64Data}get uint8Array(){return this.uint8ArrayData==null&&(this.uint8ArrayData=qd(this.base64Data)),this.uint8ArrayData}},kj=class extends v0{constructor(t){super(t),this.type="file"}};async function g0({toolCall:t,tools:e,repairToolCall:r,system:a,messages:n}){try{if(e==null)throw new af({toolName:t.toolName});try{return await y0({toolCall:t,tools:e})}catch(s){if(r==null||!(af.isInstance(s)||I_.isInstance(s)))throw s;let o=null;try{o=await r({toolCall:t,tools:e,inputSchema:({toolName:i})=>{const{inputSchema:l}=e[i];return ll(l).jsonSchema},system:a,messages:n,error:s})}catch(i){throw new WM({cause:i,originalError:s})}if(o==null)throw s;return await y0({toolCall:o,tools:e})}}catch(s){const o=await Xn({text:t.input}),i=o.success?o.value:t.input;return{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:i,dynamic:!0,invalid:!0,error:s}}}async function y0({toolCall:t,tools:e}){const r=t.toolName,a=e[r];if(a==null)throw new af({toolName:t.toolName,availableTools:Object.keys(e)});const n=ll(a.inputSchema),s=t.input.trim()===""?await Rn({value:{},schema:n}):await Xn({text:t.input,schema:n});if(s.success===!1)throw new I_({toolName:r,toolInput:t.input,cause:s.error});return a.type==="dynamic"?{type:"tool-call",toolCallId:t.toolCallId,toolName:t.toolName,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata,dynamic:!0}:{type:"tool-call",toolCallId:t.toolCallId,toolName:r,input:s.value,providerExecuted:t.providerExecuted,providerMetadata:t.providerMetadata}}var _0=class{constructor({content:t,finishReason:e,usage:r,warnings:a,request:n,response:s,providerMetadata:o}){this.content=t,this.finishReason=e,this.usage=r,this.warnings=a,this.request=n,this.response=s,this.providerMetadata=o}get text(){return this.content.filter(t=>t.type==="text").map(t=>t.text).join("")}get reasoning(){return this.content.filter(t=>t.type==="reasoning")}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(t=>t.text).join("")}get files(){return this.content.filter(t=>t.type==="file").map(t=>t.file)}get sources(){return this.content.filter(t=>t.type==="source")}get toolCalls(){return this.content.filter(t=>t.type==="tool-call")}get staticToolCalls(){return this.toolCalls.filter(t=>t.dynamic!==!0)}get dynamicToolCalls(){return this.toolCalls.filter(t=>t.dynamic===!0)}get toolResults(){return this.content.filter(t=>t.type==="tool-result")}get staticToolResults(){return this.toolResults.filter(t=>t.dynamic!==!0)}get dynamicToolResults(){return this.toolResults.filter(t=>t.dynamic===!0)}};function uf(t){return({steps:e})=>e.length===t}async function w0({stopConditions:t,steps:e}){return(await Promise.all(t.map(r=>r({steps:e})))).some(r=>r)}function df({output:t,tool:e,errorMode:r}){return r==="text"?{type:"error-text",value:Ha(t)}:r==="json"?{type:"error-json",value:b0(t)}:e!=null&&e.toModelOutput?e.toModelOutput(t):typeof t=="string"?{type:"text",value:t}:{type:"json",value:b0(t)}}function b0(t){return t===void 0?null:t}function ff({content:t,tools:e}){const r=[],a=t.filter(s=>s.type!=="source").filter(s=>(s.type!=="tool-result"||s.providerExecuted)&&(s.type!=="tool-error"||s.providerExecuted)).filter(s=>s.type!=="text"||s.text.length>0).map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,providerOptions:s.providerMetadata};case"reasoning":return{type:"reasoning",text:s.text,providerOptions:s.providerMetadata};case"file":return{type:"file",data:s.file.base64,mediaType:s.file.mediaType,providerOptions:s.providerMetadata};case"tool-call":return{type:"tool-call",toolCallId:s.toolCallId,toolName:s.toolName,input:s.input,providerExecuted:s.providerExecuted,providerOptions:s.providerMetadata};case"tool-result":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:df({tool:e==null?void 0:e[s.toolName],output:s.output,errorMode:"none"}),providerExecuted:!0,providerOptions:s.providerMetadata};case"tool-error":return{type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:df({tool:e==null?void 0:e[s.toolName],output:s.error,errorMode:"json"}),providerOptions:s.providerMetadata}}});a.length>0&&r.push({role:"assistant",content:a});const n=t.filter(s=>s.type==="tool-result"||s.type==="tool-error").filter(s=>!s.providerExecuted).map(s=>({type:"tool-result",toolCallId:s.toolCallId,toolName:s.toolName,output:df({tool:e==null?void 0:e[s.toolName],output:s.type==="tool-result"?s.output:s.error,errorMode:s.type==="tool-error"?"text":"none"})}));return n.length>0&&r.push({role:"tool",content:n}),r}var Ij=ro({prefix:"aitxt",size:24});async function Cj({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:c=uf(1),experimental_output:u,experimental_telemetry:h,providerOptions:g,experimental_activeTools:d,activeTools:f=d,experimental_prepareStep:v,prepareStep:m=v,experimental_repairToolCall:p,experimental_download:y,experimental_context:_,_internal:{generateId:w=Ij,currentDate:E=()=>new Date}={},onStepFinish:P,...T}){const O=fl(t),M=cf(c),{maxRetries:J,retry:H}=h0({maxRetries:o,abortSignal:i}),G=of(T),F=no(l??{},`ai/${X_}`),Z=c0({model:O,telemetry:h,headers:F,settings:{...G,maxRetries:J}}),te=await i0({system:a,prompt:n,messages:s}),pe=u0(h);try{return await Wa({name:"ai.generateText",attributes:hr({telemetry:h,attributes:{...Ka({operationId:"ai.generateText",telemetry:h}),...Z,"ai.model.provider":O.provider,"ai.model.id":O.modelId,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:n,messages:s})}}}),tracer:pe,fn:async ve=>{var N,ie,D,C,z,A,b;const x=of(T);let L,W=[],X=[];const $e=[],le=[];do{const Ie=[...te.messages,...$e],he=await(m==null?void 0:m({model:O,steps:le,stepNumber:le.length,messages:Ie})),Ae=fl((N=he==null?void 0:he.model)!=null?N:O),Ne=await r0({prompt:{system:(ie=he==null?void 0:he.system)!=null?ie:te.system,messages:(D=he==null?void 0:he.messages)!=null?D:Ie},supportedUrls:await Ae.supportedUrls,download:y}),{toolChoice:Te,tools:tt}=n0({tools:e,toolChoice:(C=he==null?void 0:he.toolChoice)!=null?C:r,activeTools:(z=he==null?void 0:he.activeTools)!=null?z:f});L=await H(()=>{var Ee;return Wa({name:"ai.generateText.doGenerate",attributes:hr({telemetry:h,attributes:{...Ka({operationId:"ai.generateText.doGenerate",telemetry:h}),...Z,"ai.model.provider":Ae.provider,"ai.model.id":Ae.modelId,"ai.prompt.messages":{input:()=>d0(Ne)},"ai.prompt.tools":{input:()=>tt==null?void 0:tt.map(We=>JSON.stringify(We))},"ai.prompt.toolChoice":{input:()=>Te!=null?JSON.stringify(Te):void 0},"gen_ai.system":Ae.provider,"gen_ai.request.model":Ae.modelId,"gen_ai.request.frequency_penalty":T.frequencyPenalty,"gen_ai.request.max_tokens":T.maxOutputTokens,"gen_ai.request.presence_penalty":T.presencePenalty,"gen_ai.request.stop_sequences":T.stopSequences,"gen_ai.request.temperature":(Ee=T.temperature)!=null?Ee:void 0,"gen_ai.request.top_k":T.topK,"gen_ai.request.top_p":T.topP}}),tracer:pe,fn:async We=>{var Yt,Ct,yt,Xt,Rt,er,dn,ia;const ut=await Ae.doGenerate({...x,tools:tt,toolChoice:Te,responseFormat:u==null?void 0:u.responseFormat,prompt:Ne,providerOptions:g,abortSignal:i,headers:F}),vr={id:(Ct=(Yt=ut.response)==null?void 0:Yt.id)!=null?Ct:w(),timestamp:(Xt=(yt=ut.response)==null?void 0:yt.timestamp)!=null?Xt:E(),modelId:(er=(Rt=ut.response)==null?void 0:Rt.modelId)!=null?er:Ae.modelId,headers:(dn=ut.response)==null?void 0:dn.headers,body:(ia=ut.response)==null?void 0:ia.body};return We.setAttributes(hr({telemetry:h,attributes:{"ai.response.finishReason":ut.finishReason,"ai.response.text":{output:()=>m0(ut.content)},"ai.response.toolCalls":{output:()=>{const Or=E0(ut.content);return Or==null?void 0:JSON.stringify(Or)}},"ai.response.id":vr.id,"ai.response.model":vr.modelId,"ai.response.timestamp":vr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(ut.providerMetadata),"ai.usage.promptTokens":ut.usage.inputTokens,"ai.usage.completionTokens":ut.usage.outputTokens,"gen_ai.response.finish_reasons":[ut.finishReason],"gen_ai.response.id":vr.id,"gen_ai.response.model":vr.modelId,"gen_ai.usage.input_tokens":ut.usage.inputTokens,"gen_ai.usage.output_tokens":ut.usage.outputTokens}})),{...ut,response:vr}}})});const Ze=await Promise.all(L.content.filter(Ee=>Ee.type==="tool-call").map(Ee=>g0({toolCall:Ee,tools:e,repairToolCall:p,system:a,messages:Ie})));for(const Ee of Ze){if(Ee.invalid)continue;const We=e[Ee.toolName];(We==null?void 0:We.onInputAvailable)!=null&&await We.onInputAvailable({input:Ee.input,toolCallId:Ee.toolCallId,messages:Ie,abortSignal:i,experimental_context:_})}const re=Ze.filter(Ee=>Ee.invalid&&Ee.dynamic);X=[];for(const Ee of re)X.push({type:"tool-error",toolCallId:Ee.toolCallId,toolName:Ee.toolName,input:Ee.input,error:Ad(Ee.error),dynamic:!0});W=Ze.filter(Ee=>!Ee.providerExecuted),e!=null&&X.push(...await Rj({toolCalls:W.filter(Ee=>!Ee.invalid),tools:e,tracer:pe,telemetry:h,messages:Ie,abortSignal:i,experimental_context:_}));const Le=Aj({content:L.content,toolCalls:Ze,toolOutputs:X});$e.push(...ff({content:Le,tools:e}));const He=new _0({content:Le,finishReason:L.finishReason,usage:L.usage,warnings:L.warnings,providerMetadata:L.providerMetadata,request:(A=L.request)!=null?A:{},response:{...L.response,messages:structuredClone($e)}});E_((b=L.warnings)!=null?b:[]),le.push(He),await(P==null?void 0:P(He))}while(W.length>0&&X.length===W.length&&!await w0({stopConditions:M,steps:le}));ve.setAttributes(hr({telemetry:h,attributes:{"ai.response.finishReason":L.finishReason,"ai.response.text":{output:()=>m0(L.content)},"ai.response.toolCalls":{output:()=>{const Ie=E0(L.content);return Ie==null?void 0:JSON.stringify(Ie)}},"ai.response.providerMetadata":JSON.stringify(L.providerMetadata),"ai.usage.promptTokens":L.usage.inputTokens,"ai.usage.completionTokens":L.usage.outputTokens}}));const ge=le[le.length-1];let mt;return ge.finishReason==="stop"&&(mt=await(u==null?void 0:u.parseOutput({text:ge.text},{response:ge.response,usage:ge.usage,finishReason:ge.finishReason}))),new Oj({steps:le,resolvedOutput:mt})}})}catch(ve){throw l0(ve)}}async function Rj({toolCalls:t,tools:e,tracer:r,telemetry:a,messages:n,abortSignal:s,experimental_context:o}){return(await Promise.all(t.map(async({toolCallId:l,toolName:c,input:u})=>{const h=e[c];if((h==null?void 0:h.execute)!=null)return Wa({name:"ai.toolCall",attributes:hr({telemetry:a,attributes:{...Ka({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":c,"ai.toolCall.id":l,"ai.toolCall.args":{output:()=>JSON.stringify(u)}}}),tracer:r,fn:async g=>{try{const d=Ty({execute:h.execute.bind(h),input:u,options:{toolCallId:l,messages:n,abortSignal:s,experimental_context:o}});let f;for await(const v of d)v.type==="final"&&(f=v.output);try{g.setAttributes(hr({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(f)}}}))}catch{}return{type:"tool-result",toolCallId:l,toolName:c,input:u,output:f,dynamic:h.type==="dynamic"}}catch(d){return lf(g,d),{type:"tool-error",toolCallId:l,toolName:c,input:u,error:d,dynamic:h.type==="dynamic"}}}})}))).filter(l=>l!=null)}var Oj=class{constructor(t){this.steps=t.steps,this.resolvedOutput=t.resolvedOutput}get finalStep(){return this.steps[this.steps.length-1]}get content(){return this.finalStep.content}get text(){return this.finalStep.text}get files(){return this.finalStep.files}get reasoningText(){return this.finalStep.reasoningText}get reasoning(){return this.finalStep.reasoning}get toolCalls(){return this.finalStep.toolCalls}get staticToolCalls(){return this.finalStep.staticToolCalls}get dynamicToolCalls(){return this.finalStep.dynamicToolCalls}get toolResults(){return this.finalStep.toolResults}get staticToolResults(){return this.finalStep.staticToolResults}get dynamicToolResults(){return this.finalStep.dynamicToolResults}get sources(){return this.finalStep.sources}get finishReason(){return this.finalStep.finishReason}get warnings(){return this.finalStep.warnings}get providerMetadata(){return this.finalStep.providerMetadata}get response(){return this.finalStep.response}get request(){return this.finalStep.request}get usage(){return this.finalStep.usage}get totalUsage(){return this.steps.reduce((t,e)=>f0(t,e.usage),{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0})}get experimental_output(){if(this.resolvedOutput==null)throw new w_;return this.resolvedOutput}};function E0(t){const e=t.filter(r=>r.type==="tool-call");if(e.length!==0)return e.map(r=>({toolCallId:r.toolCallId,toolName:r.toolName,input:r.input}))}function Aj({content:t,toolCalls:e,toolOutputs:r}){return[...t.map(a=>{switch(a.type){case"text":case"reasoning":case"source":return a;case"file":return{type:"file",file:new v0(a)};case"tool-call":return e.find(n=>n.toolCallId===a.toolCallId);case"tool-result":{const n=e.find(s=>s.toolCallId===a.toolCallId);if(n==null)throw new Error(`Tool call ${a.toolCallId} not found.`);return a.isError?{type:"tool-error",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,error:a.result,providerExecuted:!0,dynamic:n.dynamic}:{type:"tool-result",toolCallId:a.toolCallId,toolName:a.toolName,input:n.input,output:a.result,providerExecuted:!0,dynamic:n.dynamic}}}}),...r]}function hl(t,e){const r=new Headers(t??{});for(const[a,n]of Object.entries(e))r.has(a)||r.set(a,n);return r}function Nj({status:t,statusText:e,headers:r,textStream:a}){return new Response(a.pipeThrough(new TextEncoderStream),{status:t??200,statusText:e,headers:hl(r,{"content-type":"text/plain; charset=utf-8"})})}function $0({response:t,status:e,statusText:r,headers:a,stream:n}){t.writeHead(e??200,r,a);const s=n.getReader();(async()=>{try{for(;;){const{done:i,value:l}=await s.read();if(i)break;t.write(l)||await new Promise(u=>{t.once("drain",u)})}}catch(i){throw i}finally{t.end()}})()}function Mj({response:t,status:e,statusText:r,headers:a,textStream:n}){$0({response:t,status:e,statusText:r,headers:Object.fromEntries(hl(a,{"content-type":"text/plain; charset=utf-8"}).entries()),stream:n.pipeThrough(new TextEncoderStream)})}var S0=class extends TransformStream{constructor(){super({transform(t,e){e.enqueue(`data: ${JSON.stringify(t)}
518
522
 
519
523
  `)},flush(t){t.enqueue(`data: [DONE]
520
524
 
521
- `)}})}},P0={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function Tj({status:t,statusText:e,headers:r,stream:a,consumeSseStream:n}){let s=a.pipeThrough(new $0);if(n){const[o,i]=s.tee();s=o,n({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:kl(r,P0)})}function Cj({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return(r==null?void 0:r.role)==="assistant"?r.id:typeof e=="function"?e():e}function Rj(t){return t.type.startsWith("data-")}function k0(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)){const n=e[a];if(n===void 0)continue;const s=a in t?t[a]:void 0,o=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);o&&i?r[a]=k0(s,n):r[a]=n}return r}function Oj(t){const e=["ROOT"];let r=-1,a=null;function n(l,c,u){switch(l){case'"':{r=c,e.pop(),e.push(u),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,a=c,e.pop(),e.push(u),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(u),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(u),e.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function o(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){const c=t[l];switch(e[e.length-1]){case"ROOT":n(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,n(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const f=t.substring(a,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l)):r=l;break}}}let i=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=t.substring(a,t.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function I0(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await oa({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await oa({text:Oj(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function vp(t){return t.type.startsWith("tool-")}function x0(t){return t.type.split("-").slice(1).join("-")}function Nj({lastMessage:t,messageId:e}){return{message:(t==null?void 0:t.role)==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Aj({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:a,onError:n,onToolCall:s,onData:o}){return t.pipeThrough(new TransformStream({async transform(i,l){await a(async({state:c,write:u})=>{var f,g,d,h;function v(b){const I=c.message.parts.filter(vp).find(k=>k.toolCallId===b);if(I==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return I}function m(b){const I=c.message.parts.filter(k=>k.type==="dynamic-tool").find(k=>k.toolCallId===b);if(I==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return I}function p(b){var S;const I=c.message.parts.find(O=>vp(O)&&O.toolCallId===b.toolCallId),k=b,A=I;I!=null?(I.state=b.state,A.input=k.input,A.output=k.output,A.errorText=k.errorText,A.rawInput=k.rawInput,A.preliminary=k.preliminary,A.providerExecuted=(S=k.providerExecuted)!=null?S:I.providerExecuted,k.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=k.providerMetadata)):c.message.parts.push({type:`tool-${b.toolName}`,toolCallId:b.toolCallId,state:b.state,input:k.input,output:k.output,rawInput:k.rawInput,errorText:k.errorText,providerExecuted:k.providerExecuted,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}function _(b){var S;const I=c.message.parts.find(O=>O.type==="dynamic-tool"&&O.toolCallId===b.toolCallId),k=b,A=I;I!=null?(I.state=b.state,A.toolName=b.toolName,A.input=k.input,A.output=k.output,A.errorText=k.errorText,A.rawInput=(S=k.rawInput)!=null?S:A.rawInput,A.preliminary=k.preliminary,k.providerMetadata!=null&&I.state==="input-available"&&(I.callProviderMetadata=k.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:b.toolName,toolCallId:b.toolCallId,state:b.state,input:k.input,output:k.output,errorText:k.errorText,preliminary:k.preliminary,...k.providerMetadata!=null?{callProviderMetadata:k.providerMetadata}:{}})}async function w(b){if(b!=null){const S=c.message.metadata!=null?k0(c.message.metadata,b):b;e!=null&&await tn({value:S,schema:e}),c.message.metadata=S}}switch(i.type){case"text-start":{const b={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=b,c.message.parts.push(b),u();break}case"text-delta":{const b=c.activeTextParts[i.id];b.text+=i.delta,b.providerMetadata=(f=i.providerMetadata)!=null?f:b.providerMetadata,u();break}case"text-end":{const b=c.activeTextParts[i.id];b.state="done",b.providerMetadata=(g=i.providerMetadata)!=null?g:b.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const b={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=b,c.message.parts.push(b),u();break}case"reasoning-delta":{const b=c.activeReasoningParts[i.id];b.text+=i.delta,b.providerMetadata=(d=i.providerMetadata)!=null?d:b.providerMetadata,u();break}case"reasoning-end":{const b=c.activeReasoningParts[i.id];b.providerMetadata=(h=i.providerMetadata)!=null?h:b.providerMetadata,b.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const b=c.message.parts.filter(vp);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:b.length,dynamic:i.dynamic},i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const b=c.partialToolCalls[i.toolCallId];b.text+=i.inputTextDelta;const{value:S}=await I0(b.text);b.dynamic?_({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:S}):p({toolCallId:i.toolCallId,toolName:b.toolName,state:"input-streaming",input:S}),u();break}case"tool-input-available":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?_({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-output-available":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-available",input:b.input,output:i.output,preliminary:i.preliminary})}else{const b=v(i.toolCallId);p({toolCallId:i.toolCallId,toolName:x0(b),state:"output-available",input:b.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}u();break}case"tool-output-error":{if(i.dynamic){const b=m(i.toolCallId);_({toolCallId:i.toolCallId,toolName:b.toolName,state:"output-error",input:b.input,errorText:i.errorText})}else{const b=v(i.toolCallId);p({toolCallId:i.toolCallId,toolName:x0(b),state:"output-error",input:b.input,rawInput:b.rawInput,errorText:i.errorText})}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 w(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{await w(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await w(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{n==null||n(new Error(i.errorText));break}default:if(Rj(i)){(r==null?void 0:r[i.type])!=null&&await tn({value:i.data,schema:r[i.type]});const b=i;if(b.transient){o==null||o(b);break}const S=b.id!=null?c.message.parts.find(I=>b.type===I.type&&b.id===I.id):void 0;S!=null?S.data=b.data:c.message.parts.push(b),o==null||o(b),u()}}l.enqueue(i)})}}))}function Mj({messageId:t,originalMessages:e=[],onFinish:r,onError:a,stream:n}){let s=e==null?void 0:e[e.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:t=s.id;let o=!1;const i=n.pipeThrough(new TransformStream({transform(g,d){if(g.type==="start"){const h=g;h.messageId==null&&t!=null&&(h.messageId=t)}g.type==="abort"&&(o=!0),d.enqueue(g)}}));if(r==null)return i;const l=Nj({lastMessage:s?structuredClone(s):void 0,messageId:t??""}),c=async g=>{await g({state:l,write:()=>{}})};let u=!1;const f=async()=>{if(u||!r)return;u=!0;const g=l.message.id===(s==null?void 0:s.id);await r({isAborted:o,isContinuation:g,responseMessage:l.message,messages:[...g?e.slice(0,-1):e,l.message]})};return Aj({stream:i,runUpdateMessageJob:c,onError:a}).pipeThrough(new TransformStream({transform(g,d){d.enqueue(g)},async cancel(){await f()},async flush(){await f()}}))}function jj({response:t,status:e,statusText:r,headers:a,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new $0);if(s){const[i,l]=o.tee();o=i,s({stream:l})}S0({response:t,status:e,statusText:r,headers:Object.fromEntries(kl(a,P0).entries()),stream:o.pipeThrough(new TextEncoderStream)})}function Il(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let a=!1;async function n(s){var o;a=!0;try{s&&await((o=r.cancel)==null?void 0:o.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(a)return{done:!0,value:void 0};const{done:s,value:o}=await r.read();return s?(await n(!0),{done:!0,value:void 0}):{done:!1,value:o}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(s){throw await n(!0),s}}},e}async function Dj({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:a}=await r.read();if(a)break}}catch(a){e==null||e(a)}finally{r.releaseLock()}}function T0(){let t,e;return{promise:new Promise((a,n)=>{t=a,e=n}),resolve:t,reject:e}}function Lj(){let t=[],e=null,r=!1,a=T0();const n=()=>{r=!0,a.resolve(),t.forEach(o=>o.cancel()),t=[],e==null||e.close()},s=async()=>{if(r&&t.length===0){e==null||e.close();return}if(t.length===0)return a=T0(),await a.promise,s();try{const{value:o,done:i}=await t[0].read();i?(t.shift(),t.length>0?await s():r&&(e==null||e.close())):e==null||e.enqueue(o)}catch(o){e==null||e.error(o),t.shift(),n()}};return{stream:new ReadableStream({start(o){e=o},pull:s,async cancel(){for(const o of t)await o.cancel();t=[],r=!0}}),addStream:o=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(o.getReader()),a.resolve()},close:()=>{r=!0,a.resolve(),t.length===0&&(e==null||e.close())},terminate:n}}var xl=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}};function zj(){var t,e;return(e=(t=globalThis==null?void 0:globalThis.performance)==null?void 0:t.now())!=null?e:Date.now()}function Uj({tools:t,generatorStream:e,tracer:r,telemetry:a,system:n,messages:s,abortSignal:o,repairToolCall:i,experimental_context:l}){let c=null;const u=new ReadableStream({start(p){c=p}}),f=new Set,g=new Map;let d=!1,h;function v(){d&&f.size===0&&(h!=null&&c.enqueue(h),c.close())}const m=new TransformStream({async transform(p,_){const w=p.type;switch(w){case"stream-start":case"text-start":case"text-delta":case"text-end":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"tool-input-start":case"tool-input-delta":case"tool-input-end":case"source":case"response-metadata":case"error":case"raw":{_.enqueue(p);break}case"file":{_.enqueue({type:"file",file:new bj({data:p.data,mediaType:p.mediaType})});break}case"finish":{h={type:"finish",finishReason:p.finishReason,usage:p.usage,providerMetadata:p.providerMetadata};break}case"tool-call":{try{const b=await g0({toolCall:p,tools:t,repairToolCall:i,system:n,messages:s});if(_.enqueue(b),b.invalid){c.enqueue({type:"tool-error",toolCallId:b.toolCallId,toolName:b.toolName,input:b.input,error:Ud(b.error),dynamic:!0});break}const S=t[b.toolName];if(g.set(b.toolCallId,b.input),S.onInputAvailable!=null&&await S.onInputAvailable({input:b.input,toolCallId:b.toolCallId,messages:s,abortSignal:o,experimental_context:l}),S.execute!=null&&b.providerExecuted!==!0){const I=sr();f.add(I),rs({name:"ai.toolCall",attributes:br({telemetry:a,attributes:{...ts({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":b.toolName,"ai.toolCall.id":b.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(b.input)}}}),tracer:r,fn:async k=>{let A;try{const O=Py({execute:S.execute.bind(S),input:b.input,options:{toolCallId:b.toolCallId,messages:s,abortSignal:o,experimental_context:l}});for await(const H of O)c.enqueue({...b,type:"tool-result",output:H.output,...H.type==="preliminary"&&{preliminary:!0}}),H.type==="final"&&(A=H.output)}catch(O){dp(k,O),c.enqueue({...b,type:"tool-error",error:O}),f.delete(I),v();return}f.delete(I),v();try{k.setAttributes(br({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(A)}}}))}catch{}}})}}catch(b){c.enqueue({type:"error",error:b})}break}case"tool-result":{const b=p.toolName;p.isError?c.enqueue({type:"tool-error",toolCallId:p.toolCallId,toolName:b,input:g.get(p.toolCallId),providerExecuted:p.providerExecuted,error:p.result}):_.enqueue({type:"tool-result",toolCallId:p.toolCallId,toolName:b,input:g.get(p.toolCallId),output:p.result,providerExecuted:p.providerExecuted});break}default:{const b=w;throw new Error(`Unhandled chunk type: ${b}`)}}},flush(){d=!0,v()}});return new ReadableStream({async start(p){return Promise.all([e.pipeThrough(m).pipeTo(new WritableStream({write(_){p.enqueue(_)},close(){}})),u.pipeTo(new WritableStream({write(_){p.enqueue(_)},close(){p.close()}}))])}})}var qj=io({prefix:"aitxt",size:24});function Fj({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:c=fp(1),experimental_output:u,experimental_telemetry:f,prepareStep:g,providerOptions:d,experimental_activeTools:h,activeTools:v=h,experimental_repairToolCall:m,experimental_transform:p,experimental_download:_,includeRawChunks:w=!1,onChunk:b,onError:S=({error:U})=>{console.error(U)},onFinish:I,onAbort:k,onStepFinish:A,experimental_context:O,_internal:{now:H=zj,generateId:J=qj,currentDate:K=()=>new Date}={},...z}){return new Vj({model:Sl(t),telemetry:f,headers:l,settings:z,maxRetries:o,abortSignal:i,system:a,prompt:n,messages:s,tools:e,toolChoice:r,transforms:pp(p),activeTools:v,repairToolCall:m,stopConditions:pp(c),output:u,providerOptions:d,prepareStep:g,includeRawChunks:w,onChunk:b,onError:S,onFinish:I,onAbort:k,onStepFinish:A,now:H,currentDate:K,generateId:J,experimental_context:O,download:_})}function Zj(t){if(!t)return new TransformStream({transform(o,i){i.enqueue({part:o,partialOutput:void 0})}});let e,r="",a="",n="";function s({controller:o,partialOutput:i=void 0}){o.enqueue({part:{type:"text-delta",id:e,text:a},partialOutput:i}),a=""}return new TransformStream({async transform(o,i){if(o.type==="finish-step"&&a.length>0&&s({controller:i}),o.type!=="text-delta"&&o.type!=="text-start"&&o.type!=="text-end"){i.enqueue({part:o,partialOutput:void 0});return}if(e==null)e=o.id;else if(o.id!==e){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-start"){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-end"){a.length>0&&s({controller:i}),i.enqueue({part:o,partialOutput:void 0});return}r+=o.text,a+=o.text;const l=await t.parsePartial({text:r});if(l!=null){const c=JSON.stringify(l.partial);c!==n&&(s({controller:i,partialOutput:l.partial}),n=c)}}})}var Vj=class{constructor({model:t,telemetry:e,headers:r,settings:a,maxRetries:n,abortSignal:s,system:o,prompt:i,messages:l,tools:c,toolChoice:u,transforms:f,activeTools:g,repairToolCall:d,stopConditions:h,output:v,providerOptions:m,prepareStep:p,includeRawChunks:_,now:w,currentDate:b,generateId:S,onChunk:I,onError:k,onFinish:A,onAbort:O,onStepFinish:H,experimental_context:J,download:K}){this._totalUsage=new xl,this._finishReason=new xl,this._steps=new xl,this.output=v,this.includeRawChunks=_,this.tools=c;let z,U=[];const G=[];let se,ne,ce={},pe=[];const M=[];let R,D={},N={};const y=new TransformStream({async transform(me,Ne){var Ae,ke,tt,Ze;Ne.enqueue(me);const{part:re}=me;if((re.type==="text-delta"||re.type==="reasoning-delta"||re.type==="source"||re.type==="tool-call"||re.type==="tool-result"||re.type==="tool-input-start"||re.type==="tool-input-delta"||re.type==="raw")&&await(I==null?void 0:I({chunk:re})),re.type==="error"&&await k({error:l0(re.error)}),re.type==="text-start"&&(D[re.id]={type:"text",text:"",providerMetadata:re.providerMetadata},U.push(D[re.id])),re.type==="text-delta"){const ze=D[re.id];if(ze==null){Ne.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}ze.text+=re.text,ze.providerMetadata=(Ae=re.providerMetadata)!=null?Ae:ze.providerMetadata}if(re.type==="text-end"){const ze=D[re.id];if(ze==null){Ne.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}ze.providerMetadata=(ke=re.providerMetadata)!=null?ke:ze.providerMetadata,delete D[re.id]}if(re.type==="reasoning-start"&&(N[re.id]={type:"reasoning",text:"",providerMetadata:re.providerMetadata},U.push(N[re.id])),re.type==="reasoning-delta"){const ze=N[re.id];if(ze==null){Ne.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}ze.text+=re.text,ze.providerMetadata=(tt=re.providerMetadata)!=null?tt:ze.providerMetadata}if(re.type==="reasoning-end"){const ze=N[re.id];if(ze==null){Ne.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}ze.providerMetadata=(Ze=re.providerMetadata)!=null?Ze:ze.providerMetadata,delete N[re.id]}if(re.type==="file"&&U.push({type:"file",file:re.file}),re.type==="source"&&U.push(re),re.type==="tool-call"&&U.push(re),re.type==="tool-result"&&!re.preliminary&&U.push(re),re.type==="tool-error"&&U.push(re),re.type==="start-step"&&(ce=re.request,pe=re.warnings),re.type==="finish-step"){const ze=mp({content:U,tools:c}),Be=new _0({content:U,finishReason:re.finishReason,usage:re.usage,warnings:pe,request:ce,response:{...re.response,messages:[...G,...ze]},providerMetadata:re.providerMetadata});await(H==null?void 0:H(Be)),b_(pe),M.push(Be),U=[],N={},D={},G.push(...ze),z.resolve()}re.type==="finish"&&(ne=re.totalUsage,se=re.finishReason)},async flush(me){try{if(M.length===0){const tt=new UM({message:"No output generated. Check the stream for errors."});Te._finishReason.reject(tt),Te._totalUsage.reject(tt),Te._steps.reject(tt);return}const Ne=se??"unknown",Ae=ne??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};Te._finishReason.resolve(Ne),Te._totalUsage.resolve(Ae),Te._steps.resolve(M);const ke=M[M.length-1];await(A==null?void 0:A({finishReason:Ne,totalUsage:Ae,usage:ke.usage,content:ke.content,text:ke.text,reasoningText:ke.reasoningText,reasoning:ke.reasoning,files:ke.files,sources:ke.sources,toolCalls:ke.toolCalls,staticToolCalls:ke.staticToolCalls,dynamicToolCalls:ke.dynamicToolCalls,toolResults:ke.toolResults,staticToolResults:ke.staticToolResults,dynamicToolResults:ke.dynamicToolResults,request:ke.request,response:ke.response,warnings:ke.warnings,providerMetadata:ke.providerMetadata,steps:M})),R.setAttributes(br({telemetry:e,attributes:{"ai.response.finishReason":Ne,"ai.response.text":{output:()=>ke.text},"ai.response.toolCalls":{output:()=>{var tt;return(tt=ke.toolCalls)!=null&&tt.length?JSON.stringify(ke.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(ke.providerMetadata),"ai.usage.inputTokens":Ae.inputTokens,"ai.usage.outputTokens":Ae.outputTokens,"ai.usage.totalTokens":Ae.totalTokens,"ai.usage.reasoningTokens":Ae.reasoningTokens,"ai.usage.cachedInputTokens":Ae.cachedInputTokens}}))}catch(Ne){me.error(Ne)}finally{R.end()}}}),P=Lj();this.addStream=P.addStream,this.closeStream=P.close;const j=P.stream.getReader();let Q=new ReadableStream({async start(me){me.enqueue({type:"start"})},async pull(me){function Ne(){O==null||O({steps:M}),me.enqueue({type:"abort"}),me.close()}try{const{done:Ae,value:ke}=await j.read();if(Ae){me.close();return}if(s!=null&&s.aborted){Ne();return}me.enqueue(ke)}catch(Ae){sa(Ae)&&(s!=null&&s.aborted)?Ne():me.error(Ae)}},cancel(me){return P.stream.cancel(me)}});for(const me of f)Q=Q.pipeThrough(me({tools:c,stopStream(){P.terminate()}}));this.baseStream=Q.pipeThrough(Zj(v)).pipeThrough(y);const{maxRetries:ee,retry:Se}=h0({maxRetries:n,abortSignal:s}),de=u0(e),ge=up(a),vt=c0({model:t,telemetry:e,headers:r,settings:{...ge,maxRetries:ee}}),Te=this;rs({name:"ai.streamText",attributes:br({telemetry:e,attributes:{...ts({operationId:"ai.streamText",telemetry:e}),...vt,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:l})}}}),tracer:de,endWhenDone:!1,fn:async me=>{R=me;async function Ne({currentStep:Ae,responseMessages:ke,usage:tt}){var Ze,re,ze,Be,Ee;const Qe=Te.includeRawChunks;z=new xl;const ir=await i0({system:o,prompt:i,messages:l}),Mt=[...ir.messages,...ke],wt=await(p==null?void 0:p({model:t,steps:M,stepNumber:M.length,messages:Mt})),lr=Sl((Ze=wt==null?void 0:wt.model)!=null?Ze:t),jt=await r0({prompt:{system:(re=wt==null?void 0:wt.system)!=null?re:ir.system,messages:(ze=wt==null?void 0:wt.messages)!=null?ze:Mt},supportedUrls:await lr.supportedUrls,download:K}),{toolChoice:cr,tools:bn}=n0({tools:c,toolChoice:(Be=wt==null?void 0:wt.toolChoice)!=null?Be:u,activeTools:(Ee=wt==null?void 0:wt.activeTools)!=null?Ee:g}),{result:{stream:fa,response:ut,request:Er},doStreamSpan:qr,startTimestampMs:$o}=await Se(()=>rs({name:"ai.streamText.doStream",attributes:br({telemetry:e,attributes:{...ts({operationId:"ai.streamText.doStream",telemetry:e}),...vt,"ai.model.provider":lr.provider,"ai.model.id":lr.modelId,"ai.prompt.messages":{input:()=>d0(jt)},"ai.prompt.tools":{input:()=>bn==null?void 0:bn.map(we=>JSON.stringify(we))},"ai.prompt.toolChoice":{input:()=>cr!=null?JSON.stringify(cr):void 0},"gen_ai.system":lr.provider,"gen_ai.request.model":lr.modelId,"gen_ai.request.frequency_penalty":ge.frequencyPenalty,"gen_ai.request.max_tokens":ge.maxOutputTokens,"gen_ai.request.presence_penalty":ge.presencePenalty,"gen_ai.request.stop_sequences":ge.stopSequences,"gen_ai.request.temperature":ge.temperature,"gen_ai.request.top_k":ge.topK,"gen_ai.request.top_p":ge.topP}}),tracer:de,endWhenDone:!1,fn:async we=>({startTimestampMs:w(),doStreamSpan:we,result:await lr.doStream({...ge,tools:bn,toolChoice:cr,responseFormat:v==null?void 0:v.responseFormat,prompt:jt,providerOptions:m,abortSignal:s,headers:r,includeRawChunks:Qe})})})),Sr=Uj({tools:c,generatorStream:fa,tracer:de,telemetry:e,system:o,messages:Mt,repairToolCall:d,abortSignal:s,experimental_context:J}),wp=Er??{},ns=[],Po=[];let ko;const Io={};let Un="unknown",Dt={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},xo,To=!0,$r={id:S(),timestamp:b(),modelId:t.modelId},as="";Te.addStream(Sr.pipeThrough(new TransformStream({async transform(we,Ot){var qn,ha,ma,T;if(we.type==="stream-start"){ko=we.warnings;return}if(To){const C=w()-$o;To=!1,qr.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":C}),qr.setAttributes({"ai.response.msToFirstChunk":C}),Ot.enqueue({type:"start-step",request:wp,warnings:ko??[]})}const $=we.type;switch($){case"text-start":case"text-end":{Ot.enqueue(we);break}case"text-delta":{we.delta.length>0&&(Ot.enqueue({type:"text-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata}),as+=we.delta);break}case"reasoning-start":case"reasoning-end":{Ot.enqueue(we);break}case"reasoning-delta":{Ot.enqueue({type:"reasoning-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata});break}case"tool-call":{Ot.enqueue(we),ns.push(we);break}case"tool-result":{Ot.enqueue(we),we.preliminary||Po.push(we);break}case"tool-error":{Ot.enqueue(we),Po.push(we);break}case"response-metadata":{$r={id:(qn=we.id)!=null?qn:$r.id,timestamp:(ha=we.timestamp)!=null?ha:$r.timestamp,modelId:(ma=we.modelId)!=null?ma:$r.modelId};break}case"finish":{Dt=we.usage,Un=we.finishReason,xo=we.providerMetadata;const C=w()-$o;qr.addEvent("ai.stream.finish"),qr.setAttributes({"ai.response.msToFinish":C,"ai.response.avgOutputTokensPerSecond":1e3*((T=Dt.outputTokens)!=null?T:0)/C});break}case"file":{Ot.enqueue(we);break}case"source":{Ot.enqueue(we);break}case"tool-input-start":{Io[we.id]=we.toolName;const C=c==null?void 0:c[we.toolName];(C==null?void 0:C.onInputStart)!=null&&await C.onInputStart({toolCallId:we.id,messages:Mt,abortSignal:s,experimental_context:J}),Ot.enqueue({...we,dynamic:(C==null?void 0:C.type)==="dynamic"});break}case"tool-input-end":{delete Io[we.id],Ot.enqueue(we);break}case"tool-input-delta":{const C=Io[we.id],q=c==null?void 0:c[C];(q==null?void 0:q.onInputDelta)!=null&&await q.onInputDelta({inputTextDelta:we.delta,toolCallId:we.id,messages:Mt,abortSignal:s,experimental_context:J}),Ot.enqueue(we);break}case"error":{Ot.enqueue(we),Un="error";break}case"raw":{Qe&&Ot.enqueue(we);break}default:{const C=$;throw new Error(`Unknown chunk type: ${C}`)}}},async flush(we){const Ot=ns.length>0?JSON.stringify(ns):void 0;try{qr.setAttributes(br({telemetry:e,attributes:{"ai.response.finishReason":Un,"ai.response.text":{output:()=>as},"ai.response.toolCalls":{output:()=>Ot},"ai.response.id":$r.id,"ai.response.model":$r.modelId,"ai.response.timestamp":$r.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(xo),"ai.usage.inputTokens":Dt.inputTokens,"ai.usage.outputTokens":Dt.outputTokens,"ai.usage.totalTokens":Dt.totalTokens,"ai.usage.reasoningTokens":Dt.reasoningTokens,"ai.usage.cachedInputTokens":Dt.cachedInputTokens,"gen_ai.response.finish_reasons":[Un],"gen_ai.response.id":$r.id,"gen_ai.response.model":$r.modelId,"gen_ai.usage.input_tokens":Dt.inputTokens,"gen_ai.usage.output_tokens":Dt.outputTokens}}))}catch{}finally{qr.end()}we.enqueue({type:"finish-step",finishReason:Un,usage:Dt,providerMetadata:xo,response:{...$r,headers:ut==null?void 0:ut.headers}});const qn=p0(tt,Dt);await z.promise;const ha=ns.filter(T=>T.providerExecuted!==!0),ma=Po.filter(T=>T.providerExecuted!==!0);if(ha.length>0&&ma.length===ha.length&&!await w0({stopConditions:h,steps:M})){ke.push(...mp({content:M[M.length-1].content,tools:c}));try{await Ne({currentStep:Ae+1,responseMessages:ke,usage:qn})}catch(T){we.enqueue({type:"error",error:T}),Te.closeStream()}}else we.enqueue({type:"finish",finishReason:Un,totalUsage:qn}),Te.closeStream()}})))}await Ne({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(me=>{Te.addStream(new ReadableStream({start(Ne){Ne.enqueue({type:"error",error:me}),Ne.close()}})),Te.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return Il(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return Il(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await Dj({stream:this.fullStream,onError:t==null?void 0:t.onError})}catch(r){(e=t==null?void 0:t.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new __;return Il(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n=!0,sendSources:s=!1,sendStart:o=!0,sendFinish:i=!0,onError:l=Qa}={}){const c=e!=null?Cj({originalMessages:t,responseMessageId:e}):void 0,u={},f=d=>{var h,v;const m=u[d];return((v=(h=this.tools)==null?void 0:h[m])==null?void 0:v.type)==="dynamic"?!0:void 0},g=this.fullStream.pipeThrough(new TransformStream({transform:async(d,h)=>{const v=a==null?void 0:a({part:d}),m=d.type;switch(m){case"text-start":{h.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{h.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{n&&h.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{h.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{s&&d.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),s&&d.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{u[d.id]=d.toolName;const p=f(d.id);h.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{u[d.toolCallId]=d.toolName;const p=f(d.toolCallId);d.invalid?h.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...p!=null?{dynamic:p}:{},errorText:l(d.error)}):h.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...p!=null?{dynamic:p}:{}});break}case"tool-result":{const p=f(d.toolCallId);h.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...p!=null?{dynamic:p}:{}});break}case"tool-error":{const p=f(d.toolCallId);h.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"error":{h.enqueue({type:"error",errorText:l(d.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{o&&h.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&h.enqueue({type:"finish",...v!=null?{messageMetadata:v}:{}});break}case"abort":{h.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const p=m;throw new Error(`Unknown chunk type: ${p}`)}}v!=null&&m!=="start"&&m!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:v})}}));return Il(Mj({stream:g,messageId:c??(e==null?void 0:e()),originalMessages:t,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:c,...u}={}){jj({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(t,e){xj({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l,...c}={}){return Tj({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l}),...c})}toTextStreamResponse(t){return Ij({textStream:this.textStream,...t})}};io({prefix:"aiobj",size:24}),io({prefix:"aiobj",size:24});var Hj={};CM(Hj,{object:()=>Jj,text:()=>Bj});var Bj=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),Jj=({schema:t})=>{const e=gl(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const a=await I0(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value};default:{const n=a.state;throw new Error(`Unsupported parse state: ${n}`)}}},async parseOutput({text:r},a){const n=await oa({text:r});if(!n.success)throw new A_({message:"No object generated: could not parse the response.",cause:n.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=await Dr({value:n.value,schema:e});if(!s.success)throw new A_({message:"No object generated: response did not match schema.",cause:s.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value}}},C0="2025-06-18",Gj=[C0,"2025-03-26","2024-11-05"],Kj=Ya({name:E(),version:E()}),gp=Ya({_meta:It(x({}).loose())}),Eo=gp,Wj=x({method:E(),params:It(gp)}),Qj=Ya({experimental:It(x({}).loose()),logging:It(x({}).loose()),prompts:It(Ya({listChanged:It(Pt())})),resources:It(Ya({subscribe:It(Pt()),listChanged:It(Pt())})),tools:It(Ya({listChanged:It(Pt())}))}),Yj=Eo.extend({protocolVersion:E(),capabilities:Qj,serverInfo:Kj,instructions:It(E())}),Xj=Eo.extend({nextCursor:It(E())}),e9=x({name:E(),description:It(E()),inputSchema:x({type:W("object"),properties:It(x({}).loose())}).loose()}).loose(),t9=Xj.extend({tools:oe(e9)}),r9=x({type:W("text"),text:E()}).loose(),n9=x({type:W("image"),data:ny(),mimeType:E()}).loose(),R0=x({uri:E(),mimeType:It(E())}).loose(),a9=R0.extend({text:E()}),s9=R0.extend({blob:ny()}),o9=x({type:W("resource"),resource:He([a9,s9])}).loose(),i9=Eo.extend({content:oe(He([r9,n9,o9])),isError:Pt().default(!1).optional()}).or(Eo.extend({toolResult:jr()})),Tl="2.0",l9=x({jsonrpc:W(Tl),id:He([E(),Z().int()])}).merge(Wj).strict(),c9=x({jsonrpc:W(Tl),id:He([E(),Z().int()]),result:Eo}).strict(),u9=x({jsonrpc:W(Tl),id:He([E(),Z().int()]),error:x({code:Z().int(),message:E(),data:It(jr())})}).strict(),d9=x({jsonrpc:W(Tl)}).merge(x({method:E(),params:It(gp)})).strict(),p9=He([l9,d9,c9,u9]),f9=class{constructor({url:t,headers:e}){this.connected=!1,this.url=new URL(t),this.headers=e}async start(){return new Promise((t,e)=>{if(this.connected)return t();this.abortController=new AbortController,(async()=>{var a,n,s;try{const o=wn({...this.headers,Accept:"text/event-stream"},`ai-sdk/${$l}`,lo()),i=await fetch(this.url.href,{headers:o,signal:(a=this.abortController)==null?void 0:a.signal});if(!i.ok||!i.body){const f=new At({message:`MCP SSE Transport Error: ${i.status} ${i.statusText}`});return(n=this.onerror)==null||n.call(this,f),e(f)}const c=i.body.pipeThrough(new TextDecoderStream).pipeThrough(new rd).getReader(),u=async()=>{var f,g,d;try{for(;;){const{done:h,value:v}=await c.read();if(h){if(this.connected)throw this.connected=!1,new At({message:"MCP SSE Transport Error: Connection closed unexpectedly"});return}const{event:m,data:p}=v;if(m==="endpoint"){if(this.endpoint=new URL(p,this.url),this.endpoint.origin!==this.url.origin)throw new At({message:`MCP SSE Transport Error: Endpoint origin does not match connection origin: ${this.endpoint.origin}`});this.connected=!0,t()}else if(m==="message")try{const _=p9.parse(JSON.parse(p));(f=this.onmessage)==null||f.call(this,_)}catch(_){const w=new At({message:"MCP SSE Transport Error: Failed to parse message",cause:_});(g=this.onerror)==null||g.call(this,w)}}}catch(h){if(h instanceof Error&&h.name==="AbortError")return;(d=this.onerror)==null||d.call(this,h),e(h)}};this.sseConnection={close:()=>c.cancel()},u()}catch(o){if(o instanceof Error&&o.name==="AbortError")return;(s=this.onerror)==null||s.call(this,o),e(o)}})()})}async close(){var t,e,r;this.connected=!1,(t=this.sseConnection)==null||t.close(),(e=this.abortController)==null||e.abort(),(r=this.onclose)==null||r.call(this)}async send(t){var e,r,a;if(!this.endpoint||!this.connected)throw new At({message:"MCP SSE Transport Error: Not connected"});try{const s={method:"POST",headers:wn({...this.headers,"Content-Type":"application/json"},`ai-sdk/${$l}`,lo()),body:JSON.stringify(t),signal:(e=this.abortController)==null?void 0:e.signal},o=await fetch(this.endpoint,s);if(!o.ok){const i=await o.text().catch(()=>null),l=new At({message:`MCP SSE Transport Error: POSTing to endpoint (HTTP ${o.status}): ${i}`});(r=this.onerror)==null||r.call(this,l);return}}catch(n){(a=this.onerror)==null||a.call(this,n);return}}};function h9(t){if(t.type!=="sse")throw new At({message:"Unsupported or invalid transport configuration. If you are using a custom transport, make sure it implements the MCPTransport interface."});return new f9(t)}function m9(t){return"start"in t&&typeof t.start=="function"&&"send"in t&&typeof t.send=="function"&&"close"in t&&typeof t.close=="function"}var v9="1.0.0";async function g9(t){const e=new y9(t);return await e.init(),e}var y9=class{constructor({transport:t,name:e="ai-sdk-mcp-client",onUncaughtError:r}){this.requestMessageId=0,this.responseHandlers=new Map,this.serverCapabilities={},this.isClosed=!0,this.onUncaughtError=r,m9(t)?this.transport=t:this.transport=h9(t),this.transport.onclose=()=>this.onClose(),this.transport.onerror=a=>this.onError(a),this.transport.onmessage=a=>{if("method"in a){this.onError(new At({message:"Unsupported message type"}));return}this.onResponse(a)},this.clientInfo={name:e,version:v9}}async init(){try{await this.transport.start(),this.isClosed=!1;const t=await this.request({request:{method:"initialize",params:{protocolVersion:C0,capabilities:{},clientInfo:this.clientInfo}},resultSchema:Yj});if(t===void 0)throw new At({message:"Server sent invalid initialize result"});if(!Gj.includes(t.protocolVersion))throw new At({message:`Server's protocol version is not supported: ${t.protocolVersion}`});return this.serverCapabilities=t.capabilities,await this.notification({method:"notifications/initialized"}),this}catch(t){throw await this.close(),t}}async close(){var t;this.isClosed||(await((t=this.transport)==null?void 0:t.close()),this.onClose())}assertCapability(t){switch(t){case"initialize":break;case"tools/list":case"tools/call":if(!this.serverCapabilities.tools)throw new At({message:"Server does not support tools"});break;default:throw new At({message:`Unsupported method: ${t}`})}}async request({request:t,resultSchema:e,options:r}){return new Promise((a,n)=>{if(this.isClosed)return n(new At({message:"Attempted to send a request from a closed client"}));this.assertCapability(t.method);const s=r==null?void 0:r.signal;s==null||s.throwIfAborted();const o=this.requestMessageId++,i={...t,jsonrpc:"2.0",id:o},l=()=>{this.responseHandlers.delete(o)};this.responseHandlers.set(o,c=>{if(s!=null&&s.aborted)return n(new At({message:"Request was aborted",cause:s.reason}));if(c instanceof Error)return n(c);try{const u=e.parse(c.result);a(u)}catch(u){const f=new At({message:"Failed to parse server response",cause:u});n(f)}}),this.transport.send(i).catch(c=>{l(),n(c)})})}async listTools({params:t,options:e}={}){try{return this.request({request:{method:"tools/list",params:t},resultSchema:t9,options:e})}catch(r){throw r}}async callTool({name:t,args:e,options:r}){try{return this.request({request:{method:"tools/call",params:{name:t,arguments:e}},resultSchema:i9,options:{signal:r==null?void 0:r.abortSignal}})}catch(a){throw a}}async notification(t){const e={...t,jsonrpc:"2.0"};await this.transport.send(e)}async tools({schemas:t="automatic"}={}){var e;const r={};try{const a=await this.listTools();for(const{name:n,description:s,inputSchema:o}of a.tools){if(t!=="automatic"&&!(n in t))continue;const i=this,l=async(u,f)=>{var g;return(g=f==null?void 0:f.abortSignal)==null||g.throwIfAborted(),i.callTool({name:n,args:u,options:f})},c=t==="automatic"?yy({description:s,inputSchema:po({...o,properties:(e=o.properties)!=null?e:{},additionalProperties:!1}),execute:l}):{description:s,inputSchema:t[n].inputSchema,execute:l};r[n]=c}return r}catch(a){throw a}}onClose(){if(this.isClosed)return;this.isClosed=!0;const t=new At({message:"Connection closed"});for(const e of this.responseHandlers.values())e(t);this.responseHandlers.clear()}onError(t){this.onUncaughtError&&this.onUncaughtError(t)}onResponse(t){const e=Number(t.id),r=this.responseHandlers.get(e);if(r===void 0)throw new At({message:`Protocol error: Received a response for an unknown message ID: ${JSON.stringify(t)}`});this.responseHandlers.delete(e),r("result"in t?t:new At({message:t.error.message,code:t.error.code,data:t.error.data,cause:t.error}))}},yp=x({error:x({message:E(),type:E().nullish(),param:wr().nullish(),code:He([E(),Z()]).nullish()})}),on=ia({errorSchema:yp,errorToMessage:t=>t.error.message});function _9({prompt:t,systemMessageMode:e="system"}){const r=[],a=[];for(const{role:n,content:s}of t)switch(n){case"system":{switch(e){case"system":{r.push({role:"system",content:s});break}case"developer":{r.push({role:"developer",content:s});break}case"remove":{a.push({type:"other",message:"system messages are removed for this model"});break}default:{const o=e;throw new Error(`Unsupported system message mode: ${o}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){r.push({role:"user",content:s[0].text});break}r.push({role:"user",content:s.map((o,i)=>{var l,c,u;switch(o.type){case"text":return{type:"text",text:o.text};case"file":if(o.mediaType.startsWith("image/")){const f=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${f};base64,${la(o.data)}`,detail:(c=(l=o.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(o.mediaType.startsWith("audio/")){if(o.data instanceof URL)throw new Mr({functionality:"audio file parts with URLs"});switch(o.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:la(o.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:la(o.data),format:"mp3"}};default:throw new Mr({functionality:`audio content parts with media type ${o.mediaType}`})}}else if(o.mediaType==="application/pdf"){if(o.data instanceof URL)throw new Mr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof o.data=="string"&&o.data.startsWith("file-")?{file_id:o.data}:{filename:(u=o.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${la(o.data)}`}}}else throw new Mr({functionality:`file part media type ${o.mediaType}`})}})});break}case"assistant":{let o="";const i=[];for(const l of s)switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const o of s){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:o.toolCallId,content:l})}break}default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return{messages:r,warnings:a}}function O0({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function N0(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var w9=_t(()=>De(x({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(x({message:x({role:W("assistant").nullish(),content:E().nullish(),tool_calls:oe(x({id:E().nullish(),type:W("function"),function:x({name:E(),arguments:E()})})).nullish(),annotations:oe(x({type:W("url_citation"),start_index:Z(),end_index:Z(),url:E(),title:E()})).nullish()}),index:Z(),logprobs:x({content:oe(x({token:E(),logprob:Z(),top_logprobs:oe(x({token:E(),logprob:Z()}))})).nullish()}).nullish(),finish_reason:E().nullish()})),usage:x({prompt_tokens:Z().nullish(),completion_tokens:Z().nullish(),total_tokens:Z().nullish(),prompt_tokens_details:x({cached_tokens:Z().nullish()}).nullish(),completion_tokens_details:x({reasoning_tokens:Z().nullish(),accepted_prediction_tokens:Z().nullish(),rejected_prediction_tokens:Z().nullish()}).nullish()}).nullish()}))),b9=_t(()=>De(He([x({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(x({delta:x({role:ht(["assistant"]).nullish(),content:E().nullish(),tool_calls:oe(x({index:Z(),id:E().nullish(),type:W("function").nullish(),function:x({name:E().nullish(),arguments:E().nullish()})})).nullish(),annotations:oe(x({type:W("url_citation"),start_index:Z(),end_index:Z(),url:E(),title:E()})).nullish()}).nullish(),logprobs:x({content:oe(x({token:E(),logprob:Z(),top_logprobs:oe(x({token:E(),logprob:Z()}))})).nullish()}).nullish(),finish_reason:E().nullish(),index:Z()})),usage:x({prompt_tokens:Z().nullish(),completion_tokens:Z().nullish(),total_tokens:Z().nullish(),prompt_tokens_details:x({cached_tokens:Z().nullish()}).nullish(),completion_tokens_details:x({reasoning_tokens:Z().nullish(),accepted_prediction_tokens:Z().nullish(),rejected_prediction_tokens:Z().nullish()}).nullish()}).nullish()}),yp]))),E9=_t(()=>De(x({logitBias:kt(mN(),Z()).optional(),logprobs:He([Pt(),Z()]).optional(),parallelToolCalls:Pt().optional(),user:E().optional(),reasoningEffort:ht(["minimal","low","medium","high"]).optional(),maxCompletionTokens:Z().optional(),store:Pt().optional(),metadata:kt(E().max(64),E().max(512)).optional(),prediction:kt(E(),wr()).optional(),structuredOutputs:Pt().optional(),serviceTier:ht(["auto","flex","priority","default"]).optional(),strictJsonSchema:Pt().optional(),textVerbosity:ht(["low","medium","high"]).optional(),promptCacheKey:E().optional(),safetyIdentifier:E().optional()})));function S9({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:a}){t=t!=null&&t.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const i of t)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?a:void 0}});break;default:n.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:n};default:{const i=o;throw new Mr({functionality:`tool choice type: ${i}`})}}}var $9=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:f,providerOptions:g}){var d,h,v,m;const p=[],_=(d=await rn({provider:"openai",providerOptions:g,schema:E9}))!=null?d:{},w=(h=_.structuredOutputs)!=null?h:!0;n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!w&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:b,warnings:S}=_9({prompt:t,systemMessageMode:I9(this.modelId)});p.push(...S);const I=(v=_.strictJsonSchema)!=null?v:!1,k={model:this.modelId,logit_bias:_.logitBias,logprobs:_.logprobs===!0||typeof _.logprobs=="number"?!0:void 0,top_logprobs:typeof _.logprobs=="number"?_.logprobs:typeof _.logprobs=="boolean"&&_.logprobs?0:void 0,user:_.user,parallel_tool_calls:_.parallelToolCalls,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(l==null?void 0:l.type)==="json"?w&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:I,name:(m=l.name)!=null?m:"response",description:l.description}}:{type:"json_object"}:void 0,stop:i,seed:c,verbosity:_.textVerbosity,max_completion_tokens:_.maxCompletionTokens,store:_.store,metadata:_.metadata,prediction:_.prediction,reasoning_effort:_.reasoningEffort,service_tier:_.serviceTier,prompt_cache_key:_.promptCacheKey,safety_identifier:_.safetyIdentifier,messages:b};A0(this.modelId)?(k.temperature!=null&&(k.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),k.top_p!=null&&(k.top_p=void 0,p.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),k.frequency_penalty!=null&&(k.frequency_penalty=void 0,p.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),k.presence_penalty!=null&&(k.presence_penalty=void 0,p.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),k.logit_bias!=null&&(k.logit_bias=void 0,p.push({type:"other",message:"logitBias is not supported for reasoning models"})),k.logprobs!=null&&(k.logprobs=void 0,p.push({type:"other",message:"logprobs is not supported for reasoning models"})),k.top_logprobs!=null&&(k.top_logprobs=void 0,p.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),k.max_tokens!=null&&(k.max_completion_tokens==null&&(k.max_completion_tokens=k.max_tokens),k.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&k.temperature!=null&&(k.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),_.serviceTier==="flex"&&!P9(this.modelId)&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),k.service_tier=void 0),_.serviceTier==="priority"&&!k9(this.modelId)&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),k.service_tier=void 0);const{tools:A,toolChoice:O,toolWarnings:H}=S9({tools:u,toolChoice:f,structuredOutputs:w,strictJsonSchema:I});return{args:{...k,tools:A,tool_choice:O},warnings:[...p,...H]}}async doGenerate(t){var e,r,a,n,s,o,i,l,c,u,f,g,d,h;const{args:v,warnings:m}=await this.getArgs(t),{responseHeaders:p,value:_,rawValue:w}=await or({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Kt(this.config.headers(),t.headers),body:v,failedResponseHandler:on,successfulResponseHandler:Lr(w9),abortSignal:t.abortSignal,fetch:this.config.fetch}),b=_.choices[0],S=[],I=b.message.content;I!=null&&I.length>0&&S.push({type:"text",text:I});for(const H of(e=b.message.tool_calls)!=null?e:[])S.push({type:"tool-call",toolCallId:(r=H.id)!=null?r:sr(),toolName:H.function.name,input:H.function.arguments});for(const H of(a=b.message.annotations)!=null?a:[])S.push({type:"source",sourceType:"url",id:sr(),url:H.url,title:H.title});const k=(n=_.usage)==null?void 0:n.completion_tokens_details,A=(s=_.usage)==null?void 0:s.prompt_tokens_details,O={openai:{}};return(k==null?void 0:k.accepted_prediction_tokens)!=null&&(O.openai.acceptedPredictionTokens=k==null?void 0:k.accepted_prediction_tokens),(k==null?void 0:k.rejected_prediction_tokens)!=null&&(O.openai.rejectedPredictionTokens=k==null?void 0:k.rejected_prediction_tokens),((o=b.logprobs)==null?void 0:o.content)!=null&&(O.openai.logprobs=b.logprobs.content),{content:S,finishReason:N0(b.finish_reason),usage:{inputTokens:(l=(i=_.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=_.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(g=(f=_.usage)==null?void 0:f.total_tokens)!=null?g:void 0,reasoningTokens:(d=k==null?void 0:k.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(h=A==null?void 0:A.cached_tokens)!=null?h:void 0},request:{body:v},response:{...O0(_),headers:p,body:w},warnings:m,providerMetadata:O}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await or({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Kt(this.config.headers(),t.headers),body:a,failedResponseHandler:on,successfulResponseHandler:uo(b9),abortSignal:t.abortSignal,fetch:this.config.fetch}),o=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0,u=!1;const f={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:r})},transform(g,d){var h,v,m,p,_,w,b,S,I,k,A,O,H,J,K,z,U,G,se,ne,ce,pe,M,R;if(t.includeRawChunks&&d.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){i="error",d.enqueue({type:"error",error:g.error});return}const D=g.value;if("error"in D){i="error",d.enqueue({type:"error",error:D.error});return}c&&(c=!1,d.enqueue({type:"response-metadata",...O0(D)})),D.usage!=null&&(l.inputTokens=(h=D.usage.prompt_tokens)!=null?h:void 0,l.outputTokens=(v=D.usage.completion_tokens)!=null?v:void 0,l.totalTokens=(m=D.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(_=(p=D.usage.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?_:void 0,l.cachedInputTokens=(b=(w=D.usage.prompt_tokens_details)==null?void 0:w.cached_tokens)!=null?b:void 0,((S=D.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens)!=null&&(f.openai.acceptedPredictionTokens=(I=D.usage.completion_tokens_details)==null?void 0:I.accepted_prediction_tokens),((k=D.usage.completion_tokens_details)==null?void 0:k.rejected_prediction_tokens)!=null&&(f.openai.rejectedPredictionTokens=(A=D.usage.completion_tokens_details)==null?void 0:A.rejected_prediction_tokens));const N=D.choices[0];if((N==null?void 0:N.finish_reason)!=null&&(i=N0(N.finish_reason)),((O=N==null?void 0:N.logprobs)==null?void 0:O.content)!=null&&(f.openai.logprobs=N.logprobs.content),(N==null?void 0:N.delta)==null)return;const y=N.delta;if(y.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.enqueue({type:"text-delta",id:"0",delta:y.content})),y.tool_calls!=null)for(const P of y.tool_calls){const j=P.index;if(o[j]==null){if(P.type!=="function")throw new Ys({data:P,message:"Expected 'function' type."});if(P.id==null)throw new Ys({data:P,message:"Expected 'id' to be a string."});if(((H=P.function)==null?void 0:H.name)==null)throw new Ys({data:P,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:P.id,toolName:P.function.name}),o[j]={id:P.id,type:"function",function:{name:P.function.name,arguments:(J=P.function.arguments)!=null?J:""},hasFinished:!1};const ee=o[j];((K=ee.function)==null?void 0:K.name)!=null&&((z=ee.function)==null?void 0:z.arguments)!=null&&(ee.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:ee.id,delta:ee.function.arguments}),vl(ee.function.arguments)&&(d.enqueue({type:"tool-input-end",id:ee.id}),d.enqueue({type:"tool-call",toolCallId:(U=ee.id)!=null?U:sr(),toolName:ee.function.name,input:ee.function.arguments}),ee.hasFinished=!0));continue}const Q=o[j];Q.hasFinished||(((G=P.function)==null?void 0:G.arguments)!=null&&(Q.function.arguments+=(ne=(se=P.function)==null?void 0:se.arguments)!=null?ne:""),d.enqueue({type:"tool-input-delta",id:Q.id,delta:(ce=P.function.arguments)!=null?ce:""}),((pe=Q.function)==null?void 0:pe.name)!=null&&((M=Q.function)==null?void 0:M.arguments)!=null&&vl(Q.function.arguments)&&(d.enqueue({type:"tool-input-end",id:Q.id}),d.enqueue({type:"tool-call",toolCallId:(R=Q.id)!=null?R:sr(),toolName:Q.function.name,input:Q.function.arguments}),Q.hasFinished=!0))}if(y.annotations!=null)for(const P of y.annotations)d.enqueue({type:"source",sourceType:"url",id:sr(),url:P.url,title:P.title})},flush(g){u&&g.enqueue({type:"text-end",id:"0"}),g.enqueue({type:"finish",finishReason:i,usage:l,...f!=null?{providerMetadata:f}:{}})}})),request:{body:a},response:{headers:n}}}};function A0(t){return(t.startsWith("o")||t.startsWith("gpt-5"))&&!t.startsWith("gpt-5-chat")}function P9(t){return t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")}function k9(t){return t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini")}function I9(t){var e,r;return A0(t)?(r=(e=x9[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}var x9={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function T9({prompt:t,user:e="user",assistant:r="assistant"}){let a="";t[0].role==="system"&&(a+=`${t[0].content}
525
+ `)}})}},P0={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"};function jj({status:t,statusText:e,headers:r,stream:a,consumeSseStream:n}){let s=a.pipeThrough(new S0);if(n){const[o,i]=s.tee();s=o,n({stream:i})}return new Response(s.pipeThrough(new TextEncoderStream),{status:t,statusText:e,headers:hl(r,P0)})}function Dj({originalMessages:t,responseMessageId:e}){if(t==null)return;const r=t[t.length-1];return(r==null?void 0:r.role)==="assistant"?r.id:typeof e=="function"?e():e}function Lj(t){return t.type.startsWith("data-")}function T0(t,e){if(t===void 0&&e===void 0)return;if(t===void 0)return e;if(e===void 0)return t;const r={...t};for(const a in e)if(Object.prototype.hasOwnProperty.call(e,a)){const n=e[a];if(n===void 0)continue;const s=a in t?t[a]:void 0,o=n!==null&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof RegExp),i=s!=null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp);o&&i?r[a]=T0(s,n):r[a]=n}return r}function zj(t){const e=["ROOT"];let r=-1,a=null;function n(l,c,u){switch(l){case'"':{r=c,e.pop(),e.push(u),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{r=c,a=c,e.pop(),e.push(u),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c,e.pop(),e.push(u),e.push("INSIDE_NUMBER");break}case"{":{r=c,e.pop(),e.push(u),e.push("INSIDE_OBJECT_START");break}case"[":{r=c,e.pop(),e.push(u),e.push("INSIDE_ARRAY_START");break}}}function s(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=c,e.pop();break}}}function o(l,c){switch(l){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=c,e.pop();break}}}for(let l=0;l<t.length;l++){const c=t[l];switch(e[e.length-1]){case"ROOT":n(c,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{r=l,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(c){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(c){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(c,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{s(c,l);break}case"INSIDE_STRING":{switch(c){case'"':{e.pop(),r=l;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:r=l}break}case"INSIDE_ARRAY_START":{switch(c){case"]":{r=l,e.pop();break}default:{r=l,n(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{r=l,e.pop();break}default:{r=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(c,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),r=l;break}case"INSIDE_NUMBER":{switch(c){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=l;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&s(c,l);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const h=t.substring(a,l+1);!"false".startsWith(h)&&!"true".startsWith(h)&&!"null".startsWith(h)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?s(c,l):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&o(c,l)):r=l;break}}}let i=t.slice(0,r+1);for(let l=e.length-1;l>=0;l--)switch(e[l]){case"INSIDE_STRING":{i+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{i+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{i+="]";break}case"INSIDE_LITERAL":{const u=t.substring(a,t.length);"true".startsWith(u)?i+="true".slice(u.length):"false".startsWith(u)?i+="false".slice(u.length):"null".startsWith(u)&&(i+="null".slice(u.length))}}return i}async function x0(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let e=await Xn({text:t});return e.success?{value:e.value,state:"successful-parse"}:(e=await Xn({text:zj(t)}),e.success?{value:e.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function pf(t){return t.type.startsWith("tool-")}function k0(t){return t.type.split("-").slice(1).join("-")}function Uj({lastMessage:t,messageId:e}){return{message:(t==null?void 0:t.role)==="assistant"?t:{id:e,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function qj({stream:t,messageMetadataSchema:e,dataPartSchemas:r,runUpdateMessageJob:a,onError:n,onToolCall:s,onData:o}){return t.pipeThrough(new TransformStream({async transform(i,l){await a(async({state:c,write:u})=>{var h,g,d,f;function v(w){const P=c.message.parts.filter(pf).find(T=>T.toolCallId===w);if(P==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return P}function m(w){const P=c.message.parts.filter(T=>T.type==="dynamic-tool").find(T=>T.toolCallId===w);if(P==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return P}function p(w){var E;const P=c.message.parts.find(M=>pf(M)&&M.toolCallId===w.toolCallId),T=w,O=P;P!=null?(P.state=w.state,O.input=T.input,O.output=T.output,O.errorText=T.errorText,O.rawInput=T.rawInput,O.preliminary=T.preliminary,O.providerExecuted=(E=T.providerExecuted)!=null?E:P.providerExecuted,T.providerMetadata!=null&&P.state==="input-available"&&(P.callProviderMetadata=T.providerMetadata)):c.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:T.input,output:T.output,rawInput:T.rawInput,errorText:T.errorText,providerExecuted:T.providerExecuted,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}function y(w){var E;const P=c.message.parts.find(M=>M.type==="dynamic-tool"&&M.toolCallId===w.toolCallId),T=w,O=P;P!=null?(P.state=w.state,O.toolName=w.toolName,O.input=T.input,O.output=T.output,O.errorText=T.errorText,O.rawInput=(E=T.rawInput)!=null?E:O.rawInput,O.preliminary=T.preliminary,T.providerMetadata!=null&&P.state==="input-available"&&(P.callProviderMetadata=T.providerMetadata)):c.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:T.input,output:T.output,errorText:T.errorText,preliminary:T.preliminary,...T.providerMetadata!=null?{callProviderMetadata:T.providerMetadata}:{}})}async function _(w){if(w!=null){const E=c.message.metadata!=null?T0(c.message.metadata,w):w;e!=null&&await Md({value:E,schema:e}),c.message.metadata=E}}switch(i.type){case"text-start":{const w={type:"text",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeTextParts[i.id]=w,c.message.parts.push(w),u();break}case"text-delta":{const w=c.activeTextParts[i.id];w.text+=i.delta,w.providerMetadata=(h=i.providerMetadata)!=null?h:w.providerMetadata,u();break}case"text-end":{const w=c.activeTextParts[i.id];w.state="done",w.providerMetadata=(g=i.providerMetadata)!=null?g:w.providerMetadata,delete c.activeTextParts[i.id],u();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:i.providerMetadata,state:"streaming"};c.activeReasoningParts[i.id]=w,c.message.parts.push(w),u();break}case"reasoning-delta":{const w=c.activeReasoningParts[i.id];w.text+=i.delta,w.providerMetadata=(d=i.providerMetadata)!=null?d:w.providerMetadata,u();break}case"reasoning-end":{const w=c.activeReasoningParts[i.id];w.providerMetadata=(f=i.providerMetadata)!=null?f:w.providerMetadata,w.state="done",delete c.activeReasoningParts[i.id],u();break}case"file":{c.message.parts.push({type:"file",mediaType:i.mediaType,url:i.url}),u();break}case"source-url":{c.message.parts.push({type:"source-url",sourceId:i.sourceId,url:i.url,title:i.title,providerMetadata:i.providerMetadata}),u();break}case"source-document":{c.message.parts.push({type:"source-document",sourceId:i.sourceId,mediaType:i.mediaType,title:i.title,filename:i.filename,providerMetadata:i.providerMetadata}),u();break}case"tool-input-start":{const w=c.message.parts.filter(pf);c.partialToolCalls[i.toolCallId]={text:"",toolName:i.toolName,index:w.length,dynamic:i.dynamic},i.dynamic?y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-streaming",input:void 0,providerExecuted:i.providerExecuted}),u();break}case"tool-input-delta":{const w=c.partialToolCalls[i.toolCallId];w.text+=i.inputTextDelta;const{value:E}=await x0(w.text);w.dynamic?y({toolCallId:i.toolCallId,toolName:w.toolName,state:"input-streaming",input:E}):p({toolCallId:i.toolCallId,toolName:w.toolName,state:"input-streaming",input:E}),u();break}case"tool-input-available":{i.dynamic?y({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"input-available",input:i.input,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u(),s&&!i.providerExecuted&&await s({toolCall:i});break}case"tool-input-error":{i.dynamic?y({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:i.input,errorText:i.errorText,providerMetadata:i.providerMetadata}):p({toolCallId:i.toolCallId,toolName:i.toolName,state:"output-error",input:void 0,rawInput:i.input,errorText:i.errorText,providerExecuted:i.providerExecuted,providerMetadata:i.providerMetadata}),u();break}case"tool-output-available":{if(i.dynamic){const w=m(i.toolCallId);y({toolCallId:i.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:i.output,preliminary:i.preliminary})}else{const w=v(i.toolCallId);p({toolCallId:i.toolCallId,toolName:k0(w),state:"output-available",input:w.input,output:i.output,providerExecuted:i.providerExecuted,preliminary:i.preliminary})}u();break}case"tool-output-error":{if(i.dynamic){const w=m(i.toolCallId);y({toolCallId:i.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:i.errorText})}else{const w=v(i.toolCallId);p({toolCallId:i.toolCallId,toolName:k0(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:i.errorText})}u();break}case"start-step":{c.message.parts.push({type:"step-start"});break}case"finish-step":{c.activeTextParts={},c.activeReasoningParts={};break}case"start":{i.messageId!=null&&(c.message.id=i.messageId),await _(i.messageMetadata),(i.messageId!=null||i.messageMetadata!=null)&&u();break}case"finish":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"message-metadata":{await _(i.messageMetadata),i.messageMetadata!=null&&u();break}case"error":{n==null||n(new Error(i.errorText));break}default:if(Lj(i)){(r==null?void 0:r[i.type])!=null&&await Md({value:i.data,schema:r[i.type]});const w=i;if(w.transient){o==null||o(w);break}const E=w.id!=null?c.message.parts.find(P=>w.type===P.type&&w.id===P.id):void 0;E!=null?E.data=w.data:c.message.parts.push(w),o==null||o(w),u()}}l.enqueue(i)})}}))}function Fj({messageId:t,originalMessages:e=[],onFinish:r,onError:a,stream:n}){let s=e==null?void 0:e[e.length-1];(s==null?void 0:s.role)!=="assistant"?s=void 0:t=s.id;let o=!1;const i=n.pipeThrough(new TransformStream({transform(g,d){if(g.type==="start"){const f=g;f.messageId==null&&t!=null&&(f.messageId=t)}g.type==="abort"&&(o=!0),d.enqueue(g)}}));if(r==null)return i;const l=Uj({lastMessage:s?structuredClone(s):void 0,messageId:t??""}),c=async g=>{await g({state:l,write:()=>{}})};let u=!1;const h=async()=>{if(u||!r)return;u=!0;const g=l.message.id===(s==null?void 0:s.id);await r({isAborted:o,isContinuation:g,responseMessage:l.message,messages:[...g?e.slice(0,-1):e,l.message]})};return qj({stream:i,runUpdateMessageJob:c,onError:a}).pipeThrough(new TransformStream({transform(g,d){d.enqueue(g)},async cancel(){await h()},async flush(){await h()}}))}function Zj({response:t,status:e,statusText:r,headers:a,stream:n,consumeSseStream:s}){let o=n.pipeThrough(new S0);if(s){const[i,l]=o.tee();o=i,s({stream:l})}$0({response:t,status:e,statusText:r,headers:Object.fromEntries(hl(a,P0).entries()),stream:o.pipeThrough(new TextEncoderStream)})}function ml(t){const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=function(){const r=this.getReader();let a=!1;async function n(s){var o;a=!0;try{s&&await((o=r.cancel)==null?void 0:o.call(r))}finally{try{r.releaseLock()}catch{}}}return{async next(){if(a)return{done:!0,value:void 0};const{done:s,value:o}=await r.read();return s?(await n(!0),{done:!0,value:void 0}):{done:!1,value:o}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(s){throw await n(!0),s}}},e}async function Vj({stream:t,onError:e}){const r=t.getReader();try{for(;;){const{done:a}=await r.read();if(a)break}}catch(a){e==null||e(a)}finally{r.releaseLock()}}function I0(){let t,e;return{promise:new Promise((a,n)=>{t=a,e=n}),resolve:t,reject:e}}function Hj(){let t=[],e=null,r=!1,a=I0();const n=()=>{r=!0,a.resolve(),t.forEach(o=>o.cancel()),t=[],e==null||e.close()},s=async()=>{if(r&&t.length===0){e==null||e.close();return}if(t.length===0)return a=I0(),await a.promise,s();try{const{value:o,done:i}=await t[0].read();i?(t.shift(),t.length>0?await s():r&&(e==null||e.close())):e==null||e.enqueue(o)}catch(o){e==null||e.error(o),t.shift(),n()}};return{stream:new ReadableStream({start(o){e=o},pull:s,async cancel(){for(const o of t)await o.cancel();t=[],r=!0}}),addStream:o=>{if(r)throw new Error("Cannot add inner stream: outer stream is closed");t.push(o.getReader()),a.resolve()},close:()=>{r=!0,a.resolve(),t.length===0&&(e==null||e.close())},terminate:n}}var vl=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,e)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&e(this.status.error),this._resolve=t,this._reject=e}),this._promise)}resolve(t){var e;this.status={type:"resolved",value:t},this._promise&&((e=this._resolve)==null||e.call(this,t))}reject(t){var e;this.status={type:"rejected",error:t},this._promise&&((e=this._reject)==null||e.call(this,t))}};function Bj(){var t,e;return(e=(t=globalThis==null?void 0:globalThis.performance)==null?void 0:t.now())!=null?e:Date.now()}function Jj({tools:t,generatorStream:e,tracer:r,telemetry:a,system:n,messages:s,abortSignal:o,repairToolCall:i,experimental_context:l}){let c=null;const u=new ReadableStream({start(p){c=p}}),h=new Set,g=new Map;let d=!1,f;function v(){d&&h.size===0&&(f!=null&&c.enqueue(f),c.close())}const m=new TransformStream({async transform(p,y){const _=p.type;switch(_){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":{y.enqueue(p);break}case"file":{y.enqueue({type:"file",file:new kj({data:p.data,mediaType:p.mediaType})});break}case"finish":{f={type:"finish",finishReason:p.finishReason,usage:p.usage,providerMetadata:p.providerMetadata};break}case"tool-call":{try{const w=await g0({toolCall:p,tools:t,repairToolCall:i,system:n,messages:s});if(y.enqueue(w),w.invalid){c.enqueue({type:"tool-error",toolCallId:w.toolCallId,toolName:w.toolName,input:w.input,error:Ad(w.error),dynamic:!0});break}const E=t[w.toolName];if(g.set(w.toolCallId,w.input),E.onInputAvailable!=null&&await E.onInputAvailable({input:w.input,toolCallId:w.toolCallId,messages:s,abortSignal:o,experimental_context:l}),E.execute!=null&&w.providerExecuted!==!0){const P=SA();h.add(P),Wa({name:"ai.toolCall",attributes:hr({telemetry:a,attributes:{...Ka({operationId:"ai.toolCall",telemetry:a}),"ai.toolCall.name":w.toolName,"ai.toolCall.id":w.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(w.input)}}}),tracer:r,fn:async T=>{let O;try{const M=Ty({execute:E.execute.bind(E),input:w.input,options:{toolCallId:w.toolCallId,messages:s,abortSignal:o,experimental_context:l}});for await(const J of M)c.enqueue({...w,type:"tool-result",output:J.output,...J.type==="preliminary"&&{preliminary:!0}}),J.type==="final"&&(O=J.output)}catch(M){lf(T,M),c.enqueue({...w,type:"tool-error",error:M}),h.delete(P),v();return}h.delete(P),v();try{T.setAttributes(hr({telemetry:a,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(O)}}}))}catch{}}})}}catch(w){c.enqueue({type:"error",error:w})}break}case"tool-result":{const w=p.toolName;p.isError?c.enqueue({type:"tool-error",toolCallId:p.toolCallId,toolName:w,input:g.get(p.toolCallId),providerExecuted:p.providerExecuted,error:p.result}):y.enqueue({type:"tool-result",toolCallId:p.toolCallId,toolName:w,input:g.get(p.toolCallId),output:p.result,providerExecuted:p.providerExecuted});break}default:{const w=_;throw new Error(`Unhandled chunk type: ${w}`)}}},flush(){d=!0,v()}});return new ReadableStream({async start(p){return Promise.all([e.pipeThrough(m).pipeTo(new WritableStream({write(y){p.enqueue(y)},close(){}})),u.pipeTo(new WritableStream({write(y){p.enqueue(y)},close(){p.close()}}))])}})}var Gj=ro({prefix:"aitxt",size:24});function Kj({model:t,tools:e,toolChoice:r,system:a,prompt:n,messages:s,maxRetries:o,abortSignal:i,headers:l,stopWhen:c=uf(1),experimental_output:u,experimental_telemetry:h,prepareStep:g,providerOptions:d,experimental_activeTools:f,activeTools:v=f,experimental_repairToolCall:m,experimental_transform:p,experimental_download:y,includeRawChunks:_=!1,onChunk:w,onError:E=({error:Z})=>{console.error(Z)},onFinish:P,onAbort:T,onStepFinish:O,experimental_context:M,_internal:{now:J=Bj,generateId:H=Gj,currentDate:G=()=>new Date}={},...F}){return new Qj({model:fl(t),telemetry:h,headers:l,settings:F,maxRetries:o,abortSignal:i,system:a,prompt:n,messages:s,tools:e,toolChoice:r,transforms:cf(p),activeTools:v,repairToolCall:m,stopConditions:cf(c),output:u,providerOptions:d,prepareStep:g,includeRawChunks:_,onChunk:w,onError:E,onFinish:P,onAbort:T,onStepFinish:O,now:J,currentDate:G,generateId:H,experimental_context:M,download:y})}function Wj(t){if(!t)return new TransformStream({transform(o,i){i.enqueue({part:o,partialOutput:void 0})}});let e,r="",a="",n="";function s({controller:o,partialOutput:i=void 0}){o.enqueue({part:{type:"text-delta",id:e,text:a},partialOutput:i}),a=""}return new TransformStream({async transform(o,i){if(o.type==="finish-step"&&a.length>0&&s({controller:i}),o.type!=="text-delta"&&o.type!=="text-start"&&o.type!=="text-end"){i.enqueue({part:o,partialOutput:void 0});return}if(e==null)e=o.id;else if(o.id!==e){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-start"){i.enqueue({part:o,partialOutput:void 0});return}if(o.type==="text-end"){a.length>0&&s({controller:i}),i.enqueue({part:o,partialOutput:void 0});return}r+=o.text,a+=o.text;const l=await t.parsePartial({text:r});if(l!=null){const c=JSON.stringify(l.partial);c!==n&&(s({controller:i,partialOutput:l.partial}),n=c)}}})}var Qj=class{constructor({model:t,telemetry:e,headers:r,settings:a,maxRetries:n,abortSignal:s,system:o,prompt:i,messages:l,tools:c,toolChoice:u,transforms:h,activeTools:g,repairToolCall:d,stopConditions:f,output:v,providerOptions:m,prepareStep:p,includeRawChunks:y,now:_,currentDate:w,generateId:E,onChunk:P,onError:T,onFinish:O,onAbort:M,onStepFinish:J,experimental_context:H,download:G}){this._totalUsage=new vl,this._finishReason=new vl,this._steps=new vl,this.output=v,this.includeRawChunks=y,this.tools=c;let F,Z=[];const te=[];let pe,ve,N={},ie=[];const D=[];let C,z={},A={};const b=new TransformStream({async transform(he,Ae){var Ne,Te,tt,Ze;Ae.enqueue(he);const{part:re}=he;if((re.type==="text-delta"||re.type==="reasoning-delta"||re.type==="source"||re.type==="tool-call"||re.type==="tool-result"||re.type==="tool-input-start"||re.type==="tool-input-delta"||re.type==="raw")&&await(P==null?void 0:P({chunk:re})),re.type==="error"&&await T({error:l0(re.error)}),re.type==="text-start"&&(z[re.id]={type:"text",text:"",providerMetadata:re.providerMetadata},Z.push(z[re.id])),re.type==="text-delta"){const Le=z[re.id];if(Le==null){Ae.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}Le.text+=re.text,Le.providerMetadata=(Ne=re.providerMetadata)!=null?Ne:Le.providerMetadata}if(re.type==="text-end"){const Le=z[re.id];if(Le==null){Ae.enqueue({part:{type:"error",error:`text part ${re.id} not found`},partialOutput:void 0});return}Le.providerMetadata=(Te=re.providerMetadata)!=null?Te:Le.providerMetadata,delete z[re.id]}if(re.type==="reasoning-start"&&(A[re.id]={type:"reasoning",text:"",providerMetadata:re.providerMetadata},Z.push(A[re.id])),re.type==="reasoning-delta"){const Le=A[re.id];if(Le==null){Ae.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}Le.text+=re.text,Le.providerMetadata=(tt=re.providerMetadata)!=null?tt:Le.providerMetadata}if(re.type==="reasoning-end"){const Le=A[re.id];if(Le==null){Ae.enqueue({part:{type:"error",error:`reasoning part ${re.id} not found`},partialOutput:void 0});return}Le.providerMetadata=(Ze=re.providerMetadata)!=null?Ze:Le.providerMetadata,delete A[re.id]}if(re.type==="file"&&Z.push({type:"file",file:re.file}),re.type==="source"&&Z.push(re),re.type==="tool-call"&&Z.push(re),re.type==="tool-result"&&!re.preliminary&&Z.push(re),re.type==="tool-error"&&Z.push(re),re.type==="start-step"&&(N=re.request,ie=re.warnings),re.type==="finish-step"){const Le=ff({content:Z,tools:c}),He=new _0({content:Z,finishReason:re.finishReason,usage:re.usage,warnings:ie,request:N,response:{...re.response,messages:[...te,...Le]},providerMetadata:re.providerMetadata});await(J==null?void 0:J(He)),E_(ie),D.push(He),Z=[],A={},z={},te.push(...Le),F.resolve()}re.type==="finish"&&(ve=re.totalUsage,pe=re.finishReason)},async flush(he){try{if(D.length===0){const tt=new JM({message:"No output generated. Check the stream for errors."});Ie._finishReason.reject(tt),Ie._totalUsage.reject(tt),Ie._steps.reject(tt);return}const Ae=pe??"unknown",Ne=ve??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};Ie._finishReason.resolve(Ae),Ie._totalUsage.resolve(Ne),Ie._steps.resolve(D);const Te=D[D.length-1];await(O==null?void 0:O({finishReason:Ae,totalUsage:Ne,usage:Te.usage,content:Te.content,text:Te.text,reasoningText:Te.reasoningText,reasoning:Te.reasoning,files:Te.files,sources:Te.sources,toolCalls:Te.toolCalls,staticToolCalls:Te.staticToolCalls,dynamicToolCalls:Te.dynamicToolCalls,toolResults:Te.toolResults,staticToolResults:Te.staticToolResults,dynamicToolResults:Te.dynamicToolResults,request:Te.request,response:Te.response,warnings:Te.warnings,providerMetadata:Te.providerMetadata,steps:D})),C.setAttributes(hr({telemetry:e,attributes:{"ai.response.finishReason":Ae,"ai.response.text":{output:()=>Te.text},"ai.response.toolCalls":{output:()=>{var tt;return(tt=Te.toolCalls)!=null&&tt.length?JSON.stringify(Te.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Te.providerMetadata),"ai.usage.inputTokens":Ne.inputTokens,"ai.usage.outputTokens":Ne.outputTokens,"ai.usage.totalTokens":Ne.totalTokens,"ai.usage.reasoningTokens":Ne.reasoningTokens,"ai.usage.cachedInputTokens":Ne.cachedInputTokens}}))}catch(Ae){he.error(Ae)}finally{C.end()}}}),x=Hj();this.addStream=x.addStream,this.closeStream=x.close;const L=x.stream.getReader();let W=new ReadableStream({async start(he){he.enqueue({type:"start"})},async pull(he){function Ae(){M==null||M({steps:D}),he.enqueue({type:"abort"}),he.close()}try{const{done:Ne,value:Te}=await L.read();if(Ne){he.close();return}if(s!=null&&s.aborted){Ae();return}he.enqueue(Te)}catch(Ne){Yn(Ne)&&(s!=null&&s.aborted)?Ae():he.error(Ne)}},cancel(he){return x.stream.cancel(he)}});for(const he of h)W=W.pipeThrough(he({tools:c,stopStream(){x.terminate()}}));this.baseStream=W.pipeThrough(Wj(v)).pipeThrough(b);const{maxRetries:X,retry:$e}=h0({maxRetries:n,abortSignal:s}),le=u0(e),ge=of(a),mt=c0({model:t,telemetry:e,headers:r,settings:{...ge,maxRetries:X}}),Ie=this;Wa({name:"ai.streamText",attributes:hr({telemetry:e,attributes:{...Ka({operationId:"ai.streamText",telemetry:e}),...mt,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:i,messages:l})}}}),tracer:le,endWhenDone:!1,fn:async he=>{C=he;async function Ae({currentStep:Ne,responseMessages:Te,usage:tt}){var Ze,re,Le,He,Ee;const We=Ie.includeRawChunks;F=new vl;const Yt=await i0({system:o,prompt:i,messages:l}),Ct=[...Yt.messages,...Te],yt=await(p==null?void 0:p({model:t,steps:D,stepNumber:D.length,messages:Ct})),Xt=fl((Ze=yt==null?void 0:yt.model)!=null?Ze:t),Rt=await r0({prompt:{system:(re=yt==null?void 0:yt.system)!=null?re:Yt.system,messages:(Le=yt==null?void 0:yt.messages)!=null?Le:Ct},supportedUrls:await Xt.supportedUrls,download:G}),{toolChoice:er,tools:dn}=n0({tools:c,toolChoice:(He=yt==null?void 0:yt.toolChoice)!=null?He:u,activeTools:(Ee=yt==null?void 0:yt.activeTools)!=null?Ee:g}),{result:{stream:ia,response:ut,request:vr},doStreamSpan:Or,startTimestampMs:_o}=await $e(()=>Wa({name:"ai.streamText.doStream",attributes:hr({telemetry:e,attributes:{...Ka({operationId:"ai.streamText.doStream",telemetry:e}),...mt,"ai.model.provider":Xt.provider,"ai.model.id":Xt.modelId,"ai.prompt.messages":{input:()=>d0(Rt)},"ai.prompt.tools":{input:()=>dn==null?void 0:dn.map(we=>JSON.stringify(we))},"ai.prompt.toolChoice":{input:()=>er!=null?JSON.stringify(er):void 0},"gen_ai.system":Xt.provider,"gen_ai.request.model":Xt.modelId,"gen_ai.request.frequency_penalty":ge.frequencyPenalty,"gen_ai.request.max_tokens":ge.maxOutputTokens,"gen_ai.request.presence_penalty":ge.presencePenalty,"gen_ai.request.stop_sequences":ge.stopSequences,"gen_ai.request.temperature":ge.temperature,"gen_ai.request.top_k":ge.topK,"gen_ai.request.top_p":ge.topP}}),tracer:le,endWhenDone:!1,fn:async we=>({startTimestampMs:_(),doStreamSpan:we,result:await Xt.doStream({...ge,tools:dn,toolChoice:er,responseFormat:v==null?void 0:v.responseFormat,prompt:Rt,providerOptions:m,abortSignal:s,headers:r,includeRawChunks:We})})})),gr=Jj({tools:c,generatorStream:ia,tracer:le,telemetry:e,system:o,messages:Ct,repairToolCall:d,abortSignal:s,experimental_context:H}),bf=vr??{},Qa=[],wo=[];let bo;const Eo={};let An="unknown",Ot={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},$o,So=!0,yr={id:E(),timestamp:w(),modelId:t.modelId},Ya="";Ie.addStream(gr.pipeThrough(new TransformStream({async transform(we,It){var Nn,la,ca,k;if(we.type==="stream-start"){bo=we.warnings;return}if(So){const I=_()-_o;So=!1,Or.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":I}),Or.setAttributes({"ai.response.msToFirstChunk":I}),It.enqueue({type:"start-step",request:bf,warnings:bo??[]})}const $=we.type;switch($){case"text-start":case"text-end":{It.enqueue(we);break}case"text-delta":{we.delta.length>0&&(It.enqueue({type:"text-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata}),Ya+=we.delta);break}case"reasoning-start":case"reasoning-end":{It.enqueue(we);break}case"reasoning-delta":{It.enqueue({type:"reasoning-delta",id:we.id,text:we.delta,providerMetadata:we.providerMetadata});break}case"tool-call":{It.enqueue(we),Qa.push(we);break}case"tool-result":{It.enqueue(we),we.preliminary||wo.push(we);break}case"tool-error":{It.enqueue(we),wo.push(we);break}case"response-metadata":{yr={id:(Nn=we.id)!=null?Nn:yr.id,timestamp:(la=we.timestamp)!=null?la:yr.timestamp,modelId:(ca=we.modelId)!=null?ca:yr.modelId};break}case"finish":{Ot=we.usage,An=we.finishReason,$o=we.providerMetadata;const I=_()-_o;Or.addEvent("ai.stream.finish"),Or.setAttributes({"ai.response.msToFinish":I,"ai.response.avgOutputTokensPerSecond":1e3*((k=Ot.outputTokens)!=null?k:0)/I});break}case"file":{It.enqueue(we);break}case"source":{It.enqueue(we);break}case"tool-input-start":{Eo[we.id]=we.toolName;const I=c==null?void 0:c[we.toolName];(I==null?void 0:I.onInputStart)!=null&&await I.onInputStart({toolCallId:we.id,messages:Ct,abortSignal:s,experimental_context:H}),It.enqueue({...we,dynamic:(I==null?void 0:I.type)==="dynamic"});break}case"tool-input-end":{delete Eo[we.id],It.enqueue(we);break}case"tool-input-delta":{const I=Eo[we.id],U=c==null?void 0:c[I];(U==null?void 0:U.onInputDelta)!=null&&await U.onInputDelta({inputTextDelta:we.delta,toolCallId:we.id,messages:Ct,abortSignal:s,experimental_context:H}),It.enqueue(we);break}case"error":{It.enqueue(we),An="error";break}case"raw":{We&&It.enqueue(we);break}default:{const I=$;throw new Error(`Unknown chunk type: ${I}`)}}},async flush(we){const It=Qa.length>0?JSON.stringify(Qa):void 0;try{Or.setAttributes(hr({telemetry:e,attributes:{"ai.response.finishReason":An,"ai.response.text":{output:()=>Ya},"ai.response.toolCalls":{output:()=>It},"ai.response.id":yr.id,"ai.response.model":yr.modelId,"ai.response.timestamp":yr.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify($o),"ai.usage.inputTokens":Ot.inputTokens,"ai.usage.outputTokens":Ot.outputTokens,"ai.usage.totalTokens":Ot.totalTokens,"ai.usage.reasoningTokens":Ot.reasoningTokens,"ai.usage.cachedInputTokens":Ot.cachedInputTokens,"gen_ai.response.finish_reasons":[An],"gen_ai.response.id":yr.id,"gen_ai.response.model":yr.modelId,"gen_ai.usage.input_tokens":Ot.inputTokens,"gen_ai.usage.output_tokens":Ot.outputTokens}}))}catch{}finally{Or.end()}we.enqueue({type:"finish-step",finishReason:An,usage:Ot,providerMetadata:$o,response:{...yr,headers:ut==null?void 0:ut.headers}});const Nn=f0(tt,Ot);await F.promise;const la=Qa.filter(k=>k.providerExecuted!==!0),ca=wo.filter(k=>k.providerExecuted!==!0);if(la.length>0&&ca.length===la.length&&!await w0({stopConditions:f,steps:D})){Te.push(...ff({content:D[D.length-1].content,tools:c}));try{await Ae({currentStep:Ne+1,responseMessages:Te,usage:Nn})}catch(k){we.enqueue({type:"error",error:k}),Ie.closeStream()}}else we.enqueue({type:"finish",finishReason:An,totalUsage:Nn}),Ie.closeStream()}})))}await Ae({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(he=>{Ie.addStream(new ReadableStream({start(Ae){Ae.enqueue({type:"error",error:he}),Ae.close()}})),Ie.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(t=>t[t.length-1])}get content(){return this.finalStep.then(t=>t.content)}get warnings(){return this.finalStep.then(t=>t.warnings)}get providerMetadata(){return this.finalStep.then(t=>t.providerMetadata)}get text(){return this.finalStep.then(t=>t.text)}get reasoningText(){return this.finalStep.then(t=>t.reasoningText)}get reasoning(){return this.finalStep.then(t=>t.reasoning)}get sources(){return this.finalStep.then(t=>t.sources)}get files(){return this.finalStep.then(t=>t.files)}get toolCalls(){return this.finalStep.then(t=>t.toolCalls)}get staticToolCalls(){return this.finalStep.then(t=>t.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(t=>t.dynamicToolCalls)}get toolResults(){return this.finalStep.then(t=>t.toolResults)}get staticToolResults(){return this.finalStep.then(t=>t.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(t=>t.dynamicToolResults)}get usage(){return this.finalStep.then(t=>t.usage)}get request(){return this.finalStep.then(t=>t.request)}get response(){return this.finalStep.then(t=>t.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){const[t,e]=this.baseStream.tee();return this.baseStream=e,t}get textStream(){return ml(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){t.type==="text-delta"&&e.enqueue(t.text)}})))}get fullStream(){return ml(this.teeStream().pipeThrough(new TransformStream({transform({part:t},e){e.enqueue(t)}})))}async consumeStream(t){var e;try{await Vj({stream:this.fullStream,onError:t==null?void 0:t.onError})}catch(r){(e=t==null?void 0:t.onError)==null||e.call(t,r)}}get experimental_partialOutputStream(){if(this.output==null)throw new w_;return ml(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:t},e){t!=null&&e.enqueue(t)}})))}toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n=!0,sendSources:s=!1,sendStart:o=!0,sendFinish:i=!0,onError:l=Ha}={}){const c=e!=null?Dj({originalMessages:t,responseMessageId:e}):void 0,u={},h=d=>{var f,v;const m=u[d];return((v=(f=this.tools)==null?void 0:f[m])==null?void 0:v.type)==="dynamic"?!0:void 0},g=this.fullStream.pipeThrough(new TransformStream({transform:async(d,f)=>{const v=a==null?void 0:a({part:d}),m=d.type;switch(m){case"text-start":{f.enqueue({type:"text-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-delta":{f.enqueue({type:"text-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"text-end":{f.enqueue({type:"text-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-start":{f.enqueue({type:"reasoning-start",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-delta":{n&&f.enqueue({type:"reasoning-delta",id:d.id,delta:d.text,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"reasoning-end":{f.enqueue({type:"reasoning-end",id:d.id,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"file":{f.enqueue({type:"file",mediaType:d.file.mediaType,url:`data:${d.file.mediaType};base64,${d.file.base64}`});break}case"source":{s&&d.sourceType==="url"&&f.enqueue({type:"source-url",sourceId:d.id,url:d.url,title:d.title,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}}),s&&d.sourceType==="document"&&f.enqueue({type:"source-document",sourceId:d.id,mediaType:d.mediaType,title:d.title,filename:d.filename,...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{}});break}case"tool-input-start":{u[d.id]=d.toolName;const p=h(d.id);f.enqueue({type:"tool-input-start",toolCallId:d.id,toolName:d.toolName,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"tool-input-delta":{f.enqueue({type:"tool-input-delta",toolCallId:d.id,inputTextDelta:d.delta});break}case"tool-call":{u[d.toolCallId]=d.toolName;const p=h(d.toolCallId);d.invalid?f.enqueue({type:"tool-input-error",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...p!=null?{dynamic:p}:{},errorText:l(d.error)}):f.enqueue({type:"tool-input-available",toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.providerMetadata!=null?{providerMetadata:d.providerMetadata}:{},...p!=null?{dynamic:p}:{}});break}case"tool-result":{const p=h(d.toolCallId);f.enqueue({type:"tool-output-available",toolCallId:d.toolCallId,output:d.output,...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...d.preliminary!=null?{preliminary:d.preliminary}:{},...p!=null?{dynamic:p}:{}});break}case"tool-error":{const p=h(d.toolCallId);f.enqueue({type:"tool-output-error",toolCallId:d.toolCallId,errorText:l(d.error),...d.providerExecuted!=null?{providerExecuted:d.providerExecuted}:{},...p!=null?{dynamic:p}:{}});break}case"error":{f.enqueue({type:"error",errorText:l(d.error)});break}case"start-step":{f.enqueue({type:"start-step"});break}case"finish-step":{f.enqueue({type:"finish-step"});break}case"start":{o&&f.enqueue({type:"start",...v!=null?{messageMetadata:v}:{},...c!=null?{messageId:c}:{}});break}case"finish":{i&&f.enqueue({type:"finish",...v!=null?{messageMetadata:v}:{}});break}case"abort":{f.enqueue(d);break}case"tool-input-end":break;case"raw":break;default:{const p=m;throw new Error(`Unknown chunk type: ${p}`)}}v!=null&&m!=="start"&&m!=="finish"&&f.enqueue({type:"message-metadata",messageMetadata:v})}}));return ml(Fj({stream:g,messageId:c??(e==null?void 0:e()),originalMessages:t,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(t,{originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:c,...u}={}){Zj({response:t,stream:this.toUIMessageStream({originalMessages:e,generateMessageId:r,onFinish:a,messageMetadata:n,sendReasoning:s,sendSources:o,sendFinish:i,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(t,e){Mj({response:t,textStream:this.textStream,...e})}toUIMessageStreamResponse({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l,...c}={}){return jj({stream:this.toUIMessageStream({originalMessages:t,generateMessageId:e,onFinish:r,messageMetadata:a,sendReasoning:n,sendSources:s,sendFinish:o,sendStart:i,onError:l}),...c})}toTextStreamResponse(t){return Nj({textStream:this.textStream,...t})}};ro({prefix:"aiobj",size:24}),ro({prefix:"aiobj",size:24});var Yj={};zM(Yj,{object:()=>e9,text:()=>Xj});var Xj=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:t}){return{partial:t}},async parseOutput({text:t}){return t}}),e9=({schema:t})=>{const e=ll(t);return{type:"object",responseFormat:{type:"json",schema:e.jsonSchema},async parsePartial({text:r}){const a=await x0(r);switch(a.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:a.value};default:{const n=a.state;throw new Error(`Unsupported parse state: ${n}`)}}},async parseOutput({text:r},a){const n=await Xn({text:r});if(!n.success)throw new A_({message:"No object generated: could not parse the response.",cause:n.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});const s=await Rn({value:n.value,schema:e});if(!s.success)throw new A_({message:"No object generated: response did not match schema.",cause:s.error,text:r,response:a.response,usage:a.usage,finishReason:a.finishReason});return s.value}}},t9=Ba({name:S(),version:S()}),hf=Ba({_meta:St(R({}).loose())}),mo=hf,r9=R({method:S(),params:St(hf)}),n9=Ba({experimental:St(R({}).loose()),logging:St(R({}).loose()),prompts:St(Ba({listChanged:St($t())})),resources:St(Ba({subscribe:St($t()),listChanged:St($t())})),tools:St(Ba({listChanged:St($t())}))});mo.extend({protocolVersion:S(),capabilities:n9,serverInfo:t9,instructions:St(S())});var a9=mo.extend({nextCursor:St(S())}),s9=R({name:S(),description:St(S()),inputSchema:R({type:ne("object"),properties:St(R({}).loose())}).loose()}).loose();a9.extend({tools:ce(s9)});var o9=R({type:ne("text"),text:S()}).loose(),i9=R({type:ne("image"),data:oy(),mimeType:S()}).loose(),C0=R({uri:S(),mimeType:St(S())}).loose(),l9=C0.extend({text:S()}),c9=C0.extend({blob:oy()}),u9=R({type:ne("resource"),resource:Ve([l9,c9])}).loose();mo.extend({content:ce(Ve([o9,i9,u9])),isError:$t().default(!1).optional()}).or(mo.extend({toolResult:Cn()}));var gl="2.0",d9=R({jsonrpc:ne(gl),id:Ve([S(),K().int()])}).merge(r9).strict(),f9=R({jsonrpc:ne(gl),id:Ve([S(),K().int()]),result:mo}).strict(),p9=R({jsonrpc:ne(gl),id:Ve([S(),K().int()]),error:R({code:K().int(),message:S(),data:St(Cn())})}).strict(),h9=R({jsonrpc:ne(gl)}).merge(R({method:S(),params:St(hf)})).strict();Ve([d9,h9,f9,p9]);function mr(...t){return t.reduce((e,r)=>({...e,...r??{}}),{})}function vo(t){return Object.fromEntries([...t.headers])}var m9=({prefix:t,size:e=16,alphabet:r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:a="-"}={})=>{const n=()=>{const s=r.length,o=new Array(e);for(let i=0;i<e;i++)o[i]=r[Math.random()*s|0];return o.join("")};if(t==null)return n;if(r.includes(a))throw new yd({argument:"separator",message:`The separator "${a}" must not be part of the alphabet "${r}".`});return()=>`${t}${a}${n()}`},ir=m9();function mf(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var v9=["fetch failed","failed to fetch"];function g9({error:t,url:e,requestBodyValues:r}){if(mf(t))return t;if(t instanceof TypeError&&v9.includes(t.message.toLowerCase())){const a=t.cause;if(a!=null)return new Xe({message:`Cannot connect to API: ${a.message}`,cause:a,url:e,requestBodyValues:r,isRetryable:!0})}return t}function y9(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>r!=null))}function R0({apiKey:t,environmentVariableName:e,apiKeyParameterName:r="apiKey",description:a}){if(typeof t=="string")return t;if(t!=null)throw new Ji({message:`${a} API key must be a string.`});if(typeof process>"u")throw new Ji({message:`${a} API key is missing. Pass it using the '${r}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[e],t==null)throw new Ji({message:`${a} API key is missing. Pass it using the '${r}' parameter or the ${e} environment variable.`});if(typeof t!="string")throw new Ji({message:`${a} API key must be a string. The value of the ${e} environment variable is not a string.`});return t}var _9=/"__proto__"\s*:/,w9=/"constructor"\s*:/;function b9(t){const e=JSON.parse(t);return e===null||typeof e!="object"||_9.test(t)===!1&&w9.test(t)===!1?e:E9(e)}function E9(t){let e=[t];for(;e.length;){const r=e;e=[];for(const a of r){if(Object.prototype.hasOwnProperty.call(a,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const n in a){const s=a[n];s&&typeof s=="object"&&e.push(s)}}}return t}function vf(t){const{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return b9(t)}finally{Error.stackTraceLimit=e}}var gf=Symbol.for("vercel.ai.validator");function $9(t){return{[gf]:!0,validate:t}}function S9(t){return typeof t=="object"&&t!==null&&gf in t&&t[gf]===!0&&"validate"in t}function P9(t){return S9(t)?t:T9(t)}function T9(t){return $9(async e=>{const r=await t["~standard"].validate(e);return r.issues==null?{success:!0,value:r.value}:{success:!1,error:new Br({value:e,cause:r.issues})}})}async function x9({value:t,schema:e}){const r=await go({value:t,schema:e});if(!r.success)throw Br.wrap({value:t,cause:r.error});return r.value}async function go({value:t,schema:e}){const r=P9(e);try{if(r.validate==null)return{success:!0,value:t,rawValue:t};const a=await r.validate(t);return a.success?{success:!0,value:a.value,rawValue:t}:{success:!1,error:Br.wrap({value:t,cause:a.error}),rawValue:t}}catch(a){return{success:!1,error:Br.wrap({value:t,cause:a}),rawValue:t}}}async function k9({text:t,schema:e}){try{const r=vf(t);return e==null?r:x9({value:r,schema:e})}catch(r){throw xn.isInstance(r)||Br.isInstance(r)?r:new xn({text:t,cause:r})}}async function O0({text:t,schema:e}){try{const r=vf(t);return e==null?{success:!0,value:r,rawValue:r}:await go({value:r,schema:e})}catch(r){return{success:!1,error:xn.isInstance(r)?r:new xn({text:t,cause:r}),rawValue:void 0}}}function yl(t){try{return vf(t),!0}catch{return!1}}function I9({stream:t,schema:e}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Zm).pipeThrough(new TransformStream({async transform({data:r},a){r!=="[DONE]"&&a.enqueue(await O0({text:r,schema:e}))}}))}async function Wr({provider:t,providerOptions:e,schema:r}){if((e==null?void 0:e[t])==null)return;const a=await go({value:e[t],schema:r});if(!a.success)throw new yd({argument:"providerOptions",message:`invalid ${t} provider options`,cause:a.error});return a.value}var C9=()=>globalThis.fetch,Rr=async({url:t,headers:e,body:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>A0({url:t,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(r),values:r},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),R9=async({url:t,headers:e,formData:r,failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o})=>A0({url:t,headers:e,body:{content:r,values:Object.fromEntries(r.entries())},failedResponseHandler:a,successfulResponseHandler:n,abortSignal:s,fetch:o}),A0=async({url:t,headers:e={},body:r,successfulResponseHandler:a,failedResponseHandler:n,abortSignal:s,fetch:o=C9()})=>{try{const i=await o(t,{method:"POST",headers:y9(e),body:r.content,signal:s}),l=vo(i);if(!i.ok){let c;try{c=await n({response:i,url:t,requestBodyValues:r.values})}catch(u){throw mf(u)||Xe.isInstance(u)?u:new Xe({message:"Failed to process error response",cause:u,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw c.value}try{return await a({response:i,url:t,requestBodyValues:r.values})}catch(c){throw c instanceof Error&&(mf(c)||Xe.isInstance(c))?c:new Xe({message:"Failed to process successful response",cause:c,statusCode:i.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(i){throw g9({error:i,url:t,requestBodyValues:r.values})}};function r5(t){return t}function yf({id:t,name:e,inputSchema:r}){return({execute:a,outputSchema:n,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l,...c})=>({type:"provider-defined",id:t,name:e,args:c,inputSchema:r,outputSchema:n,execute:a,toModelOutput:s,onInputStart:o,onInputDelta:i,onInputAvailable:l})}var N0=({errorSchema:t,errorToMessage:e,isRetryable:r})=>async({response:a,url:n,requestBodyValues:s})=>{const o=await a.text(),i=vo(a);if(o.trim()==="")return{responseHeaders:i,value:new Xe({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})};try{const l=await k9({text:o,schema:t});return{responseHeaders:i,value:new Xe({message:e(l),url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,data:l,isRetryable:r==null?void 0:r(a,l)})}}catch{return{responseHeaders:i,value:new Xe({message:a.statusText,url:n,requestBodyValues:s,statusCode:a.status,responseHeaders:i,responseBody:o,isRetryable:r==null?void 0:r(a)})}}},_l=t=>async({response:e})=>{const r=vo(e);if(e.body==null)throw new Hv({});return{responseHeaders:r,value:I9({stream:e.body,schema:t})}},sa=t=>async({response:e,url:r,requestBodyValues:a})=>{const n=await e.text(),s=await O0({text:n,schema:t}),o=vo(e);if(!s.success)throw new Xe({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:o,responseBody:n,url:r,requestBodyValues:a});return{responseHeaders:o,value:s.value,rawValue:s.rawValue}},O9=()=>async({response:t,url:e,requestBodyValues:r})=>{const a=vo(t);if(!t.body)throw new Xe({message:"Response body is empty",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0});try{const n=await t.arrayBuffer();return{responseHeaders:a,value:new Uint8Array(n)}}catch(n){throw new Xe({message:"Failed to read response as array buffer",url:e,requestBodyValues:r,statusCode:t.status,responseHeaders:a,responseBody:void 0,cause:n})}},{btoa:A9,atob:N9}=globalThis;function M9(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=N9(e);return Uint8Array.from(r,a=>a.codePointAt(0))}function j9(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCodePoint(t[r]);return A9(e)}function oa(t){return t instanceof Uint8Array?j9(t):t}function M0(t){return t==null?void 0:t.replace(/\/$/,"")}var _f=R({error:R({message:S(),type:S().nullish(),param:pr().nullish(),code:Ve([S(),K()]).nullish()})}),Qr=N0({errorSchema:_f,errorToMessage:t=>t.error.message});function D9({prompt:t,systemMessageMode:e="system"}){const r=[],a=[];for(const{role:n,content:s}of t)switch(n){case"system":{switch(e){case"system":{r.push({role:"system",content:s});break}case"developer":{r.push({role:"developer",content:s});break}case"remove":{a.push({type:"other",message:"system messages are removed for this model"});break}default:{const o=e;throw new Error(`Unsupported system message mode: ${o}`)}}break}case"user":{if(s.length===1&&s[0].type==="text"){r.push({role:"user",content:s[0].text});break}r.push({role:"user",content:s.map((o,i)=>{var l,c,u;switch(o.type){case"text":return{type:"text",text:o.text};case"file":if(o.mediaType.startsWith("image/")){const h=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${h};base64,${oa(o.data)}`,detail:(c=(l=o.providerOptions)==null?void 0:l.openai)==null?void 0:c.imageDetail}}}else if(o.mediaType.startsWith("audio/")){if(o.data instanceof URL)throw new fr({functionality:"audio file parts with URLs"});switch(o.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:oa(o.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:oa(o.data),format:"mp3"}};default:throw new fr({functionality:`audio content parts with media type ${o.mediaType}`})}}else if(o.mediaType==="application/pdf"){if(o.data instanceof URL)throw new fr({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof o.data=="string"&&o.data.startsWith("file-")?{file_id:o.data}:{filename:(u=o.filename)!=null?u:`part-${i}.pdf`,file_data:`data:application/pdf;base64,${oa(o.data)}`}}}else throw new fr({functionality:`file part media type ${o.mediaType}`})}})});break}case"assistant":{let o="";const i=[];for(const l of s)switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)}});break}}r.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0});break}case"tool":{for(const o of s){const i=o.output;let l;switch(i.type){case"text":case"error-text":l=i.value;break;case"content":case"json":case"error-json":l=JSON.stringify(i.value);break}r.push({role:"tool",tool_call_id:o.toolCallId,content:l})}break}default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return{messages:r,warnings:a}}function j0({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function D0(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var L9=R({logitBias:Qt(EA(),K()).optional(),logprobs:Ve([$t(),K()]).optional(),parallelToolCalls:$t().optional(),user:S().optional(),reasoningEffort:zt(["minimal","low","medium","high"]).optional(),maxCompletionTokens:K().optional(),store:$t().optional(),metadata:Qt(S().max(64),S().max(512)).optional(),prediction:Qt(S(),pr()).optional(),structuredOutputs:$t().optional(),serviceTier:zt(["auto","flex","priority"]).optional(),strictJsonSchema:$t().optional(),textVerbosity:zt(["low","medium","high"]).optional(),promptCacheKey:S().optional(),safetyIdentifier:S().optional()}),L0=R({key:S(),type:zt(["eq","ne","gt","gte","lt","lte"]),value:Ve([S(),K(),$t()])}),z0=R({type:zt(["and","or"]),filters:ce(Ve([L0,hy(()=>z0)]))}),z9=Ve([L0,z0]),U0=R({vectorStoreIds:ce(S()).optional(),maxNumResults:K().optional(),ranking:R({ranker:zt(["auto","default-2024-08-21"]).optional()}).optional(),filters:z9.optional()}),U9=yf({id:"openai.file_search",name:"file_search",inputSchema:R({query:S()})}),q0=R({searchContextSize:zt(["low","medium","high"]).optional(),userLocation:R({type:ne("approximate"),country:S().optional(),city:S().optional(),region:S().optional(),timezone:S().optional()}).optional()}),q9=yf({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:R({})});function F9({tools:t,toolChoice:e,structuredOutputs:r,strictJsonSchema:a}){t=t!=null&&t.length?t:void 0;const n=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};const s=[];for(const i of t)switch(i.type){case"function":s.push({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema,strict:r?a:void 0}});break;case"provider-defined":switch(i.id){case"openai.file_search":{const l=U0.parse(i.args);s.push({type:"file_search",vector_store_ids:l.vectorStoreIds,max_num_results:l.maxNumResults,ranking_options:l.ranking?{ranker:l.ranking.ranker}:void 0,filters:l.filters});break}case"openai.web_search_preview":{const l=q0.parse(i.args);s.push({type:"web_search_preview",search_context_size:l.searchContextSize,user_location:l.userLocation});break}default:n.push({type:"unsupported-tool",tool:i});break}break;default:n.push({type:"unsupported-tool",tool:i});break}if(e==null)return{tools:s,toolChoice:void 0,toolWarnings:n};const o=e.type;switch(o){case"auto":case"none":case"required":return{tools:s,toolChoice:o,toolWarnings:n};case"tool":return{tools:s,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:n};default:{const i=o;throw new fr({functionality:`tool choice type: ${i}`})}}}var Z9=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,seed:c,tools:u,toolChoice:h,providerOptions:g}){var d,f,v,m;const p=[],y=(d=await Wr({provider:"openai",providerOptions:g,schema:L9}))!=null?d:{},_=(f=y.structuredOutputs)!=null?f:!0;n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),(l==null?void 0:l.type)==="json"&&l.schema!=null&&!_&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{messages:w,warnings:E}=D9({prompt:t,systemMessageMode:G9(this.modelId)});p.push(...E);const P=(v=y.strictJsonSchema)!=null?v:!1,T={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:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(l==null?void 0:l.type)==="json"?_&&l.schema!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:P,name:(m=l.name)!=null?m:"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,safety_identifier:y.safetyIdentifier,messages:w};Z0(this.modelId)?(T.temperature!=null&&(T.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,p.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),T.frequency_penalty!=null&&(T.frequency_penalty=void 0,p.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),T.presence_penalty!=null&&(T.presence_penalty=void 0,p.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),T.logit_bias!=null&&(T.logit_bias=void 0,p.push({type:"other",message:"logitBias is not supported for reasoning models"})),T.logprobs!=null&&(T.logprobs=void 0,p.push({type:"other",message:"logprobs is not supported for reasoning models"})),T.top_logprobs!=null&&(T.top_logprobs=void 0,p.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),T.max_tokens!=null&&(T.max_completion_tokens==null&&(T.max_completion_tokens=T.max_tokens),T.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&T.temperature!=null&&(T.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),y.serviceTier==="flex"&&!B9(this.modelId)&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),T.service_tier=void 0),y.serviceTier==="priority"&&!J9(this.modelId)&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),T.service_tier=void 0);const{tools:O,toolChoice:M,toolWarnings:J}=F9({tools:u,toolChoice:h,structuredOutputs:_,strictJsonSchema:P});return{args:{...T,tools:O,tool_choice:M},warnings:[...p,...J]}}async doGenerate(t){var e,r,a,n,s,o,i,l,c,u,h,g,d,f;const{args:v,warnings:m}=await this.getArgs(t),{responseHeaders:p,value:y,rawValue:_}=await Rr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:v,failedResponseHandler:Qr,successfulResponseHandler:sa(V9),abortSignal:t.abortSignal,fetch:this.config.fetch}),w=y.choices[0],E=[],P=w.message.content;P!=null&&P.length>0&&E.push({type:"text",text:P});for(const J of(e=w.message.tool_calls)!=null?e:[])E.push({type:"tool-call",toolCallId:(r=J.id)!=null?r:ir(),toolName:J.function.name,input:J.function.arguments});for(const J of(a=w.message.annotations)!=null?a:[])E.push({type:"source",sourceType:"url",id:ir(),url:J.url,title:J.title});const T=(n=y.usage)==null?void 0:n.completion_tokens_details,O=(s=y.usage)==null?void 0:s.prompt_tokens_details,M={openai:{}};return(T==null?void 0:T.accepted_prediction_tokens)!=null&&(M.openai.acceptedPredictionTokens=T==null?void 0:T.accepted_prediction_tokens),(T==null?void 0:T.rejected_prediction_tokens)!=null&&(M.openai.rejectedPredictionTokens=T==null?void 0:T.rejected_prediction_tokens),((o=w.logprobs)==null?void 0:o.content)!=null&&(M.openai.logprobs=w.logprobs.content),{content:E,finishReason:D0(w.finish_reason),usage:{inputTokens:(l=(i=y.usage)==null?void 0:i.prompt_tokens)!=null?l:void 0,outputTokens:(u=(c=y.usage)==null?void 0:c.completion_tokens)!=null?u:void 0,totalTokens:(g=(h=y.usage)==null?void 0:h.total_tokens)!=null?g:void 0,reasoningTokens:(d=T==null?void 0:T.reasoning_tokens)!=null?d:void 0,cachedInputTokens:(f=O==null?void 0:O.cached_tokens)!=null?f:void 0},request:{body:v},response:{...j0(y),headers:p,body:_},warnings:m,providerMetadata:M}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await Rr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:a,failedResponseHandler:Qr,successfulResponseHandler:_l(H9),abortSignal:t.abortSignal,fetch:this.config.fetch}),o=[];let i="unknown";const l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0,u=!1;const h={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(g){g.enqueue({type:"stream-start",warnings:r})},transform(g,d){var f,v,m,p,y,_,w,E,P,T,O,M,J,H,G,F,Z,te,pe,ve,N,ie,D,C;if(t.includeRawChunks&&d.enqueue({type:"raw",rawValue:g.rawValue}),!g.success){i="error",d.enqueue({type:"error",error:g.error});return}const z=g.value;if("error"in z){i="error",d.enqueue({type:"error",error:z.error});return}c&&(c=!1,d.enqueue({type:"response-metadata",...j0(z)})),z.usage!=null&&(l.inputTokens=(f=z.usage.prompt_tokens)!=null?f:void 0,l.outputTokens=(v=z.usage.completion_tokens)!=null?v:void 0,l.totalTokens=(m=z.usage.total_tokens)!=null?m:void 0,l.reasoningTokens=(y=(p=z.usage.completion_tokens_details)==null?void 0:p.reasoning_tokens)!=null?y:void 0,l.cachedInputTokens=(w=(_=z.usage.prompt_tokens_details)==null?void 0:_.cached_tokens)!=null?w:void 0,((E=z.usage.completion_tokens_details)==null?void 0:E.accepted_prediction_tokens)!=null&&(h.openai.acceptedPredictionTokens=(P=z.usage.completion_tokens_details)==null?void 0:P.accepted_prediction_tokens),((T=z.usage.completion_tokens_details)==null?void 0:T.rejected_prediction_tokens)!=null&&(h.openai.rejectedPredictionTokens=(O=z.usage.completion_tokens_details)==null?void 0:O.rejected_prediction_tokens));const A=z.choices[0];if((A==null?void 0:A.finish_reason)!=null&&(i=D0(A.finish_reason)),((M=A==null?void 0:A.logprobs)==null?void 0:M.content)!=null&&(h.openai.logprobs=A.logprobs.content),(A==null?void 0:A.delta)==null)return;const b=A.delta;if(b.content!=null&&(u||(d.enqueue({type:"text-start",id:"0"}),u=!0),d.enqueue({type:"text-delta",id:"0",delta:b.content})),b.tool_calls!=null)for(const x of b.tool_calls){const L=x.index;if(o[L]==null){if(x.type!=="function")throw new Js({data:x,message:"Expected 'function' type."});if(x.id==null)throw new Js({data:x,message:"Expected 'id' to be a string."});if(((J=x.function)==null?void 0:J.name)==null)throw new Js({data:x,message:"Expected 'function.name' to be a string."});d.enqueue({type:"tool-input-start",id:x.id,toolName:x.function.name}),o[L]={id:x.id,type:"function",function:{name:x.function.name,arguments:(H=x.function.arguments)!=null?H:""},hasFinished:!1};const X=o[L];((G=X.function)==null?void 0:G.name)!=null&&((F=X.function)==null?void 0:F.arguments)!=null&&(X.function.arguments.length>0&&d.enqueue({type:"tool-input-delta",id:X.id,delta:X.function.arguments}),yl(X.function.arguments)&&(d.enqueue({type:"tool-input-end",id:X.id}),d.enqueue({type:"tool-call",toolCallId:(Z=X.id)!=null?Z:ir(),toolName:X.function.name,input:X.function.arguments}),X.hasFinished=!0));continue}const W=o[L];W.hasFinished||(((te=x.function)==null?void 0:te.arguments)!=null&&(W.function.arguments+=(ve=(pe=x.function)==null?void 0:pe.arguments)!=null?ve:""),d.enqueue({type:"tool-input-delta",id:W.id,delta:(N=x.function.arguments)!=null?N:""}),((ie=W.function)==null?void 0:ie.name)!=null&&((D=W.function)==null?void 0:D.arguments)!=null&&yl(W.function.arguments)&&(d.enqueue({type:"tool-input-end",id:W.id}),d.enqueue({type:"tool-call",toolCallId:(C=W.id)!=null?C:ir(),toolName:W.function.name,input:W.function.arguments}),W.hasFinished=!0))}if(b.annotations!=null)for(const x of b.annotations)d.enqueue({type:"source",sourceType:"url",id:ir(),url:x.url,title:x.title})},flush(g){u&&g.enqueue({type:"text-end",id:"0"}),g.enqueue({type:"finish",finishReason:i,usage:l,...h!=null?{providerMetadata:h}:{}})}})),request:{body:a},response:{headers:n}}}},F0=R({prompt_tokens:K().nullish(),completion_tokens:K().nullish(),total_tokens:K().nullish(),prompt_tokens_details:R({cached_tokens:K().nullish()}).nullish(),completion_tokens_details:R({reasoning_tokens:K().nullish(),accepted_prediction_tokens:K().nullish(),rejected_prediction_tokens:K().nullish()}).nullish()}).nullish(),V9=R({id:S().nullish(),created:K().nullish(),model:S().nullish(),choices:ce(R({message:R({role:ne("assistant").nullish(),content:S().nullish(),tool_calls:ce(R({id:S().nullish(),type:ne("function"),function:R({name:S(),arguments:S()})})).nullish(),annotations:ce(R({type:ne("url_citation"),start_index:K(),end_index:K(),url:S(),title:S()})).nullish()}),index:K(),logprobs:R({content:ce(R({token:S(),logprob:K(),top_logprobs:ce(R({token:S(),logprob:K()}))})).nullish()}).nullish(),finish_reason:S().nullish()})),usage:F0}),H9=Ve([R({id:S().nullish(),created:K().nullish(),model:S().nullish(),choices:ce(R({delta:R({role:zt(["assistant"]).nullish(),content:S().nullish(),tool_calls:ce(R({index:K(),id:S().nullish(),type:ne("function").nullish(),function:R({name:S().nullish(),arguments:S().nullish()})})).nullish(),annotations:ce(R({type:ne("url_citation"),start_index:K(),end_index:K(),url:S(),title:S()})).nullish()}).nullish(),logprobs:R({content:ce(R({token:S(),logprob:K(),top_logprobs:ce(R({token:S(),logprob:K()}))})).nullish()}).nullish(),finish_reason:S().nullish(),index:K()})),usage:F0}),_f]);function Z0(t){return(t.startsWith("o")||t.startsWith("gpt-5"))&&!t.startsWith("gpt-5-chat")}function B9(t){return t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")}function J9(t){return t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini")}function G9(t){var e,r;return Z0(t)?(r=(e=K9[t])==null?void 0:e.systemMessageMode)!=null?r:"developer":"system"}var K9={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}};function W9({prompt:t,user:e="user",assistant:r="assistant"}){let a="";t[0].role==="system"&&(a+=`${t[0].content}
522
526
 
523
- `,t=t.slice(1));for(const{role:n,content:s}of t)switch(n){case"system":throw new ra({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const o=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");a+=`${e}:
527
+ `,t=t.slice(1));for(const{role:n,content:s}of t)switch(n){case"system":throw new Kn({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const o=s.map(i=>{switch(i.type){case"text":return i.text}}).filter(Boolean).join("");a+=`${e}:
524
528
  ${o}
525
529
 
526
- `;break}case"assistant":{const o=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new Mr({functionality:"tool-call messages"})}}).join("");a+=`${r}:
530
+ `;break}case"assistant":{const o=s.map(i=>{switch(i.type){case"text":return i.text;case"tool-call":throw new fr({functionality:"tool-call messages"})}}).join("");a+=`${r}:
527
531
  ${o}
528
532
 
529
- `;break}case"tool":throw new Mr({functionality:"tool messages"});default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return a+=`${r}:
533
+ `;break}case"tool":throw new fr({functionality:"tool messages"});default:{const o=n;throw new Error(`Unsupported role: ${o}`)}}return a+=`${r}:
530
534
  `,{prompt:a,stopSequences:[`
531
- ${e}:`]}}function M0({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function j0(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var C9=_t(()=>De(x({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(x({text:E(),finish_reason:E(),logprobs:x({tokens:oe(E()),token_logprobs:oe(Z()),top_logprobs:oe(kt(E(),Z())).nullish()}).nullish()})),usage:x({prompt_tokens:Z(),completion_tokens:Z(),total_tokens:Z()}).nullish()}))),R9=_t(()=>De(He([x({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(x({text:E(),finish_reason:E().nullish(),index:Z(),logprobs:x({tokens:oe(E()),token_logprobs:oe(Z()),top_logprobs:oe(kt(E(),Z())).nullish()}).nullish()})),usage:x({prompt_tokens:Z(),completion_tokens:Z(),total_tokens:Z()}).nullish()}),yp]))),D0=_t(()=>De(x({echo:Pt().optional(),logitBias:kt(E(),Z()).optional(),suffix:E().optional(),user:E().optional(),logprobs:He([Pt(),Z()]).optional()}))),O9=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:f,providerOptions:g}){const d=[],h={...await rn({provider:"openai",providerOptions:g,schema:D0}),...await rn({provider:this.providerOptionsName,providerOptions:g,schema:D0})};n!=null&&d.push({type:"unsupported-setting",setting:"topK"}),c!=null&&c.length&&d.push({type:"unsupported-setting",setting:"tools"}),u!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:m}=T9({prompt:t}),p=[...m??[],...i??[]];return{args:{model:this.modelId,echo:h.echo,logit_bias:h.logitBias,logprobs:(h==null?void 0:h.logprobs)===!0?0:(h==null?void 0:h.logprobs)===!1||h==null?void 0:h.logprobs,suffix:h.suffix,user:h.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,seed:f,prompt:v,stop:p.length>0?p:void 0},warnings:d}}async doGenerate(t){var e,r,a;const{args:n,warnings:s}=await this.getArgs(t),{responseHeaders:o,value:i,rawValue:l}=await or({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Kt(this.config.headers(),t.headers),body:n,failedResponseHandler:on,successfulResponseHandler:Lr(C9),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=i.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(a=i.usage)==null?void 0:a.total_tokens},finishReason:j0(c.finish_reason),request:{body:n},response:{...M0(i),headers:o,body:l},providerMetadata:u,warnings:s}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await or({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:Kt(this.config.headers(),t.headers),body:a,failedResponseHandler:on,successfulResponseHandler:uo(R9),abortSignal:t.abortSignal,fetch:this.config.fetch});let o="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,f){if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){o="error",f.enqueue({type:"error",error:u.error});return}const g=u.value;if("error"in g){o="error",f.enqueue({type:"error",error:g.error});return}c&&(c=!1,f.enqueue({type:"response-metadata",...M0(g)}),f.enqueue({type:"text-start",id:"0"})),g.usage!=null&&(l.inputTokens=g.usage.prompt_tokens,l.outputTokens=g.usage.completion_tokens,l.totalTokens=g.usage.total_tokens);const d=g.choices[0];(d==null?void 0:d.finish_reason)!=null&&(o=j0(d.finish_reason)),(d==null?void 0:d.logprobs)!=null&&(i.openai.logprobs=d.logprobs),(d==null?void 0:d.text)!=null&&d.text.length>0&&f.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:o,providerMetadata:i,usage:l})}})),request:{body:a},response:{headers:n}}}},N9=_t(()=>De(x({dimensions:Z().optional(),user:E().optional()}))),A9=_t(()=>De(x({data:oe(x({embedding:oe(Z())})),usage:x({prompt_tokens:Z()}).nullish()}))),M9=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;if(t.length>this.maxEmbeddingsPerCall)throw new uC({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const s=(n=await rn({provider:"openai",providerOptions:a,schema:N9}))!=null?n:{},{responseHeaders:o,value:i,rawValue:l}=await or({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:Kt(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:on,successfulResponseHandler:Lr(A9),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:o,body:l}}}},j9=_t(()=>De(x({data:oe(x({b64_json:E(),revised_prompt:E().optional()}))}))),D9={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},L9=new Set(["gpt-image-1","gpt-image-1-mini"]),z9=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=D9[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:a,seed:n,providerOptions:s,headers:o,abortSignal:i}){var l,c,u,f;const g=[];a!=null&&g.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),n!=null&&g.push({type:"unsupported-setting",setting:"seed"});const d=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:h,responseHeaders:v}=await or({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:Kt(this.config.headers(),o),body:{model:this.modelId,prompt:t,n:e,size:r,...(f=s.openai)!=null?f:{},...L9.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:on,successfulResponseHandler:Lr(j9),abortSignal:i,fetch:this.config.fetch});return{images:h.data.map(m=>m.b64_json),warnings:g,response:{timestamp:d,modelId:this.modelId,headers:v},providerMetadata:{openai:{images:h.data.map(m=>m.revised_prompt?{revisedPrompt:m.revised_prompt}:null)}}}}},U9=Ht(()=>De(x({code:E().nullish(),containerId:E()}))),q9=Ht(()=>De(x({outputs:oe(ar("type",[x({type:W("logs"),logs:E()}),x({type:W("image"),url:E()})])).nullish()}))),F9=Ht(()=>De(x({container:He([E(),x({fileIds:oe(E()).optional()})]).optional()}))),Z9=es({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:U9,outputSchema:q9}),V9=(t={})=>Z9(t),L0=x({key:E(),type:ht(["eq","ne","gt","gte","lt","lte"]),value:He([E(),Z(),Pt()])}),z0=x({type:ht(["and","or"]),filters:oe(He([L0,dy(()=>z0)]))}),H9=Ht(()=>De(x({vectorStoreIds:oe(E()),maxNumResults:Z().optional(),ranking:x({ranker:E().optional(),scoreThreshold:Z().optional()}).optional(),filters:He([L0,z0]).optional()}))),B9=Ht(()=>De(x({queries:oe(E()),results:oe(x({attributes:kt(E(),jr()),fileId:E(),filename:E(),score:Z(),text:E()})).nullable()}))),J9=es({id:"openai.file_search",name:"file_search",inputSchema:x({}),outputSchema:B9}),G9=Ht(()=>De(x({background:ht(["auto","opaque","transparent"]).optional(),inputFidelity:ht(["low","high"]).optional(),inputImageMask:x({fileId:E().optional(),imageUrl:E().optional()}).optional(),model:E().optional(),moderation:ht(["auto"]).optional(),outputCompression:Z().int().min(0).max(100).optional(),outputFormat:ht(["png","jpeg","webp"]).optional(),partialImages:Z().int().min(0).max(3).optional(),quality:ht(["auto","low","medium","high"]).optional(),size:ht(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),K9=Ht(()=>De(x({}))),W9=Ht(()=>De(x({result:E()}))),Q9=es({id:"openai.image_generation",name:"image_generation",inputSchema:K9,outputSchema:W9}),Y9=(t={})=>Q9(t),U0=Ht(()=>De(x({action:x({type:W("exec"),command:oe(E()),timeoutMs:Z().optional(),user:E().optional(),workingDirectory:E().optional(),env:kt(E(),E()).optional()})}))),q0=Ht(()=>De(x({output:E()}))),X9=es({id:"openai.local_shell",name:"local_shell",inputSchema:U0,outputSchema:q0}),eD=Ht(()=>De(x({filters:x({allowedDomains:oe(E()).optional()}).optional(),searchContextSize:ht(["low","medium","high"]).optional(),userLocation:x({type:W("approximate"),country:E().optional(),city:E().optional(),region:E().optional(),timezone:E().optional()}).optional()}))),tD=Ht(()=>De(x({}))),rD=Ht(()=>De(x({action:ar("type",[x({type:W("search"),query:E().optional()}),x({type:W("openPage"),url:E()}),x({type:W("find"),url:E(),pattern:E()})])}))),nD=es({id:"openai.web_search",name:"web_search",inputSchema:tD,outputSchema:rD}),aD=(t={})=>nD(t),sD=Ht(()=>De(x({searchContextSize:ht(["low","medium","high"]).optional(),userLocation:x({type:W("approximate"),country:E().optional(),city:E().optional(),region:E().optional(),timezone:E().optional()}).optional()}))),oD=Ht(()=>De(x({}))),iD=Ht(()=>De(x({action:ar("type",[x({type:W("search"),query:E().optional()}),x({type:W("openPage"),url:E()}),x({type:W("find"),url:E(),pattern:E()})])}))),lD=es({id:"openai.web_search_preview",name:"web_search_preview",inputSchema:oD,outputSchema:iD}),cD={codeInterpreter:V9,fileSearch:J9,imageGeneration:Y9,localShell:X9,webSearchPreview:lD,webSearch:aD};function F0(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function uD({prompt:t,systemMessageMode:e,fileIdPrefixes:r,store:a,hasLocalShellTool:n=!1}){var s,o,i,l;const c=[],u=[];for(const{role:f,content:g}of t)switch(f){case"system":{switch(e){case"system":{c.push({role:"system",content:g});break}case"developer":{c.push({role:"developer",content:g});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=e;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{c.push({role:"user",content:g.map((d,h)=>{var v,m,p;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const _=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&F0(d.data,r)?{file_id:d.data}:{image_url:`data:${_};base64,${la(d.data)}`},detail:(m=(v=d.providerOptions)==null?void 0:v.openai)==null?void 0:m.imageDetail}}else{if(d.mediaType==="application/pdf")return d.data instanceof URL?{type:"input_file",file_url:d.data.toString()}:{type:"input_file",...typeof d.data=="string"&&F0(d.data,r)?{file_id:d.data}:{filename:(p=d.filename)!=null?p:`part-${h}.pdf`,file_data:`data:application/pdf;base64,${la(d.data)}`}};throw new Mr({functionality:`file part media type ${d.mediaType}`})}}})});break}case"assistant":{const d={},h={};for(const v of g)switch(v.type){case"text":{const m=(o=(s=v.providerOptions)==null?void 0:s.openai)==null?void 0:o.itemId;if(a&&m!=null){c.push({type:"item_reference",id:m});break}c.push({role:"assistant",content:[{type:"output_text",text:v.text}],id:m});break}case"tool-call":{if(h[v.toolCallId]=v,v.providerExecuted)break;const m=(l=(i=v.providerOptions)==null?void 0:i.openai)==null?void 0:l.itemId;if(a&&m!=null){c.push({type:"item_reference",id:m});break}if(n&&v.toolName==="local_shell"){const p=await tn({value:v.input,schema:U0});c.push({type:"local_shell_call",call_id:v.toolCallId,id:m,action:{type:"exec",command:p.action.command,timeout_ms:p.action.timeoutMs,user:p.action.user,working_directory:p.action.workingDirectory,env:p.action.env}});break}c.push({type:"function_call",call_id:v.toolCallId,name:v.toolName,arguments:JSON.stringify(v.input),id:m});break}case"tool-result":{a?c.push({type:"item_reference",id:v.toolCallId}):u.push({type:"other",message:`Results for OpenAI tool ${v.toolName} are not sent to the API when store is false`});break}case"reasoning":{const m=await rn({provider:"openai",providerOptions:v.providerOptions,schema:dD}),p=m==null?void 0:m.itemId;if(p!=null){const _=d[p];if(a)_===void 0&&(c.push({type:"item_reference",id:p}),d[p]={type:"reasoning",id:p,summary:[]});else{const w=[];v.text.length>0?w.push({type:"summary_text",text:v.text}):_!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(v)}.`}),_===void 0?(d[p]={type:"reasoning",id:p,encrypted_content:m==null?void 0:m.reasoningEncryptedContent,summary:w},c.push(d[p])):(_.summary.push(...w),(m==null?void 0:m.reasoningEncryptedContent)!=null&&(_.encrypted_content=m.reasoningEncryptedContent))}}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(v)}.`});break}}break}case"tool":{for(const d of g){const h=d.output;if(n&&d.toolName==="local_shell"&&h.type==="json"){const m=await tn({value:h.value,schema:q0});c.push({type:"local_shell_call_output",call_id:d.toolCallId,output:m.output});break}let v;switch(h.type){case"text":case"error-text":v=h.value;break;case"json":case"error-json":v=JSON.stringify(h.value);break;case"content":v=h.value.map(m=>{switch(m.type){case"text":return{type:"input_text",text:m.text};case"media":return m.mediaType.startsWith("image/")?{type:"input_image",image_url:`data:${m.mediaType};base64,${m.data}`}:{type:"input_file",filename:"data",file_data:`data:${m.mediaType};base64,${m.data}`}}});break}c.push({type:"function_call_output",call_id:d.toolCallId,output:v})}break}default:{const d=f;throw new Error(`Unsupported role: ${d}`)}}return{input:c,warnings:u}}var dD=x({itemId:E().nullish(),reasoningEncryptedContent:E().nullish()});function Z0({finishReason:t,hasFunctionCall:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}var pD=_t(()=>De(He([x({type:W("response.output_text.delta"),item_id:E(),delta:E(),logprobs:oe(x({token:E(),logprob:Z(),top_logprobs:oe(x({token:E(),logprob:Z()}))})).nullish()}),x({type:ht(["response.completed","response.incomplete"]),response:x({incomplete_details:x({reason:E()}).nullish(),usage:x({input_tokens:Z(),input_tokens_details:x({cached_tokens:Z().nullish()}).nullish(),output_tokens:Z(),output_tokens_details:x({reasoning_tokens:Z().nullish()}).nullish()}),service_tier:E().nullish()})}),x({type:W("response.created"),response:x({id:E(),created_at:Z(),model:E(),service_tier:E().nullish()})}),x({type:W("response.output_item.added"),output_index:Z(),item:ar("type",[x({type:W("message"),id:E()}),x({type:W("reasoning"),id:E(),encrypted_content:E().nullish()}),x({type:W("function_call"),id:E(),call_id:E(),name:E(),arguments:E()}),x({type:W("web_search_call"),id:E(),status:E()}),x({type:W("computer_call"),id:E(),status:E()}),x({type:W("file_search_call"),id:E()}),x({type:W("image_generation_call"),id:E()}),x({type:W("code_interpreter_call"),id:E(),container_id:E(),code:E().nullable(),outputs:oe(ar("type",[x({type:W("logs"),logs:E()}),x({type:W("image"),url:E()})])).nullable(),status:E()})])}),x({type:W("response.output_item.done"),output_index:Z(),item:ar("type",[x({type:W("message"),id:E()}),x({type:W("reasoning"),id:E(),encrypted_content:E().nullish()}),x({type:W("function_call"),id:E(),call_id:E(),name:E(),arguments:E(),status:W("completed")}),x({type:W("code_interpreter_call"),id:E(),code:E().nullable(),container_id:E(),outputs:oe(ar("type",[x({type:W("logs"),logs:E()}),x({type:W("image"),url:E()})])).nullable()}),x({type:W("image_generation_call"),id:E(),result:E()}),x({type:W("web_search_call"),id:E(),status:E(),action:ar("type",[x({type:W("search"),query:E().nullish()}),x({type:W("open_page"),url:E()}),x({type:W("find"),url:E(),pattern:E()})])}),x({type:W("file_search_call"),id:E(),queries:oe(E()),results:oe(x({attributes:kt(E(),jr()),file_id:E(),filename:E(),score:Z(),text:E()})).nullish()}),x({type:W("local_shell_call"),id:E(),call_id:E(),action:x({type:W("exec"),command:oe(E()),timeout_ms:Z().optional(),user:E().optional(),working_directory:E().optional(),env:kt(E(),E()).optional()})}),x({type:W("computer_call"),id:E(),status:W("completed")})])}),x({type:W("response.function_call_arguments.delta"),item_id:E(),output_index:Z(),delta:E()}),x({type:W("response.image_generation_call.partial_image"),item_id:E(),output_index:Z(),partial_image_b64:E()}),x({type:W("response.code_interpreter_call_code.delta"),item_id:E(),output_index:Z(),delta:E()}),x({type:W("response.code_interpreter_call_code.done"),item_id:E(),output_index:Z(),code:E()}),x({type:W("response.output_text.annotation.added"),annotation:ar("type",[x({type:W("url_citation"),url:E(),title:E()}),x({type:W("file_citation"),file_id:E(),filename:E().nullish(),index:Z().nullish(),start_index:Z().nullish(),end_index:Z().nullish(),quote:E().nullish()})])}),x({type:W("response.reasoning_summary_part.added"),item_id:E(),summary_index:Z()}),x({type:W("response.reasoning_summary_text.delta"),item_id:E(),summary_index:Z(),delta:E()}),x({type:W("response.reasoning_summary_part.done"),item_id:E(),summary_index:Z()}),x({type:W("error"),code:E(),message:E(),param:E().nullish(),sequence_number:Z()}),x({type:E()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),fD=_t(()=>De(x({id:E(),created_at:Z(),error:x({code:E(),message:E()}).nullish(),model:E(),output:oe(ar("type",[x({type:W("message"),role:W("assistant"),id:E(),content:oe(x({type:W("output_text"),text:E(),logprobs:oe(x({token:E(),logprob:Z(),top_logprobs:oe(x({token:E(),logprob:Z()}))})).nullish(),annotations:oe(ar("type",[x({type:W("url_citation"),start_index:Z(),end_index:Z(),url:E(),title:E()}),x({type:W("file_citation"),file_id:E(),filename:E().nullish(),index:Z().nullish(),start_index:Z().nullish(),end_index:Z().nullish(),quote:E().nullish()}),x({type:W("container_file_citation")})]))}))}),x({type:W("web_search_call"),id:E(),status:E(),action:ar("type",[x({type:W("search"),query:E().nullish()}),x({type:W("open_page"),url:E()}),x({type:W("find"),url:E(),pattern:E()})])}),x({type:W("file_search_call"),id:E(),queries:oe(E()),results:oe(x({attributes:kt(E(),jr()),file_id:E(),filename:E(),score:Z(),text:E()})).nullish()}),x({type:W("code_interpreter_call"),id:E(),code:E().nullable(),container_id:E(),outputs:oe(ar("type",[x({type:W("logs"),logs:E()}),x({type:W("image"),url:E()})])).nullable()}),x({type:W("image_generation_call"),id:E(),result:E()}),x({type:W("local_shell_call"),id:E(),call_id:E(),action:x({type:W("exec"),command:oe(E()),timeout_ms:Z().optional(),user:E().optional(),working_directory:E().optional(),env:kt(E(),E()).optional()})}),x({type:W("function_call"),call_id:E(),name:E(),arguments:E(),id:E()}),x({type:W("computer_call"),id:E(),status:E().optional()}),x({type:W("reasoning"),id:E(),encrypted_content:E().nullish(),summary:oe(x({type:W("summary_text"),text:E()}))})])),service_tier:E().nullish(),incomplete_details:x({reason:E()}).nullish(),usage:x({input_tokens:Z(),input_tokens_details:x({cached_tokens:Z().nullish()}).nullish(),output_tokens:Z(),output_tokens_details:x({reasoning_tokens:Z().nullish()}).nullish()})}))),V0=20,hD=_t(()=>De(x({include:oe(ht(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:E().nullish(),logprobs:He([Pt(),Z().min(1).max(V0)]).optional(),maxToolCalls:Z().nullish(),metadata:wr().nullish(),parallelToolCalls:Pt().nullish(),previousResponseId:E().nullish(),promptCacheKey:E().nullish(),reasoningEffort:E().nullish(),reasoningSummary:E().nullish(),safetyIdentifier:E().nullish(),serviceTier:ht(["auto","flex","priority","default"]).nullish(),store:Pt().nullish(),strictJsonSchema:Pt().nullish(),textVerbosity:ht(["low","medium","high"]).nullish(),truncation:ht(["auto","disabled"]).nullish(),user:E().nullish()})));async function mD({tools:t,toolChoice:e,strictJsonSchema:r}){t=t!=null&&t.length?t:void 0;const a=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};const n=[];for(const o of t)switch(o.type){case"function":n.push({type:"function",name:o.name,description:o.description,parameters:o.inputSchema,strict:r});break;case"provider-defined":{switch(o.id){case"openai.file_search":{const i=await tn({value:o.args,schema:H9});n.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker,score_threshold:i.ranking.scoreThreshold}:void 0,filters:i.filters});break}case"openai.local_shell":{n.push({type:"local_shell"});break}case"openai.web_search_preview":{const i=await tn({value:o.args,schema:sD});n.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.web_search":{const i=await tn({value:o.args,schema:eD});n.push({type:"web_search",filters:i.filters!=null?{allowed_domains:i.filters.allowedDomains}:void 0,search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=await tn({value:o.args,schema:F9});n.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}case"openai.image_generation":{const i=await tn({value:o.args,schema:G9});n.push({type:"image_generation",background:i.background,input_fidelity:i.inputFidelity,input_image_mask:i.inputImageMask?{file_id:i.inputImageMask.fileId,image_url:i.inputImageMask.imageUrl}:void 0,model:i.model,size:i.size,quality:i.quality,moderation:i.moderation,output_format:i.outputFormat,output_compression:i.outputCompression});break}}break}default:a.push({type:"unsupported-tool",tool:o});break}if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:a};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:a};case"tool":return{tools:n,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="image_generation"||e.toolName==="web_search_preview"||e.toolName==="web_search"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:a};default:{const o=s;throw new Mr({functionality:`tool choice type: ${o}`})}}}var vD=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:a,topK:n,presencePenalty:s,frequencyPenalty:o,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:f,responseFormat:g}){var d,h,v,m;const p=[],_=kD(this.modelId);n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),i!=null&&p.push({type:"unsupported-setting",setting:"seed"}),s!=null&&p.push({type:"unsupported-setting",setting:"presencePenalty"}),o!=null&&p.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&p.push({type:"unsupported-setting",setting:"stopSequences"});const w=await rn({provider:"openai",providerOptions:c,schema:hD}),{input:b,warnings:S}=await uD({prompt:l,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:(d=w==null?void 0:w.store)!=null?d:!0,hasLocalShellTool:O("openai.local_shell")});p.push(...S);const I=(h=w==null?void 0:w.strictJsonSchema)!=null?h:!1;let k=w==null?void 0:w.include;function A(ne){k==null?k=[ne]:k.includes(ne)||(k=[...k,ne])}function O(ne){return(u==null?void 0:u.find(ce=>ce.type==="provider-defined"&&ce.id===ne))!=null}const H=typeof(w==null?void 0:w.logprobs)=="number"?w==null?void 0:w.logprobs:(w==null?void 0:w.logprobs)===!0?V0:void 0;H&&A("message.output_text.logprobs");const J=(v=u==null?void 0:u.find(ne=>ne.type==="provider-defined"&&(ne.id==="openai.web_search"||ne.id==="openai.web_search_preview")))==null?void 0:v.name;J&&A("web_search_call.action.sources"),O("openai.code_interpreter")&&A("code_interpreter_call.outputs");const K=w==null?void 0:w.store;K===!1&&_.isReasoningModel&&A("reasoning.encrypted_content");const z={model:this.modelId,input:b,temperature:e,top_p:a,max_output_tokens:t,...((g==null?void 0:g.type)==="json"||(w==null?void 0:w.textVerbosity))&&{text:{...(g==null?void 0:g.type)==="json"&&{format:g.schema!=null?{type:"json_schema",strict:I,name:(m=g.name)!=null?m:"response",description:g.description,schema:g.schema}:{type:"json_object"}},...(w==null?void 0:w.textVerbosity)&&{verbosity:w.textVerbosity}}},max_tool_calls:w==null?void 0:w.maxToolCalls,metadata:w==null?void 0:w.metadata,parallel_tool_calls:w==null?void 0:w.parallelToolCalls,previous_response_id:w==null?void 0:w.previousResponseId,store:K,user:w==null?void 0:w.user,instructions:w==null?void 0:w.instructions,service_tier:w==null?void 0:w.serviceTier,include:k,prompt_cache_key:w==null?void 0:w.promptCacheKey,safety_identifier:w==null?void 0:w.safetyIdentifier,top_logprobs:H,truncation:w==null?void 0:w.truncation,..._.isReasoningModel&&((w==null?void 0:w.reasoningEffort)!=null||(w==null?void 0:w.reasoningSummary)!=null)&&{reasoning:{...(w==null?void 0:w.reasoningEffort)!=null&&{effort:w.reasoningEffort},...(w==null?void 0:w.reasoningSummary)!=null&&{summary:w.reasoningSummary}}}};_.isReasoningModel?(z.temperature!=null&&(z.temperature=void 0,p.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),z.top_p!=null&&(z.top_p=void 0,p.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((w==null?void 0:w.reasoningEffort)!=null&&p.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(w==null?void 0:w.reasoningSummary)!=null&&p.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(w==null?void 0:w.serviceTier)==="flex"&&!_.supportsFlexProcessing&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete z.service_tier),(w==null?void 0:w.serviceTier)==="priority"&&!_.supportsPriorityProcessing&&(p.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete z.service_tier);const{tools:U,toolChoice:G,toolWarnings:se}=await mD({tools:u,toolChoice:f,strictJsonSchema:I});return{webSearchToolName:J,args:{...z,tools:U,tool_choice:G},warnings:[...p,...se],store:K}}async doGenerate(t){var e,r,a,n,s,o,i,l,c,u,f,g,d,h,v,m,p,_,w;const{args:b,warnings:S,webSearchToolName:I}=await this.getArgs(t),k=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:A,value:O,rawValue:H}=await or({url:k,headers:Kt(this.config.headers(),t.headers),body:b,failedResponseHandler:on,successfulResponseHandler:Lr(fD),abortSignal:t.abortSignal,fetch:this.config.fetch});if(O.error)throw new Nt({message:O.error.message,url:k,requestBodyValues:b,statusCode:400,responseHeaders:A,responseBody:H,isRetryable:!1});const J=[],K=[];let z=!1;for(const G of O.output)switch(G.type){case"reasoning":{G.summary.length===0&&G.summary.push({type:"summary_text",text:""});for(const se of G.summary)J.push({type:"reasoning",text:se.text,providerMetadata:{openai:{itemId:G.id,reasoningEncryptedContent:(e=G.encrypted_content)!=null?e:null}}});break}case"image_generation_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:"image_generation",input:"{}",providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:"image_generation",result:{result:G.result},providerExecuted:!0});break}case"local_shell_call":{J.push({type:"tool-call",toolCallId:G.call_id,toolName:"local_shell",input:JSON.stringify({action:G.action}),providerMetadata:{openai:{itemId:G.id}}});break}case"message":{for(const se of G.content){(a=(r=t.providerOptions)==null?void 0:r.openai)!=null&&a.logprobs&&se.logprobs&&K.push(se.logprobs),J.push({type:"text",text:se.text,providerMetadata:{openai:{itemId:G.id}}});for(const ne of se.annotations)ne.type==="url_citation"?J.push({type:"source",sourceType:"url",id:(o=(s=(n=this.config).generateId)==null?void 0:s.call(n))!=null?o:sr(),url:ne.url,title:ne.title}):ne.type==="file_citation"&&J.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:sr(),mediaType:"text/plain",title:(f=(u=ne.quote)!=null?u:ne.filename)!=null?f:"Document",filename:(g=ne.filename)!=null?g:ne.file_id})}break}case"function_call":{z=!0,J.push({type:"tool-call",toolCallId:G.call_id,toolName:G.name,input:G.arguments,providerMetadata:{openai:{itemId:G.id}}});break}case"web_search_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:I??"web_search",input:JSON.stringify({}),providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:I??"web_search",result:B0(G.action),providerExecuted:!0});break}case"computer_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:"computer_use",input:"",providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:G.status||"completed"},providerExecuted:!0});break}case"file_search_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:"file_search",input:"{}",providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:"file_search",result:{queries:G.queries,results:(h=(d=G.results)==null?void 0:d.map(se=>({attributes:se.attributes,fileId:se.file_id,filename:se.filename,score:se.score,text:se.text})))!=null?h:null},providerExecuted:!0});break}case"code_interpreter_call":{J.push({type:"tool-call",toolCallId:G.id,toolName:"code_interpreter",input:JSON.stringify({code:G.code,containerId:G.container_id}),providerExecuted:!0}),J.push({type:"tool-result",toolCallId:G.id,toolName:"code_interpreter",result:{outputs:G.outputs},providerExecuted:!0});break}}const U={openai:{responseId:O.id}};return K.length>0&&(U.openai.logprobs=K),typeof O.service_tier=="string"&&(U.openai.serviceTier=O.service_tier),{content:J,finishReason:Z0({finishReason:(v=O.incomplete_details)==null?void 0:v.reason,hasFunctionCall:z}),usage:{inputTokens:O.usage.input_tokens,outputTokens:O.usage.output_tokens,totalTokens:O.usage.input_tokens+O.usage.output_tokens,reasoningTokens:(p=(m=O.usage.output_tokens_details)==null?void 0:m.reasoning_tokens)!=null?p:void 0,cachedInputTokens:(w=(_=O.usage.input_tokens_details)==null?void 0:_.cached_tokens)!=null?w:void 0},request:{body:b},response:{id:O.id,timestamp:new Date(O.created_at*1e3),modelId:O.model,headers:A,body:H},providerMetadata:U,warnings:S}}async doStream(t){const{args:e,warnings:r,webSearchToolName:a,store:n}=await this.getArgs(t),{responseHeaders:s,value:o}=await or({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:Kt(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:on,successfulResponseHandler:uo(pD),abortSignal:t.abortSignal,fetch:this.config.fetch}),i=this;let l="unknown";const c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},u=[];let f=null;const g={};let d=!1;const h={};let v;return{stream:o.pipeThrough(new TransformStream({start(m){m.enqueue({type:"stream-start",warnings:r})},transform(m,p){var _,w,b,S,I,k,A,O,H,J,K,z,U,G,se,ne,ce,pe,M,R,D,N;if(t.includeRawChunks&&p.enqueue({type:"raw",rawValue:m.rawValue}),!m.success){l="error",p.enqueue({type:"error",error:m.error});return}const y=m.value;if(H0(y))y.item.type==="function_call"?(g[y.output_index]={toolName:y.item.name,toolCallId:y.item.call_id},p.enqueue({type:"tool-input-start",id:y.item.call_id,toolName:y.item.name})):y.item.type==="web_search_call"?(g[y.output_index]={toolName:a??"web_search",toolCallId:y.item.id},p.enqueue({type:"tool-input-start",id:y.item.id,toolName:a??"web_search",providerExecuted:!0}),p.enqueue({type:"tool-input-end",id:y.item.id}),p.enqueue({type:"tool-call",toolCallId:y.item.id,toolName:"web_search",input:JSON.stringify({}),providerExecuted:!0})):y.item.type==="computer_call"?(g[y.output_index]={toolName:"computer_use",toolCallId:y.item.id},p.enqueue({type:"tool-input-start",id:y.item.id,toolName:"computer_use",providerExecuted:!0})):y.item.type==="code_interpreter_call"?(g[y.output_index]={toolName:"code_interpreter",toolCallId:y.item.id,codeInterpreter:{containerId:y.item.container_id}},p.enqueue({type:"tool-input-start",id:y.item.id,toolName:"code_interpreter",providerExecuted:!0}),p.enqueue({type:"tool-input-delta",id:y.item.id,delta:`{"containerId":"${y.item.container_id}","code":"`})):y.item.type==="file_search_call"?p.enqueue({type:"tool-call",toolCallId:y.item.id,toolName:"file_search",input:"{}",providerExecuted:!0}):y.item.type==="image_generation_call"?p.enqueue({type:"tool-call",toolCallId:y.item.id,toolName:"image_generation",input:"{}",providerExecuted:!0}):y.item.type==="message"?p.enqueue({type:"text-start",id:y.item.id,providerMetadata:{openai:{itemId:y.item.id}}}):H0(y)&&y.item.type==="reasoning"&&(h[y.item.id]={encryptedContent:y.item.encrypted_content,summaryParts:{0:"active"}},p.enqueue({type:"reasoning-start",id:`${y.item.id}:0`,providerMetadata:{openai:{itemId:y.item.id,reasoningEncryptedContent:(_=y.item.encrypted_content)!=null?_:null}}}));else if(yD(y)){if(y.item.type==="function_call")g[y.output_index]=void 0,d=!0,p.enqueue({type:"tool-input-end",id:y.item.call_id}),p.enqueue({type:"tool-call",toolCallId:y.item.call_id,toolName:y.item.name,input:y.item.arguments,providerMetadata:{openai:{itemId:y.item.id}}});else if(y.item.type==="web_search_call")g[y.output_index]=void 0,p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"web_search",result:B0(y.item.action),providerExecuted:!0});else if(y.item.type==="computer_call")g[y.output_index]=void 0,p.enqueue({type:"tool-input-end",id:y.item.id}),p.enqueue({type:"tool-call",toolCallId:y.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:y.item.status||"completed"},providerExecuted:!0});else if(y.item.type==="file_search_call")g[y.output_index]=void 0,p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"file_search",result:{queries:y.item.queries,results:(b=(w=y.item.results)==null?void 0:w.map(P=>({attributes:P.attributes,fileId:P.file_id,filename:P.filename,score:P.score,text:P.text})))!=null?b:null},providerExecuted:!0});else if(y.item.type==="code_interpreter_call")g[y.output_index]=void 0,p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"code_interpreter",result:{outputs:y.item.outputs},providerExecuted:!0});else if(y.item.type==="image_generation_call")p.enqueue({type:"tool-result",toolCallId:y.item.id,toolName:"image_generation",result:{result:y.item.result},providerExecuted:!0});else if(y.item.type==="local_shell_call")g[y.output_index]=void 0,p.enqueue({type:"tool-call",toolCallId:y.item.call_id,toolName:"local_shell",input:JSON.stringify({action:{type:"exec",command:y.item.action.command,timeoutMs:y.item.action.timeout_ms,user:y.item.action.user,workingDirectory:y.item.action.working_directory,env:y.item.action.env}}),providerMetadata:{openai:{itemId:y.item.id}}});else if(y.item.type==="message")p.enqueue({type:"text-end",id:y.item.id});else if(y.item.type==="reasoning"){const P=h[y.item.id],j=Object.entries(P.summaryParts).filter(([Q,ee])=>ee==="active"||ee==="can-conclude").map(([Q])=>Q);for(const Q of j)p.enqueue({type:"reasoning-end",id:`${y.item.id}:${Q}`,providerMetadata:{openai:{itemId:y.item.id,reasoningEncryptedContent:(S=y.item.encrypted_content)!=null?S:null}}});delete h[y.item.id]}}else if(bD(y)){const P=g[y.output_index];P!=null&&p.enqueue({type:"tool-input-delta",id:P.toolCallId,delta:y.delta})}else if(ED(y)){const P=g[y.output_index];P!=null&&p.enqueue({type:"tool-input-delta",id:P.toolCallId,delta:JSON.stringify(y.delta).slice(1,-1)})}else if(SD(y)){const P=g[y.output_index];P!=null&&(p.enqueue({type:"tool-input-delta",id:P.toolCallId,delta:'"}'}),p.enqueue({type:"tool-input-end",id:P.toolCallId}),p.enqueue({type:"tool-call",toolCallId:P.toolCallId,toolName:"code_interpreter",input:JSON.stringify({code:y.code,containerId:P.codeInterpreter.containerId}),providerExecuted:!0}))}else if(wD(y))f=y.response.id,p.enqueue({type:"response-metadata",id:y.response.id,timestamp:new Date(y.response.created_at*1e3),modelId:y.response.model});else if(gD(y))p.enqueue({type:"text-delta",id:y.item_id,delta:y.delta}),(k=(I=t.providerOptions)==null?void 0:I.openai)!=null&&k.logprobs&&y.logprobs&&u.push(y.logprobs);else if(y.type==="response.reasoning_summary_part.added"){if(y.summary_index>0){const P=h[y.item_id];P.summaryParts[y.summary_index]="active";for(const j of Object.keys(P.summaryParts))P.summaryParts[j]==="can-conclude"&&(p.enqueue({type:"reasoning-end",id:`${y.item_id}:${j}`,providerMetadata:{openai:{itemId:y.item_id}}}),P.summaryParts[j]="concluded");p.enqueue({type:"reasoning-start",id:`${y.item_id}:${y.summary_index}`,providerMetadata:{openai:{itemId:y.item_id,reasoningEncryptedContent:(O=(A=h[y.item_id])==null?void 0:A.encryptedContent)!=null?O:null}}})}}else y.type==="response.reasoning_summary_text.delta"?p.enqueue({type:"reasoning-delta",id:`${y.item_id}:${y.summary_index}`,delta:y.delta,providerMetadata:{openai:{itemId:y.item_id}}}):y.type==="response.reasoning_summary_part.done"?n?(p.enqueue({type:"reasoning-end",id:`${y.item_id}:${y.summary_index}`,providerMetadata:{openai:{itemId:y.item_id}}}),h[y.item_id].summaryParts[y.summary_index]="concluded"):h[y.item_id].summaryParts[y.summary_index]="can-conclude":_D(y)?(l=Z0({finishReason:(H=y.response.incomplete_details)==null?void 0:H.reason,hasFunctionCall:d}),c.inputTokens=y.response.usage.input_tokens,c.outputTokens=y.response.usage.output_tokens,c.totalTokens=y.response.usage.input_tokens+y.response.usage.output_tokens,c.reasoningTokens=(K=(J=y.response.usage.output_tokens_details)==null?void 0:J.reasoning_tokens)!=null?K:void 0,c.cachedInputTokens=(U=(z=y.response.usage.input_tokens_details)==null?void 0:z.cached_tokens)!=null?U:void 0,typeof y.response.service_tier=="string"&&(v=y.response.service_tier)):$D(y)?y.annotation.type==="url_citation"?p.enqueue({type:"source",sourceType:"url",id:(ne=(se=(G=i.config).generateId)==null?void 0:se.call(G))!=null?ne:sr(),url:y.annotation.url,title:y.annotation.title}):y.annotation.type==="file_citation"&&p.enqueue({type:"source",sourceType:"document",id:(M=(pe=(ce=i.config).generateId)==null?void 0:pe.call(ce))!=null?M:sr(),mediaType:"text/plain",title:(D=(R=y.annotation.quote)!=null?R:y.annotation.filename)!=null?D:"Document",filename:(N=y.annotation.filename)!=null?N:y.annotation.file_id}):PD(y)&&p.enqueue({type:"error",error:y})},flush(m){const p={openai:{responseId:f}};u.length>0&&(p.openai.logprobs=u),v!==void 0&&(p.openai.serviceTier=v),m.enqueue({type:"finish",finishReason:l,usage:c,providerMetadata:p})}})),request:{body:e},response:{headers:s}}}};function gD(t){return t.type==="response.output_text.delta"}function yD(t){return t.type==="response.output_item.done"}function _D(t){return t.type==="response.completed"||t.type==="response.incomplete"}function wD(t){return t.type==="response.created"}function bD(t){return t.type==="response.function_call_arguments.delta"}function ED(t){return t.type==="response.code_interpreter_call_code.delta"}function SD(t){return t.type==="response.code_interpreter_call_code.done"}function H0(t){return t.type==="response.output_item.added"}function $D(t){return t.type==="response.output_text.annotation.added"}function PD(t){return t.type==="error"}function kD(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),a={systemMessageMode:"system",supportsFlexProcessing:e,supportsPriorityProcessing:r};return t.startsWith("gpt-5-chat")?{...a,isReasoningModel:!1}:t.startsWith("o")||t.startsWith("gpt-5")||t.startsWith("codex-")||t.startsWith("computer-use")?t.startsWith("o1-mini")||t.startsWith("o1-preview")?{...a,isReasoningModel:!0,systemMessageMode:"remove"}:{...a,isReasoningModel:!0,systemMessageMode:"developer"}:{...a,isReasoningModel:!1}}function B0(t){var e;switch(t.type){case"search":return{action:{type:"search",query:(e=t.query)!=null?e:void 0}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find":return{action:{type:"find",url:t.url,pattern:t.pattern}}}}var ID=_t(()=>De(x({instructions:E().nullish(),speed:Z().min(.25).max(4).default(1).nullish()}))),xD=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:a,instructions:n,language:s,providerOptions:o}){const i=[],l=await rn({provider:"openai",providerOptions:o,schema:ID}),c={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:a,instructions:n};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const f in u){const g=u[f];g!==void 0&&(c[f]=g)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(t){var e,r,a;const n=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{requestBody:s,warnings:o}=await this.getArgs(t),{value:i,responseHeaders:l,rawValue:c}=await or({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:Kt(this.config.headers(),t.headers),body:s,failedResponseHandler:on,successfulResponseHandler:AN(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:o,request:{body:JSON.stringify(s)},response:{timestamp:n,modelId:this.modelId,headers:l,body:c}}}},TD=_t(()=>De(x({text:E(),language:E().nullish(),duration:Z().nullish(),words:oe(x({word:E(),start:Z(),end:Z()})).nullish(),segments:oe(x({id:Z(),seek:Z(),start:Z(),end:Z(),text:E(),tokens:oe(Z()),temperature:Z(),avg_logprob:Z(),compression_ratio:Z(),no_speech_prob:Z()})).nullish()}))),CD=_t(()=>De(x({include:oe(E()).optional(),language:E().optional(),prompt:E().optional(),temperature:Z().min(0).max(1).default(0).optional(),timestampGranularities:oe(ht(["word","segment"])).default(["segment"]).optional()}))),J0={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"},RD=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const a=[],n=await rn({provider:"openai",providerOptions:r,schema:CD}),s=new FormData,o=t instanceof Uint8Array?new Blob([t]):new Blob([yl(t)]);s.append("model",this.modelId);const i=bN(e);if(s.append("file",new File([o],"audio",{type:e}),`audio.${i}`),n){const l={include:n.include,language:n.language,prompt:n.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:n.temperature,timestamp_granularities:n.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:a}}async doGenerate(t){var e,r,a,n,s,o,i,l;const c=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{formData:u,warnings:f}=await this.getArgs(t),{value:g,responseHeaders:d,rawValue:h}=await NN({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:Kt(this.config.headers(),t.headers),formData:u,failedResponseHandler:on,successfulResponseHandler:Lr(TD),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=g.language!=null&&g.language in J0?J0[g.language]:void 0;return{text:g.text,segments:(i=(o=(n=g.segments)==null?void 0:n.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?o:(s=g.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:v,durationInSeconds:(l=g.duration)!=null?l:void 0,warnings:f,response:{timestamp:c,modelId:this.modelId,headers:d,body:h}}}},OD="2.0.53";function G0(t={}){var e,r;const a=(e=Bd(co({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?e:"https://api.openai.com/v1",n=(r=t.name)!=null?r:"openai",s=()=>wn({Authorization:`Bearer ${vy({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${OD}`),o=v=>new $9(v,{provider:`${n}.chat`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),i=v=>new O9(v,{provider:`${n}.completion`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),l=v=>new M9(v,{provider:`${n}.embedding`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),c=v=>new z9(v,{provider:`${n}.image`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),u=v=>new RD(v,{provider:`${n}.transcription`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),f=v=>new xD(v,{provider:`${n}.speech`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),g=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(v)},d=v=>new vD(v,{provider:`${n}.responses`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch,fileIdPrefixes:["file-"]}),h=function(v){return g(v)};return h.languageModel=g,h.chat=o,h.completion=i,h.responses=d,h.embedding=l,h.textEmbedding=l,h.textEmbeddingModel=l,h.image=c,h.imageModel=c,h.transcription=u,h.transcriptionModel=u,h.speech=f,h.speechModel=f,h.tools=cD,h}G0();function So(t){var e,r;return(r=(e=t==null?void 0:t.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function ND(t){const e=[];for(const{role:r,content:a,...n}of t){const s=So({...n});switch(r){case"system":{e.push({role:"system",content:a,...s});break}case"user":{if(a.length===1&&a[0].type==="text"){e.push({role:"user",content:a[0].text,...So(a[0])});break}e.push({role:"user",content:a.map(o=>{const i=So(o);switch(o.type){case"text":return{type:"text",text:o.text,...i};case"file":if(o.mediaType.startsWith("image/")){const l=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${l};base64,${la(o.data)}`},...i}}else throw new Mr({functionality:`file part media type ${o.mediaType}`})}}),...s});break}case"assistant":{let o="";const i=[];for(const l of a){const c=So(l);switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}e.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const o of a){const i=o.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=So(o);e.push({role:"tool",tool_call_id:o.toolCallId,content:l,...c})}break}default:{const o=r;throw new Error(`Unsupported role: ${o}`)}}}return e}function K0({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function W0(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var _p=x({user:E().optional(),reasoningEffort:E().optional(),textVerbosity:E().optional()}),AD=x({error:x({message:E(),type:E().nullish(),param:wr().nullish(),code:He([E(),Z()]).nullish()})}),MD={errorSchema:AD,errorToMessage:t=>t.error.message};function jD({tools:t,toolChoice:e}){t=t!=null&&t.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const a=[];for(const s of t)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):a.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(e==null)return{tools:a,toolChoice:void 0,toolWarnings:r};const n=e.type;switch(n){case"auto":case"none":case"required":return{tools:a,toolChoice:n,toolWarnings:r};case"tool":return{tools:a,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const s=n;throw new Mr({functionality:`tool choice type: ${s}`})}}}var DD=class{constructor(t,e){this.specificationVersion="v2";var r,a;this.modelId=t,this.config=e;const n=(r=e.errorStructure)!=null?r:MD;this.chunkSchema=zD(n.errorSchema),this.failedResponseHandler=ia(n),this.supportsStructuredOutputs=(a=e.supportsStructuredOutputs)!=null?a:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:f,tools:g}){var d,h,v,m;const p=[],_=Object.assign((d=await rn({provider:"openai-compatible",providerOptions:i,schema:_p}))!=null?d:{},(h=await rn({provider:this.providerOptionsName,providerOptions:i,schema:_p}))!=null?h:{});n!=null&&p.push({type:"unsupported-setting",setting:"topK"}),(c==null?void 0:c.type)==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&p.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:w,toolChoice:b,toolWarnings:S}=jD({tools:g,toolChoice:f});return{args:{model:this.modelId,user:_.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(c==null?void 0:c.type)==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(v=c.name)!=null?v:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...Object.fromEntries(Object.entries((m=i==null?void 0:i[this.providerOptionsName])!=null?m:{}).filter(([I])=>!Object.keys(_p.shape).includes(I))),reasoning_effort:_.reasoningEffort,verbosity:_.textVerbosity,messages:ND(t),tools:w,tool_choice:b},warnings:[...p,...S]}}async doGenerate(t){var e,r,a,n,s,o,i,l,c,u,f,g,d,h,v,m,p;const{args:_,warnings:w}=await this.getArgs({...t}),b=JSON.stringify(_),{responseHeaders:S,value:I,rawValue:k}=await or({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Kt(this.config.headers(),t.headers),body:_,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Lr(LD),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=I.choices[0],O=[],H=A.message.content;H!=null&&H.length>0&&O.push({type:"text",text:H});const J=(e=A.message.reasoning_content)!=null?e:A.message.reasoning;if(J!=null&&J.length>0&&O.push({type:"reasoning",text:J}),A.message.tool_calls!=null)for(const U of A.message.tool_calls)O.push({type:"tool-call",toolCallId:(r=U.id)!=null?r:sr(),toolName:U.function.name,input:U.function.arguments});const K={[this.providerOptionsName]:{},...await((n=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:n.call(a,{parsedBody:k}))},z=(s=I.usage)==null?void 0:s.completion_tokens_details;return(z==null?void 0:z.accepted_prediction_tokens)!=null&&(K[this.providerOptionsName].acceptedPredictionTokens=z==null?void 0:z.accepted_prediction_tokens),(z==null?void 0:z.rejected_prediction_tokens)!=null&&(K[this.providerOptionsName].rejectedPredictionTokens=z==null?void 0:z.rejected_prediction_tokens),{content:O,finishReason:W0(A.finish_reason),usage:{inputTokens:(i=(o=I.usage)==null?void 0:o.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=I.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(f=(u=I.usage)==null?void 0:u.total_tokens)!=null?f:void 0,reasoningTokens:(h=(d=(g=I.usage)==null?void 0:g.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?h:void 0,cachedInputTokens:(p=(m=(v=I.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?p:void 0},providerMetadata:K,request:{body:b},response:{...K0(I),headers:S,body:k},warnings:w}}async doStream(t){var e;const{args:r,warnings:a}=await this.getArgs({...t}),n={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:o,value:i}=await or({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Kt(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:uo(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let f=!0;const g=this.providerOptionsName;let d=!1,h=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:a})},transform(v,m){var p,_,w,b,S,I,k,A,O,H,J,K,z;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",m.enqueue({type:"error",error:v.error});return}const U=v.value;if(s==null||s.processChunk(v.rawValue),"error"in U){c="error",m.enqueue({type:"error",error:U.error.message});return}if(f&&(f=!1,m.enqueue({type:"response-metadata",...K0(U)})),U.usage!=null){const{prompt_tokens:ce,completion_tokens:pe,total_tokens:M,prompt_tokens_details:R,completion_tokens_details:D}=U.usage;u.promptTokens=ce??void 0,u.completionTokens=pe??void 0,u.totalTokens=M??void 0,(D==null?void 0:D.reasoning_tokens)!=null&&(u.completionTokensDetails.reasoningTokens=D==null?void 0:D.reasoning_tokens),(D==null?void 0:D.accepted_prediction_tokens)!=null&&(u.completionTokensDetails.acceptedPredictionTokens=D==null?void 0:D.accepted_prediction_tokens),(D==null?void 0:D.rejected_prediction_tokens)!=null&&(u.completionTokensDetails.rejectedPredictionTokens=D==null?void 0:D.rejected_prediction_tokens),(R==null?void 0:R.cached_tokens)!=null&&(u.promptTokensDetails.cachedTokens=R==null?void 0:R.cached_tokens)}const G=U.choices[0];if((G==null?void 0:G.finish_reason)!=null&&(c=W0(G.finish_reason)),(G==null?void 0:G.delta)==null)return;const se=G.delta,ne=(p=se.reasoning_content)!=null?p:se.reasoning;if(ne&&(d||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ne})),se.content&&(h||(m.enqueue({type:"text-start",id:"txt-0"}),h=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:se.content})),se.tool_calls!=null)for(const ce of se.tool_calls){const pe=ce.index;if(l[pe]==null){if(ce.id==null)throw new Ys({data:ce,message:"Expected 'id' to be a string."});if(((_=ce.function)==null?void 0:_.name)==null)throw new Ys({data:ce,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:ce.id,toolName:ce.function.name}),l[pe]={id:ce.id,type:"function",function:{name:ce.function.name,arguments:(w=ce.function.arguments)!=null?w:""},hasFinished:!1};const R=l[pe];((b=R.function)==null?void 0:b.name)!=null&&((S=R.function)==null?void 0:S.arguments)!=null&&(R.function.arguments.length>0&&m.enqueue({type:"tool-input-delta",id:R.id,delta:R.function.arguments}),vl(R.function.arguments)&&(m.enqueue({type:"tool-input-end",id:R.id}),m.enqueue({type:"tool-call",toolCallId:(I=R.id)!=null?I:sr(),toolName:R.function.name,input:R.function.arguments}),R.hasFinished=!0));continue}const M=l[pe];M.hasFinished||(((k=ce.function)==null?void 0:k.arguments)!=null&&(M.function.arguments+=(O=(A=ce.function)==null?void 0:A.arguments)!=null?O:""),m.enqueue({type:"tool-input-delta",id:M.id,delta:(H=ce.function.arguments)!=null?H:""}),((J=M.function)==null?void 0:J.name)!=null&&((K=M.function)==null?void 0:K.arguments)!=null&&vl(M.function.arguments)&&(m.enqueue({type:"tool-input-end",id:M.id}),m.enqueue({type:"tool-call",toolCallId:(z=M.id)!=null?z:sr(),toolName:M.function.name,input:M.function.arguments}),M.hasFinished=!0))}},flush(v){var m,p,_,w,b,S;d&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),h&&v.enqueue({type:"text-end",id:"txt-0"});for(const k of l.filter(A=>!A.hasFinished))v.enqueue({type:"tool-input-end",id:k.id}),v.enqueue({type:"tool-call",toolCallId:(m=k.id)!=null?m:sr(),toolName:k.function.name,input:k.function.arguments});const I={[g]:{},...s==null?void 0:s.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(I[g].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(I[g].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(p=u.promptTokens)!=null?p:void 0,outputTokens:(_=u.completionTokens)!=null?_:void 0,totalTokens:(w=u.totalTokens)!=null?w:void 0,reasoningTokens:(b=u.completionTokensDetails.reasoningTokens)!=null?b:void 0,cachedInputTokens:(S=u.promptTokensDetails.cachedTokens)!=null?S:void 0},providerMetadata:I})}})),request:{body:n},response:{headers:o}}}},Q0=x({prompt_tokens:Z().nullish(),completion_tokens:Z().nullish(),total_tokens:Z().nullish(),prompt_tokens_details:x({cached_tokens:Z().nullish()}).nullish(),completion_tokens_details:x({reasoning_tokens:Z().nullish(),accepted_prediction_tokens:Z().nullish(),rejected_prediction_tokens:Z().nullish()}).nullish()}).nullish(),LD=x({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(x({message:x({role:W("assistant").nullish(),content:E().nullish(),reasoning_content:E().nullish(),reasoning:E().nullish(),tool_calls:oe(x({id:E().nullish(),function:x({name:E(),arguments:E()})})).nullish()}),finish_reason:E().nullish()})),usage:Q0}),zD=t=>He([x({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(x({delta:x({role:ht(["assistant"]).nullish(),content:E().nullish(),reasoning_content:E().nullish(),reasoning:E().nullish(),tool_calls:oe(x({index:Z(),id:E().nullish(),function:x({name:E().nullish(),arguments:E().nullish()})})).nullish()}).nullish(),finish_reason:E().nullish()})),usage:Q0}),t]);x({echo:Pt().optional(),logitBias:kt(E(),Z()).optional(),suffix:E().optional(),user:E().optional()});var UD=x({prompt_tokens:Z(),completion_tokens:Z(),total_tokens:Z()});x({id:E().nullish(),created:Z().nullish(),model:E().nullish(),choices:oe(x({text:E(),finish_reason:E()})),usage:UD.nullish()}),x({dimensions:Z().optional(),user:E().optional()}),x({data:oe(x({embedding:oe(Z())})),usage:x({prompt_tokens:Z()}).nullish(),providerMetadata:kt(E(),kt(E(),wr())).optional()}),x({data:oe(x({b64_json:E()}))});var Y0=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},qD={extractMetadata:async({parsedBody:t})=>{const e=await Dr({value:t,schema:FD});return!e.success||e.value.usage==null?void 0:Y0(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,a;const n=await Dr({value:e,schema:ZD});n.success&&((a=(r=n.value.choices)==null?void 0:r[0])==null?void 0:a.finish_reason)==="stop"&&n.value.usage&&(t=n.value.usage)},buildMetadata:()=>Y0(t)}}},X0=x({prompt_cache_hit_tokens:Z().nullish(),prompt_cache_miss_tokens:Z().nullish()}),FD=x({usage:X0.nullish()}),ZD=x({choices:oe(x({finish_reason:E().nullish()})).nullish(),usage:X0.nullish()}),VD="1.0.23";function ew(t={}){var e;const r=Bd((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),a=()=>wn({Authorization:`Bearer ${vy({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${VD}`),n=o=>new DD(o,{provider:"deepseek.chat",url:({path:i})=>`${r}${i}`,headers:a,fetch:t.fetch,metadataExtractor:qD}),s=o=>n(o);return s.languageModel=n,s.chat=n,s.textEmbeddingModel=o=>{throw new xd({modelId:o,modelType:"textEmbeddingModel"})},s.imageModel=o=>{throw new xd({modelId:o,modelType:"imageModel"})},s}ew();const HD={openai:G0,deepseek:ew};class BD{constructor({llmConfig:e,mcpServers:r,llm:a}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},a)this.llm=a;else if(e){let n;typeof e.providerType=="string"?n=HD[e.providerType]:n=e.providerType,this.llm=n({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig or llm must be provided")}async _createOneClient(e){try{let r;"type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new Js(new URL(e.url)):"type"in e&&e.type==="extension"?r=new dv(e.sessionId):r=e;const a=await g9({transport:r});return a.__transport__=r,a}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){var r,a,n,s,o;try{await((a=(r=e.__transport__)==null?void 0:r.terminateSession)==null?void 0:a.call(r)),await((s=(n=e.__transport__)==null?void 0:n.close)==null?void 0:s.call(n)),await((o=e==null?void 0:e.close)==null?void 0:o.call(e))}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([a,n])=>{const s=await this._createOneClient(n);return{serverName:a,client:s}}));this.mcpClients={},r.forEach(({serverName:a,client:n})=>{this.mcpClients[a]=n})}async _createMpcTools(){const e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([a,n])=>{var s;try{const o=n?await((s=n==null?void 0:n.tools)==null?void 0:s.call(n)):null;return{serverName:a,tools:o}}catch(o){return this.onError&&this.onError((o==null?void 0:o.message)||"Failed to query tools",o),console.error("Failed to query tools",o),{serverName:a,tools:null}}}));this.mcpTools={},r.forEach(({serverName:a,tools:n})=>{this.mcpTools[a]=n})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}catch(r){this.onError&&this.onError((r==null?void 0:r.message)||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){var e;await this._createMpcClients(),await this._createMpcTools(),(e=this.onUpdatedTools)==null||e.call(this)}async updateMcpServers(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){var n,s;if(this.mcpServers[e])return!1;const a=await this._createOneClient(r);return this.mcpClients[e]=a,this.mcpTools[e]=await((n=a==null?void 0:a.tools)==null?void 0:n.call(a)),this.mcpServers[e]=r,(s=this.onUpdatedTools)==null||s.call(this),!0}async removeMcpServer(e){var n;if(!this.mcpServers[e])return;delete this.mcpServers[e];const r=this.mcpClients[e];delete this.mcpClients[e];try{await this._closeOneClient(r)}catch{}const a=this.mcpTools[e];delete this.mcpTools[e],a&&Object.keys(a).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),(n=this.onUpdatedTools)==null||n.call(this)}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((a,n)=>({...a,...n}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(a=>{delete r[a]}),r}async _chat(e,{model:r,maxSteps:a=5,...n}){var i;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:fp(a),...n,tools:this._tempMergeTools(n.tools)};n.message&&!n.messages&&(this.messages.push({role:"user",content:n.message}),s.messages=[...this.messages]);const o=e(s);return(i=o==null?void 0:o.response)==null||i.then(l=>{this.messages.push(...l.messages)}),o}async chat(e){return this._chat(Sj,e)}async chatStream(e){return this._chat(Fj,e)}}const JD=async t=>{const e={};try{const r=await t.listTools();for(const{name:a,description:n,inputSchema:s}of r.tools){const o=async(i,l)=>t.callTool({name:a,arguments:i},{signal:l==null?void 0:l.abortSignal});e[a]=yy({description:n,inputSchema:po({...s,properties:s.properties??{},additionalProperties:!1}),execute:o})}return e}catch(r){throw r}};Ve.AgentModelProvider=BD,Ve.Ajv=gS,Ve.AuthClientProvider=tx,Ve.ContentScriptServerTransport=iT,Ve.ExtensionClientTransport=dv,Ve.ExtensionPageServerTransport=oT,Ve.QrCode=Ov,Ve.ResourceTemplate=Zx,Ve.UriTemplate=_n,Ve.WebMcpClient=Xx,Ve.WebMcpServer=Gx,Ve.completable=Ux,Ve.createMessageChannelClientTransport=rT,Ve.createMessageChannelPairTransport=Wx,Ve.createMessageChannelServerTransport=Kx,Ve.createRemoter=QT,Ve.createSSEClientTransport=eT,Ve.createStreamableHTTPClientTransport=tT,Ve.getAISDKTools=JD,Ve.getDisplayName=Jx,Ve.isMcpClient=sT,Ve.isMcpServer=Yx,Ve.isMessageChannelClientTransport=aT,Ve.isMessageChannelServerTransport=Qx,Ve.isSSEClientTransport=nT,Ve.isStreamableHTTPClientTransport=cv,Ve.z=m$,Object.defineProperty(Ve,Symbol.toStringTag,{value:"Module"})});
535
+ ${e}:`]}}function V0({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function H0(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var B0=R({echo:$t().optional(),logitBias:Qt(S(),K()).optional(),suffix:S().optional(),user:S().optional(),logprobs:Ve([$t(),K()]).optional()}),Q9=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={},this.modelId=t,this.config=e}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,stopSequences:i,responseFormat:l,tools:c,toolChoice:u,seed:h,providerOptions:g}){const d=[],f={...await Wr({provider:"openai",providerOptions:g,schema:B0}),...await Wr({provider:this.providerOptionsName,providerOptions:g,schema:B0})};n!=null&&d.push({type:"unsupported-setting",setting:"topK"}),c!=null&&c.length&&d.push({type:"unsupported-setting",setting:"tools"}),u!=null&&d.push({type:"unsupported-setting",setting:"toolChoice"}),l!=null&&l.type!=="text"&&d.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});const{prompt:v,stopSequences:m}=W9({prompt:t}),p=[...m??[],...i??[]];return{args:{model:this.modelId,echo:f.echo,logit_bias:f.logitBias,logprobs:(f==null?void 0:f.logprobs)===!0?0:(f==null?void 0:f.logprobs)===!1||f==null?void 0:f.logprobs,suffix:f.suffix,user:f.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,seed:h,prompt:v,stop:p.length>0?p:void 0},warnings:d}}async doGenerate(t){var e,r,a;const{args:n,warnings:s}=await this.getArgs(t),{responseHeaders:o,value:i,rawValue:l}=await Rr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:n,failedResponseHandler:Qr,successfulResponseHandler:sa(Y9),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=i.choices[0],u={openai:{}};return c.logprobs!=null&&(u.openai.logprobs=c.logprobs),{content:[{type:"text",text:c.text}],usage:{inputTokens:(e=i.usage)==null?void 0:e.prompt_tokens,outputTokens:(r=i.usage)==null?void 0:r.completion_tokens,totalTokens:(a=i.usage)==null?void 0:a.total_tokens},finishReason:H0(c.finish_reason),request:{body:n},response:{...V0(i),headers:o,body:l},providerMetadata:u,warnings:s}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),a={...e,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:n,value:s}=await Rr({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:a,failedResponseHandler:Qr,successfulResponseHandler:_l(X9),abortSignal:t.abortSignal,fetch:this.config.fetch});let o="unknown";const i={openai:{}},l={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};let c=!0;return{stream:s.pipeThrough(new TransformStream({start(u){u.enqueue({type:"stream-start",warnings:r})},transform(u,h){if(t.includeRawChunks&&h.enqueue({type:"raw",rawValue:u.rawValue}),!u.success){o="error",h.enqueue({type:"error",error:u.error});return}const g=u.value;if("error"in g){o="error",h.enqueue({type:"error",error:g.error});return}c&&(c=!1,h.enqueue({type:"response-metadata",...V0(g)}),h.enqueue({type:"text-start",id:"0"})),g.usage!=null&&(l.inputTokens=g.usage.prompt_tokens,l.outputTokens=g.usage.completion_tokens,l.totalTokens=g.usage.total_tokens);const d=g.choices[0];(d==null?void 0:d.finish_reason)!=null&&(o=H0(d.finish_reason)),(d==null?void 0:d.logprobs)!=null&&(i.openai.logprobs=d.logprobs),(d==null?void 0:d.text)!=null&&d.text.length>0&&h.enqueue({type:"text-delta",id:"0",delta:d.text})},flush(u){c||u.enqueue({type:"text-end",id:"0"}),u.enqueue({type:"finish",finishReason:o,providerMetadata:i,usage:l})}})),request:{body:a},response:{headers:n}}}},J0=R({prompt_tokens:K(),completion_tokens:K(),total_tokens:K()}),Y9=R({id:S().nullish(),created:K().nullish(),model:S().nullish(),choices:ce(R({text:S(),finish_reason:S(),logprobs:R({tokens:ce(S()),token_logprobs:ce(K()),top_logprobs:ce(Qt(S(),K())).nullish()}).nullish()})),usage:J0.nullish()}),X9=Ve([R({id:S().nullish(),created:K().nullish(),model:S().nullish(),choices:ce(R({text:S(),finish_reason:S().nullish(),index:K(),logprobs:R({tokens:ce(S()),token_logprobs:ce(K()),top_logprobs:ce(Qt(S(),K())).nullish()}).nullish()})),usage:J0.nullish()}),_f]),eD=R({dimensions:K().optional(),user:S().optional()}),tD=class{constructor(t,e){this.specificationVersion="v2",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=e}get provider(){return this.config.provider}async doEmbed({values:t,headers:e,abortSignal:r,providerOptions:a}){var n;if(t.length>this.maxEmbeddingsPerCall)throw new hC({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const s=(n=await Wr({provider:"openai",providerOptions:a,schema:eD}))!=null?n:{},{responseHeaders:o,value:i,rawValue:l}=await Rr({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:mr(this.config.headers(),e),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:s.dimensions,user:s.user},failedResponseHandler:Qr,successfulResponseHandler:sa(rD),abortSignal:r,fetch:this.config.fetch});return{embeddings:i.data.map(c=>c.embedding),usage:i.usage?{tokens:i.usage.prompt_tokens}:void 0,response:{headers:o,body:l}}}},rD=R({data:ce(R({embedding:ce(K())})),usage:R({prompt_tokens:K()}).nullish()}),nD={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},aD=new Set(["gpt-image-1"]),sD=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get maxImagesPerCall(){var t;return(t=nD[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,n:e,size:r,aspectRatio:a,seed:n,providerOptions:s,headers:o,abortSignal:i}){var l,c,u,h;const g=[];a!=null&&g.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),n!=null&&g.push({type:"unsupported-setting",setting:"seed"});const d=(u=(c=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:c.call(l))!=null?u:new Date,{value:f,responseHeaders:v}=await Rr({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:mr(this.config.headers(),o),body:{model:this.modelId,prompt:t,n:e,size:r,...(h=s.openai)!=null?h:{},...aD.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Qr,successfulResponseHandler:sa(oD),abortSignal:i,fetch:this.config.fetch});return{images:f.data.map(m=>m.b64_json),warnings:g,response:{timestamp:d,modelId:this.modelId,headers:v},providerMetadata:{openai:{images:f.data.map(m=>m.revised_prompt?{revisedPrompt:m.revised_prompt}:null)}}}}},oD=R({data:ce(R({b64_json:S(),revised_prompt:S().optional()}))}),iD=R({container:Ve([S(),R({fileIds:ce(S()).optional()})]).optional()}),lD=yf({id:"openai.code_interpreter",name:"code_interpreter",inputSchema:R({})}),cD={codeInterpreter:lD,fileSearch:U9,webSearchPreview:q9};function G0(t,e){return e?e.some(r=>t.startsWith(r)):!1}async function uD({prompt:t,systemMessageMode:e,fileIdPrefixes:r}){var a,n,s,o,i,l;const c=[],u=[];for(const{role:h,content:g}of t)switch(h){case"system":{switch(e){case"system":{c.push({role:"system",content:g});break}case"developer":{c.push({role:"developer",content:g});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const d=e;throw new Error(`Unsupported system message mode: ${d}`)}}break}case"user":{c.push({role:"user",content:g.map((d,f)=>{var v,m,p;switch(d.type){case"text":return{type:"input_text",text:d.text};case"file":if(d.mediaType.startsWith("image/")){const y=d.mediaType==="image/*"?"image/jpeg":d.mediaType;return{type:"input_image",...d.data instanceof URL?{image_url:d.data.toString()}:typeof d.data=="string"&&G0(d.data,r)?{file_id:d.data}:{image_url:`data:${y};base64,${oa(d.data)}`},detail:(m=(v=d.providerOptions)==null?void 0:v.openai)==null?void 0:m.imageDetail}}else if(d.mediaType==="application/pdf"){if(d.data instanceof URL)throw new fr({functionality:"PDF file parts with URLs"});return{type:"input_file",...typeof d.data=="string"&&G0(d.data,r)?{file_id:d.data}:{filename:(p=d.filename)!=null?p:`part-${f}.pdf`,file_data:`data:application/pdf;base64,${oa(d.data)}`}}}else throw new fr({functionality:`file part media type ${d.mediaType}`})}})});break}case"assistant":{const d={};for(const f of g)switch(f.type){case"text":{c.push({role:"assistant",content:[{type:"output_text",text:f.text}],id:(s=(n=(a=f.providerOptions)==null?void 0:a.openai)==null?void 0:n.itemId)!=null?s:void 0});break}case"tool-call":{if(f.providerExecuted)break;c.push({type:"function_call",call_id:f.toolCallId,name:f.toolName,arguments:JSON.stringify(f.input),id:(l=(i=(o=f.providerOptions)==null?void 0:o.openai)==null?void 0:i.itemId)!=null?l:void 0});break}case"tool-result":{u.push({type:"other",message:"tool result parts in assistant messages are not supported for OpenAI responses"});break}case"reasoning":{const v=await Wr({provider:"openai",providerOptions:f.providerOptions,schema:dD}),m=v==null?void 0:v.itemId;if(m!=null){const p=d[m],y=[];f.text.length>0?y.push({type:"summary_text",text:f.text}):p!==void 0&&u.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(f)}.`}),p===void 0?(d[m]={type:"reasoning",id:m,encrypted_content:v==null?void 0:v.reasoningEncryptedContent,summary:y},c.push(d[m])):p.summary.push(...y)}else u.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(f)}.`});break}}break}case"tool":{for(const d of g){const f=d.output;let v;switch(f.type){case"text":case"error-text":v=f.value;break;case"content":case"json":case"error-json":v=JSON.stringify(f.value);break}c.push({type:"function_call_output",call_id:d.toolCallId,output:v})}break}default:{const d=h;throw new Error(`Unsupported role: ${d}`)}}return{messages:c,warnings:u}}var dD=R({itemId:S().nullish(),reasoningEncryptedContent:S().nullish()});function K0({finishReason:t,hasToolCalls:e}){switch(t){case void 0:case null:return e?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return e?"tool-calls":"unknown"}}function fD({tools:t,toolChoice:e,strictJsonSchema:r}){t=t!=null&&t.length?t:void 0;const a=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};const n=[];for(const o of t)switch(o.type){case"function":n.push({type:"function",name:o.name,description:o.description,parameters:o.inputSchema,strict:r});break;case"provider-defined":{switch(o.id){case"openai.file_search":{const i=U0.parse(o.args);n.push({type:"file_search",vector_store_ids:i.vectorStoreIds,max_num_results:i.maxNumResults,ranking_options:i.ranking?{ranker:i.ranking.ranker}:void 0,filters:i.filters});break}case"openai.web_search_preview":{const i=q0.parse(o.args);n.push({type:"web_search_preview",search_context_size:i.searchContextSize,user_location:i.userLocation});break}case"openai.code_interpreter":{const i=iD.parse(o.args);n.push({type:"code_interpreter",container:i.container==null?{type:"auto",file_ids:void 0}:typeof i.container=="string"?i.container:{type:"auto",file_ids:i.container.fileIds}});break}default:{a.push({type:"unsupported-tool",tool:o});break}}break}default:a.push({type:"unsupported-tool",tool:o});break}if(e==null)return{tools:n,toolChoice:void 0,toolWarnings:a};const s=e.type;switch(s){case"auto":case"none":case"required":return{tools:n,toolChoice:s,toolWarnings:a};case"tool":return{tools:n,toolChoice:e.toolName==="code_interpreter"||e.toolName==="file_search"||e.toolName==="web_search_preview"?{type:e.toolName}:{type:"function",name:e.toolName},toolWarnings:a};default:{const o=s;throw new fr({functionality:`tool choice type: ${o}`})}}}var W0=20,Q0=ce(R({token:S(),logprob:K(),top_logprobs:ce(R({token:S(),logprob:K()}))})),pD=class{constructor(t,e){this.specificationVersion="v2",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=e}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:e,stopSequences:r,topP:a,topK:n,presencePenalty:s,frequencyPenalty:o,seed:i,prompt:l,providerOptions:c,tools:u,toolChoice:h,responseFormat:g}){var d,f;const v=[],m=MD(this.modelId);n!=null&&v.push({type:"unsupported-setting",setting:"topK"}),i!=null&&v.push({type:"unsupported-setting",setting:"seed"}),s!=null&&v.push({type:"unsupported-setting",setting:"presencePenalty"}),o!=null&&v.push({type:"unsupported-setting",setting:"frequencyPenalty"}),r!=null&&v.push({type:"unsupported-setting",setting:"stopSequences"});const{messages:p,warnings:y}=await uD({prompt:l,systemMessageMode:m.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});v.push(...y);const _=await Wr({provider:"openai",providerOptions:c,schema:jD}),w=(d=_==null?void 0:_.strictJsonSchema)!=null?d:!1,E=typeof(_==null?void 0:_.logprobs)=="number"?_==null?void 0:_.logprobs:(_==null?void 0:_.logprobs)===!0?W0:void 0,P=E?Array.isArray(_==null?void 0:_.include)?[..._==null?void 0:_.include,"message.output_text.logprobs"]:["message.output_text.logprobs"]:_==null?void 0:_.include,T={model:this.modelId,input:p,temperature:e,top_p:a,max_output_tokens:t,...((g==null?void 0:g.type)==="json"||(_==null?void 0:_.textVerbosity))&&{text:{...(g==null?void 0:g.type)==="json"&&{format:g.schema!=null?{type:"json_schema",strict:w,name:(f=g.name)!=null?f:"response",description:g.description,schema:g.schema}:{type:"json_object"}},...(_==null?void 0:_.textVerbosity)&&{verbosity:_.textVerbosity}}},metadata:_==null?void 0:_.metadata,parallel_tool_calls:_==null?void 0:_.parallelToolCalls,previous_response_id:_==null?void 0:_.previousResponseId,store:_==null?void 0:_.store,user:_==null?void 0:_.user,instructions:_==null?void 0:_.instructions,service_tier:_==null?void 0:_.serviceTier,include:P,prompt_cache_key:_==null?void 0:_.promptCacheKey,safety_identifier:_==null?void 0:_.safetyIdentifier,top_logprobs:E,...m.isReasoningModel&&((_==null?void 0:_.reasoningEffort)!=null||(_==null?void 0:_.reasoningSummary)!=null)&&{reasoning:{...(_==null?void 0:_.reasoningEffort)!=null&&{effort:_.reasoningEffort},...(_==null?void 0:_.reasoningSummary)!=null&&{summary:_.reasoningSummary}}},...m.requiredAutoTruncation&&{truncation:"auto"}};m.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,v.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),T.top_p!=null&&(T.top_p=void 0,v.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))):((_==null?void 0:_.reasoningEffort)!=null&&v.push({type:"unsupported-setting",setting:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),(_==null?void 0:_.reasoningSummary)!=null&&v.push({type:"unsupported-setting",setting:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),(_==null?void 0:_.serviceTier)==="flex"&&!m.supportsFlexProcessing&&(v.push({type:"unsupported-setting",setting:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete T.service_tier),(_==null?void 0:_.serviceTier)==="priority"&&!m.supportsPriorityProcessing&&(v.push({type:"unsupported-setting",setting:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete T.service_tier);const{tools:O,toolChoice:M,toolWarnings:J}=fD({tools:u,toolChoice:h,strictJsonSchema:w});return{args:{...T,tools:O,tool_choice:M},warnings:[...v,...J]}}async doGenerate(t){var e,r,a,n,s,o,i,l,c,u,h,g,d,f,v,m,p;const{args:y,warnings:_}=await this.getArgs(t),w=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:E,value:P,rawValue:T}=await Rr({url:w,headers:mr(this.config.headers(),t.headers),body:y,failedResponseHandler:Qr,successfulResponseHandler:sa(R({id:S(),created_at:K(),error:R({code:S(),message:S()}).nullish(),model:S(),output:ce(Ja("type",[R({type:ne("message"),role:ne("assistant"),id:S(),content:ce(R({type:ne("output_text"),text:S(),logprobs:Q0.nullish(),annotations:ce(Ja("type",[R({type:ne("url_citation"),start_index:K(),end_index:K(),url:S(),title:S()}),R({type:ne("file_citation"),start_index:K(),end_index:K(),file_id:S(),quote:S()})]))}))}),R({type:ne("function_call"),call_id:S(),name:S(),arguments:S(),id:S()}),R({type:ne("web_search_call"),id:S(),status:S().optional(),action:R({type:ne("search"),query:S().optional()}).nullish()}),R({type:ne("computer_call"),id:S(),status:S().optional()}),R({type:ne("file_search_call"),id:S(),status:S().optional(),queries:ce(S()).nullish(),results:ce(R({attributes:R({file_id:S(),filename:S(),score:K(),text:S()})})).nullish()}),R({type:ne("reasoning"),id:S(),encrypted_content:S().nullish(),summary:ce(R({type:ne("summary_text"),text:S()}))})])),incomplete_details:R({reason:S()}).nullable(),usage:Y0})),abortSignal:t.abortSignal,fetch:this.config.fetch});if(P.error)throw new Xe({message:P.error.message,url:w,requestBodyValues:y,statusCode:400,responseHeaders:E,responseBody:T,isRetryable:!1});const O=[],M=[];for(const H of P.output)switch(H.type){case"reasoning":{H.summary.length===0&&H.summary.push({type:"summary_text",text:""});for(const G of H.summary)O.push({type:"reasoning",text:G.text,providerMetadata:{openai:{itemId:H.id,reasoningEncryptedContent:(e=H.encrypted_content)!=null?e:null}}});break}case"message":{for(const G of H.content){(a=(r=t.providerOptions)==null?void 0:r.openai)!=null&&a.logprobs&&G.logprobs&&M.push(G.logprobs),O.push({type:"text",text:G.text,providerMetadata:{openai:{itemId:H.id}}});for(const F of G.annotations)F.type==="url_citation"?O.push({type:"source",sourceType:"url",id:(o=(s=(n=this.config).generateId)==null?void 0:s.call(n))!=null?o:ir(),url:F.url,title:F.title}):F.type==="file_citation"&&O.push({type:"source",sourceType:"document",id:(c=(l=(i=this.config).generateId)==null?void 0:l.call(i))!=null?c:ir(),mediaType:"text/plain",title:F.quote,filename:F.file_id})}break}case"function_call":{O.push({type:"tool-call",toolCallId:H.call_id,toolName:H.name,input:H.arguments,providerMetadata:{openai:{itemId:H.id}}});break}case"web_search_call":{O.push({type:"tool-call",toolCallId:H.id,toolName:"web_search_preview",input:(h=(u=H.action)==null?void 0:u.query)!=null?h:"",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:H.id,toolName:"web_search_preview",result:{status:H.status||"completed",...((g=H.action)==null?void 0:g.query)&&{query:H.action.query}},providerExecuted:!0});break}case"computer_call":{O.push({type:"tool-call",toolCallId:H.id,toolName:"computer_use",input:"",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:H.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:H.status||"completed"},providerExecuted:!0});break}case"file_search_call":{O.push({type:"tool-call",toolCallId:H.id,toolName:"file_search",input:"",providerExecuted:!0}),O.push({type:"tool-result",toolCallId:H.id,toolName:"file_search",result:{type:"file_search_tool_result",status:H.status||"completed",...H.queries&&{queries:H.queries},...H.results&&{results:H.results}},providerExecuted:!0});break}}const J={openai:{responseId:P.id}};return M.length>0&&(J.openai.logprobs=M),{content:O,finishReason:K0({finishReason:(d=P.incomplete_details)==null?void 0:d.reason,hasToolCalls:O.some(H=>H.type==="tool-call")}),usage:{inputTokens:P.usage.input_tokens,outputTokens:P.usage.output_tokens,totalTokens:P.usage.input_tokens+P.usage.output_tokens,reasoningTokens:(v=(f=P.usage.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?v:void 0,cachedInputTokens:(p=(m=P.usage.input_tokens_details)==null?void 0:m.cached_tokens)!=null?p:void 0},request:{body:y},response:{id:P.id,timestamp:new Date(P.created_at*1e3),modelId:P.model,headers:E,body:T},providerMetadata:J,warnings:_}}async doStream(t){const{args:e,warnings:r}=await this.getArgs(t),{responseHeaders:a,value:n}=await Rr({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:{...e,stream:!0},failedResponseHandler:Qr,successfulResponseHandler:_l(SD),abortSignal:t.abortSignal,fetch:this.config.fetch}),s=this;let o="unknown";const i={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[];let c=null;const u={};let h=!1;const g={};return{stream:n.pipeThrough(new TransformStream({start(d){d.enqueue({type:"stream-start",warnings:r})},transform(d,f){var v,m,p,y,_,w,E,P,T,O,M,J,H,G,F,Z,te,pe,ve;if(t.includeRawChunks&&f.enqueue({type:"raw",rawValue:d.rawValue}),!d.success){o="error",f.enqueue({type:"error",error:d.error});return}const N=d.value;if(ew(N))N.item.type==="function_call"?(u[N.output_index]={toolName:N.item.name,toolCallId:N.item.call_id},f.enqueue({type:"tool-input-start",id:N.item.call_id,toolName:N.item.name})):N.item.type==="web_search_call"?(u[N.output_index]={toolName:"web_search_preview",toolCallId:N.item.id},f.enqueue({type:"tool-input-start",id:N.item.id,toolName:"web_search_preview"})):N.item.type==="computer_call"?(u[N.output_index]={toolName:"computer_use",toolCallId:N.item.id},f.enqueue({type:"tool-input-start",id:N.item.id,toolName:"computer_use"})):N.item.type==="file_search_call"?(u[N.output_index]={toolName:"file_search",toolCallId:N.item.id},f.enqueue({type:"tool-input-start",id:N.item.id,toolName:"file_search"})):N.item.type==="message"?f.enqueue({type:"text-start",id:N.item.id,providerMetadata:{openai:{itemId:N.item.id}}}):CD(N)&&(g[N.item.id]={encryptedContent:N.item.encrypted_content,summaryParts:[0]},f.enqueue({type:"reasoning-start",id:`${N.item.id}:0`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:(v=N.item.encrypted_content)!=null?v:null}}}));else if(X0(N)){if(N.item.type==="function_call")u[N.output_index]=void 0,h=!0,f.enqueue({type:"tool-input-end",id:N.item.call_id}),f.enqueue({type:"tool-call",toolCallId:N.item.call_id,toolName:N.item.name,input:N.item.arguments,providerMetadata:{openai:{itemId:N.item.id}}});else if(N.item.type==="web_search_call")u[N.output_index]=void 0,h=!0,f.enqueue({type:"tool-input-end",id:N.item.id}),f.enqueue({type:"tool-call",toolCallId:N.item.id,toolName:"web_search_preview",input:(p=(m=N.item.action)==null?void 0:m.query)!=null?p:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:N.item.id,toolName:"web_search_preview",result:{type:"web_search_tool_result",status:N.item.status||"completed",...((y=N.item.action)==null?void 0:y.query)&&{query:N.item.action.query}},providerExecuted:!0});else if(N.item.type==="computer_call")u[N.output_index]=void 0,h=!0,f.enqueue({type:"tool-input-end",id:N.item.id}),f.enqueue({type:"tool-call",toolCallId:N.item.id,toolName:"computer_use",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:N.item.id,toolName:"computer_use",result:{type:"computer_use_tool_result",status:N.item.status||"completed"},providerExecuted:!0});else if(N.item.type==="file_search_call")u[N.output_index]=void 0,h=!0,f.enqueue({type:"tool-input-end",id:N.item.id}),f.enqueue({type:"tool-call",toolCallId:N.item.id,toolName:"file_search",input:"",providerExecuted:!0}),f.enqueue({type:"tool-result",toolCallId:N.item.id,toolName:"file_search",result:{type:"file_search_tool_result",status:N.item.status||"completed",...N.item.queries&&{queries:N.item.queries},...N.item.results&&{results:N.item.results}},providerExecuted:!0});else if(N.item.type==="message")f.enqueue({type:"text-end",id:N.item.id});else if(TD(N)){const ie=g[N.item.id];for(const D of ie.summaryParts)f.enqueue({type:"reasoning-end",id:`${N.item.id}:${D}`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:(_=N.item.encrypted_content)!=null?_:null}}});delete g[N.item.id]}}else if(ID(N)){const ie=u[N.output_index];ie!=null&&f.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:N.delta})}else kD(N)?(c=N.response.id,f.enqueue({type:"response-metadata",id:N.response.id,timestamp:new Date(N.response.created_at*1e3),modelId:N.response.model})):PD(N)?(f.enqueue({type:"text-delta",id:N.item_id,delta:N.delta}),N.logprobs&&l.push(N.logprobs)):OD(N)?N.summary_index>0&&((w=g[N.item_id])==null||w.summaryParts.push(N.summary_index),f.enqueue({type:"reasoning-start",id:`${N.item_id}:${N.summary_index}`,providerMetadata:{openai:{itemId:N.item_id,reasoningEncryptedContent:(P=(E=g[N.item_id])==null?void 0:E.encryptedContent)!=null?P:null}}})):AD(N)?f.enqueue({type:"reasoning-delta",id:`${N.item_id}:${N.summary_index}`,delta:N.delta,providerMetadata:{openai:{itemId:N.item_id}}}):xD(N)?(o=K0({finishReason:(T=N.response.incomplete_details)==null?void 0:T.reason,hasToolCalls:h}),i.inputTokens=N.response.usage.input_tokens,i.outputTokens=N.response.usage.output_tokens,i.totalTokens=N.response.usage.input_tokens+N.response.usage.output_tokens,i.reasoningTokens=(M=(O=N.response.usage.output_tokens_details)==null?void 0:O.reasoning_tokens)!=null?M:void 0,i.cachedInputTokens=(H=(J=N.response.usage.input_tokens_details)==null?void 0:J.cached_tokens)!=null?H:void 0):RD(N)?N.annotation.type==="url_citation"?f.enqueue({type:"source",sourceType:"url",id:(Z=(F=(G=s.config).generateId)==null?void 0:F.call(G))!=null?Z:ir(),url:N.annotation.url,title:N.annotation.title}):N.annotation.type==="file_citation"&&f.enqueue({type:"source",sourceType:"document",id:(ve=(pe=(te=s.config).generateId)==null?void 0:pe.call(te))!=null?ve:ir(),mediaType:"text/plain",title:N.annotation.quote,filename:N.annotation.file_id}):ND(N)&&f.enqueue({type:"error",error:N})},flush(d){const f={openai:{responseId:c}};l.length>0&&(f.openai.logprobs=l),d.enqueue({type:"finish",finishReason:o,usage:i,providerMetadata:f})}})),request:{body:e},response:{headers:a}}}},Y0=R({input_tokens:K(),input_tokens_details:R({cached_tokens:K().nullish()}).nullish(),output_tokens:K(),output_tokens_details:R({reasoning_tokens:K().nullish()}).nullish()}),hD=R({type:ne("response.output_text.delta"),item_id:S(),delta:S(),logprobs:Q0.nullish()}),mD=R({type:ne("error"),code:S(),message:S(),param:S().nullish(),sequence_number:K()}),vD=R({type:zt(["response.completed","response.incomplete"]),response:R({incomplete_details:R({reason:S()}).nullish(),usage:Y0})}),gD=R({type:ne("response.created"),response:R({id:S(),created_at:K(),model:S()})}),yD=R({type:ne("response.output_item.added"),output_index:K(),item:Ja("type",[R({type:ne("message"),id:S()}),R({type:ne("reasoning"),id:S(),encrypted_content:S().nullish()}),R({type:ne("function_call"),id:S(),call_id:S(),name:S(),arguments:S()}),R({type:ne("web_search_call"),id:S(),status:S(),action:R({type:ne("search"),query:S().optional()}).nullish()}),R({type:ne("computer_call"),id:S(),status:S()}),R({type:ne("file_search_call"),id:S(),status:S(),queries:ce(S()).nullish(),results:ce(R({attributes:R({file_id:S(),filename:S(),score:K(),text:S()})})).optional()})])}),_D=R({type:ne("response.output_item.done"),output_index:K(),item:Ja("type",[R({type:ne("message"),id:S()}),R({type:ne("reasoning"),id:S(),encrypted_content:S().nullish()}),R({type:ne("function_call"),id:S(),call_id:S(),name:S(),arguments:S(),status:ne("completed")}),R({type:ne("web_search_call"),id:S(),status:ne("completed"),action:R({type:ne("search"),query:S().optional()}).nullish()}),R({type:ne("computer_call"),id:S(),status:ne("completed")}),R({type:ne("file_search_call"),id:S(),status:ne("completed"),queries:ce(S()).nullish(),results:ce(R({attributes:R({file_id:S(),filename:S(),score:K(),text:S()})})).nullish()})])}),wD=R({type:ne("response.function_call_arguments.delta"),item_id:S(),output_index:K(),delta:S()}),bD=R({type:ne("response.output_text.annotation.added"),annotation:Ja("type",[R({type:ne("url_citation"),url:S(),title:S()}),R({type:ne("file_citation"),file_id:S(),quote:S()})])}),ED=R({type:ne("response.reasoning_summary_part.added"),item_id:S(),summary_index:K()}),$D=R({type:ne("response.reasoning_summary_text.delta"),item_id:S(),summary_index:K(),delta:S()}),SD=Ve([hD,vD,gD,yD,_D,wD,bD,ED,$D,mD,R({type:S()}).loose()]);function PD(t){return t.type==="response.output_text.delta"}function X0(t){return t.type==="response.output_item.done"}function TD(t){return X0(t)&&t.item.type==="reasoning"}function xD(t){return t.type==="response.completed"||t.type==="response.incomplete"}function kD(t){return t.type==="response.created"}function ID(t){return t.type==="response.function_call_arguments.delta"}function ew(t){return t.type==="response.output_item.added"}function CD(t){return ew(t)&&t.item.type==="reasoning"}function RD(t){return t.type==="response.output_text.annotation.added"}function OD(t){return t.type==="response.reasoning_summary_part.added"}function AD(t){return t.type==="response.reasoning_summary_text.delta"}function ND(t){return t.type==="error"}function MD(t){const e=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),r=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),a={requiredAutoTruncation:!1,systemMessageMode:"system",supportsFlexProcessing:e,supportsPriorityProcessing:r};return t.startsWith("gpt-5-chat")?{...a,isReasoningModel:!1}:t.startsWith("o")||t.startsWith("gpt-5")||t.startsWith("codex-")||t.startsWith("computer-use")?t.startsWith("o1-mini")||t.startsWith("o1-preview")?{...a,isReasoningModel:!0,systemMessageMode:"remove"}:{...a,isReasoningModel:!0,systemMessageMode:"developer"}:{...a,isReasoningModel:!1}}var jD=R({metadata:pr().nullish(),parallelToolCalls:$t().nullish(),previousResponseId:S().nullish(),store:$t().nullish(),user:S().nullish(),reasoningEffort:S().nullish(),strictJsonSchema:$t().nullish(),instructions:S().nullish(),reasoningSummary:S().nullish(),serviceTier:zt(["auto","flex","priority"]).nullish(),include:ce(zt(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),textVerbosity:zt(["low","medium","high"]).nullish(),promptCacheKey:S().nullish(),safetyIdentifier:S().nullish(),logprobs:Ve([$t(),K().min(1).max(W0)]).optional()}),DD=R({instructions:S().nullish(),speed:K().min(.25).max(4).default(1).nullish()}),LD=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({text:t,voice:e="alloy",outputFormat:r="mp3",speed:a,instructions:n,language:s,providerOptions:o}){const i=[],l=await Wr({provider:"openai",providerOptions:o,schema:DD}),c={model:this.modelId,input:t,voice:e,response_format:"mp3",speed:a,instructions:n};if(r&&(["mp3","opus","aac","flac","wav","pcm"].includes(r)?c.response_format=r:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${r}. Using mp3 instead.`})),l){const u={};for(const h in u){const g=u[h];g!==void 0&&(c[h]=g)}}return s&&i.push({type:"unsupported-setting",setting:"language",details:`OpenAI speech models do not support language selection. Language parameter "${s}" was ignored.`}),{requestBody:c,warnings:i}}async doGenerate(t){var e,r,a;const n=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{requestBody:s,warnings:o}=await this.getArgs(t),{value:i,responseHeaders:l,rawValue:c}=await Rr({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:s,failedResponseHandler:Qr,successfulResponseHandler:O9(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:i,warnings:o,request:{body:JSON.stringify(s)},response:{timestamp:n,modelId:this.modelId,headers:l,body:c}}}},zD=R({include:ce(S()).optional(),language:S().optional(),prompt:S().optional(),temperature:K().min(0).max(1).default(0).optional(),timestampGranularities:ce(zt(["word","segment"])).default(["segment"]).optional()}),tw={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"},UD=class{constructor(t,e){this.modelId=t,this.config=e,this.specificationVersion="v2"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:e,providerOptions:r}){const a=[],n=await Wr({provider:"openai",providerOptions:r,schema:zD}),s=new FormData,o=t instanceof Uint8Array?new Blob([t]):new Blob([M9(t)]);if(s.append("model",this.modelId),s.append("file",new File([o],"audio",{type:e})),n){const i={include:n.include,language:n.language,prompt:n.prompt,response_format:"verbose_json",temperature:n.temperature,timestamp_granularities:n.timestampGranularities};for(const[l,c]of Object.entries(i))c!=null&&s.append(l,String(c))}return{formData:s,warnings:a}}async doGenerate(t){var e,r,a,n,s,o,i,l;const c=(a=(r=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:r.call(e))!=null?a:new Date,{formData:u,warnings:h}=await this.getArgs(t),{value:g,responseHeaders:d,rawValue:f}=await R9({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),formData:u,failedResponseHandler:Qr,successfulResponseHandler:sa(qD),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=g.language!=null&&g.language in tw?tw[g.language]:void 0;return{text:g.text,segments:(i=(o=(n=g.segments)==null?void 0:n.map(m=>({text:m.text,startSecond:m.start,endSecond:m.end})))!=null?o:(s=g.words)==null?void 0:s.map(m=>({text:m.word,startSecond:m.start,endSecond:m.end})))!=null?i:[],language:v,durationInSeconds:(l=g.duration)!=null?l:void 0,warnings:h,response:{timestamp:c,modelId:this.modelId,headers:d,body:f}}}},qD=R({text:S(),language:S().nullish(),duration:K().nullish(),words:ce(R({word:S(),start:K(),end:K()})).nullish(),segments:ce(R({id:K(),seek:K(),start:K(),end:K(),text:S(),tokens:ce(K()),temperature:K(),avg_logprob:K(),compression_ratio:K(),no_speech_prob:K()})).nullish()});function rw(t={}){var e,r;const a=(e=M0(t.baseURL))!=null?e:"https://api.openai.com/v1",n=(r=t.name)!=null?r:"openai",s=()=>({Authorization:`Bearer ${R0({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers}),o=v=>new Z9(v,{provider:`${n}.chat`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),i=v=>new Q9(v,{provider:`${n}.completion`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),l=v=>new tD(v,{provider:`${n}.embedding`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),c=v=>new sD(v,{provider:`${n}.image`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),u=v=>new UD(v,{provider:`${n}.transcription`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),h=v=>new LD(v,{provider:`${n}.speech`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch}),g=v=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return d(v)},d=v=>new pD(v,{provider:`${n}.responses`,url:({path:m})=>`${a}${m}`,headers:s,fetch:t.fetch,fileIdPrefixes:["file-"]}),f=function(v){return g(v)};return f.languageModel=g,f.chat=o,f.completion=i,f.responses=d,f.embedding=l,f.textEmbedding=l,f.textEmbeddingModel=l,f.image=c,f.imageModel=c,f.transcription=u,f.transcriptionModel=u,f.speech=h,f.speechModel=h,f.tools=cD,f}rw();function yo(t){var e,r;return(r=(e=t==null?void 0:t.providerOptions)==null?void 0:e.openaiCompatible)!=null?r:{}}function FD(t){const e=[];for(const{role:r,content:a,...n}of t){const s=yo({...n});switch(r){case"system":{e.push({role:"system",content:a,...s});break}case"user":{if(a.length===1&&a[0].type==="text"){e.push({role:"user",content:a[0].text,...yo(a[0])});break}e.push({role:"user",content:a.map(o=>{const i=yo(o);switch(o.type){case"text":return{type:"text",text:o.text,...i};case"file":if(o.mediaType.startsWith("image/")){const l=o.mediaType==="image/*"?"image/jpeg":o.mediaType;return{type:"image_url",image_url:{url:o.data instanceof URL?o.data.toString():`data:${l};base64,${oa(o.data)}`},...i}}else throw new fr({functionality:`file part media type ${o.mediaType}`})}}),...s});break}case"assistant":{let o="";const i=[];for(const l of a){const c=yo(l);switch(l.type){case"text":{o+=l.text;break}case"tool-call":{i.push({id:l.toolCallId,type:"function",function:{name:l.toolName,arguments:JSON.stringify(l.input)},...c});break}}}e.push({role:"assistant",content:o,tool_calls:i.length>0?i:void 0,...s});break}case"tool":{for(const o of a){const i=o.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=yo(o);e.push({role:"tool",tool_call_id:o.toolCallId,content:l,...c})}break}default:{const o=r;throw new Error(`Unsupported role: ${o}`)}}}return e}function nw({id:t,model:e,created:r}){return{id:t??void 0,modelId:e??void 0,timestamp:r!=null?new Date(r*1e3):void 0}}function aw(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var sw=R({user:S().optional(),reasoningEffort:S().optional()}),ZD=R({error:R({message:S(),type:S().nullish(),param:pr().nullish(),code:Ve([S(),K()]).nullish()})}),VD={errorSchema:ZD,errorToMessage:t=>t.error.message};function HD({tools:t,toolChoice:e}){t=t!=null&&t.length?t:void 0;const r=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};const a=[];for(const s of t)s.type==="provider-defined"?r.push({type:"unsupported-tool",tool:s}):a.push({type:"function",function:{name:s.name,description:s.description,parameters:s.inputSchema}});if(e==null)return{tools:a,toolChoice:void 0,toolWarnings:r};const n=e.type;switch(n){case"auto":case"none":case"required":return{tools:a,toolChoice:n,toolWarnings:r};case"tool":return{tools:a,toolChoice:{type:"function",function:{name:e.toolName}},toolWarnings:r};default:{const s=n;throw new fr({functionality:`tool choice type: ${s}`})}}}var BD=class{constructor(t,e){this.specificationVersion="v2";var r,a;this.modelId=t,this.config=e;const n=(r=e.errorStructure)!=null?r:VD;this.chunkSchema=GD(n.errorSchema),this.failedResponseHandler=N0(n),this.supportsStructuredOutputs=(a=e.supportsStructuredOutputs)!=null?a:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,e,r;return(r=(e=(t=this.config).supportedUrls)==null?void 0:e.call(t))!=null?r:{}}async getArgs({prompt:t,maxOutputTokens:e,temperature:r,topP:a,topK:n,frequencyPenalty:s,presencePenalty:o,providerOptions:i,stopSequences:l,responseFormat:c,seed:u,toolChoice:h,tools:g}){var d,f,v;const m=[],p=Object.assign((d=await Wr({provider:"openai-compatible",providerOptions:i,schema:sw}))!=null?d:{},(f=await Wr({provider:this.providerOptionsName,providerOptions:i,schema:sw}))!=null?f:{});n!=null&&m.push({type:"unsupported-setting",setting:"topK"}),(c==null?void 0:c.type)==="json"&&c.schema!=null&&!this.supportsStructuredOutputs&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:y,toolChoice:_,toolWarnings:w}=HD({tools:g,toolChoice:h});return{args:{model:this.modelId,user:p.user,max_tokens:e,temperature:r,top_p:a,frequency_penalty:s,presence_penalty:o,response_format:(c==null?void 0:c.type)==="json"?this.supportsStructuredOutputs===!0&&c.schema!=null?{type:"json_schema",json_schema:{schema:c.schema,name:(v=c.name)!=null?v:"response",description:c.description}}:{type:"json_object"}:void 0,stop:l,seed:u,...i==null?void 0:i[this.providerOptionsName],reasoning_effort:p.reasoningEffort,messages:FD(t),tools:y,tool_choice:_},warnings:[...m,...w]}}async doGenerate(t){var e,r,a,n,s,o,i,l,c,u,h,g,d,f,v,m,p;const{args:y,warnings:_}=await this.getArgs({...t}),w=JSON.stringify(y),{responseHeaders:E,value:P,rawValue:T}=await Rr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:y,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:sa(JD),abortSignal:t.abortSignal,fetch:this.config.fetch}),O=P.choices[0],M=[],J=O.message.content;J!=null&&J.length>0&&M.push({type:"text",text:J});const H=(e=O.message.reasoning_content)!=null?e:O.message.reasoning;if(H!=null&&H.length>0&&M.push({type:"reasoning",text:H}),O.message.tool_calls!=null)for(const Z of O.message.tool_calls)M.push({type:"tool-call",toolCallId:(r=Z.id)!=null?r:ir(),toolName:Z.function.name,input:Z.function.arguments});const G={[this.providerOptionsName]:{},...await((n=(a=this.config.metadataExtractor)==null?void 0:a.extractMetadata)==null?void 0:n.call(a,{parsedBody:T}))},F=(s=P.usage)==null?void 0:s.completion_tokens_details;return(F==null?void 0:F.accepted_prediction_tokens)!=null&&(G[this.providerOptionsName].acceptedPredictionTokens=F==null?void 0:F.accepted_prediction_tokens),(F==null?void 0:F.rejected_prediction_tokens)!=null&&(G[this.providerOptionsName].rejectedPredictionTokens=F==null?void 0:F.rejected_prediction_tokens),{content:M,finishReason:aw(O.finish_reason),usage:{inputTokens:(i=(o=P.usage)==null?void 0:o.prompt_tokens)!=null?i:void 0,outputTokens:(c=(l=P.usage)==null?void 0:l.completion_tokens)!=null?c:void 0,totalTokens:(h=(u=P.usage)==null?void 0:u.total_tokens)!=null?h:void 0,reasoningTokens:(f=(d=(g=P.usage)==null?void 0:g.completion_tokens_details)==null?void 0:d.reasoning_tokens)!=null?f:void 0,cachedInputTokens:(p=(m=(v=P.usage)==null?void 0:v.prompt_tokens_details)==null?void 0:m.cached_tokens)!=null?p:void 0},providerMetadata:G,request:{body:w},response:{...nw(P),headers:E,body:T},warnings:_}}async doStream(t){var e;const{args:r,warnings:a}=await this.getArgs({...t}),n={...r,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},s=(e=this.config.metadataExtractor)==null?void 0:e.createStreamExtractor(),{responseHeaders:o,value:i}=await Rr({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:mr(this.config.headers(),t.headers),body:n,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:_l(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=[];let c="unknown";const u={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let h=!0;const g=this.providerOptionsName;let d=!1,f=!1;return{stream:i.pipeThrough(new TransformStream({start(v){v.enqueue({type:"stream-start",warnings:a})},transform(v,m){var p,y,_,w,E,P,T,O,M,J,H,G,F;if(t.includeRawChunks&&m.enqueue({type:"raw",rawValue:v.rawValue}),!v.success){c="error",m.enqueue({type:"error",error:v.error});return}const Z=v.value;if(s==null||s.processChunk(v.rawValue),"error"in Z){c="error",m.enqueue({type:"error",error:Z.error.message});return}if(h&&(h=!1,m.enqueue({type:"response-metadata",...nw(Z)})),Z.usage!=null){const{prompt_tokens:N,completion_tokens:ie,total_tokens:D,prompt_tokens_details:C,completion_tokens_details:z}=Z.usage;u.promptTokens=N??void 0,u.completionTokens=ie??void 0,u.totalTokens=D??void 0,(z==null?void 0:z.reasoning_tokens)!=null&&(u.completionTokensDetails.reasoningTokens=z==null?void 0:z.reasoning_tokens),(z==null?void 0:z.accepted_prediction_tokens)!=null&&(u.completionTokensDetails.acceptedPredictionTokens=z==null?void 0:z.accepted_prediction_tokens),(z==null?void 0:z.rejected_prediction_tokens)!=null&&(u.completionTokensDetails.rejectedPredictionTokens=z==null?void 0:z.rejected_prediction_tokens),(C==null?void 0:C.cached_tokens)!=null&&(u.promptTokensDetails.cachedTokens=C==null?void 0:C.cached_tokens)}const te=Z.choices[0];if((te==null?void 0:te.finish_reason)!=null&&(c=aw(te.finish_reason)),(te==null?void 0:te.delta)==null)return;const pe=te.delta,ve=(p=pe.reasoning_content)!=null?p:pe.reasoning;if(ve&&(d||(m.enqueue({type:"reasoning-start",id:"reasoning-0"}),d=!0),m.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ve})),pe.content&&(f||(m.enqueue({type:"text-start",id:"txt-0"}),f=!0),m.enqueue({type:"text-delta",id:"txt-0",delta:pe.content})),pe.tool_calls!=null)for(const N of pe.tool_calls){const ie=N.index;if(l[ie]==null){if(N.id==null)throw new Js({data:N,message:"Expected 'id' to be a string."});if(((y=N.function)==null?void 0:y.name)==null)throw new Js({data:N,message:"Expected 'function.name' to be a string."});m.enqueue({type:"tool-input-start",id:N.id,toolName:N.function.name}),l[ie]={id:N.id,type:"function",function:{name:N.function.name,arguments:(_=N.function.arguments)!=null?_:""},hasFinished:!1};const C=l[ie];((w=C.function)==null?void 0:w.name)!=null&&((E=C.function)==null?void 0:E.arguments)!=null&&(C.function.arguments.length>0&&m.enqueue({type:"tool-input-start",id:C.id,toolName:C.function.name}),yl(C.function.arguments)&&(m.enqueue({type:"tool-input-end",id:C.id}),m.enqueue({type:"tool-call",toolCallId:(P=C.id)!=null?P:ir(),toolName:C.function.name,input:C.function.arguments}),C.hasFinished=!0));continue}const D=l[ie];D.hasFinished||(((T=N.function)==null?void 0:T.arguments)!=null&&(D.function.arguments+=(M=(O=N.function)==null?void 0:O.arguments)!=null?M:""),m.enqueue({type:"tool-input-delta",id:D.id,delta:(J=N.function.arguments)!=null?J:""}),((H=D.function)==null?void 0:H.name)!=null&&((G=D.function)==null?void 0:G.arguments)!=null&&yl(D.function.arguments)&&(m.enqueue({type:"tool-input-end",id:D.id}),m.enqueue({type:"tool-call",toolCallId:(F=D.id)!=null?F:ir(),toolName:D.function.name,input:D.function.arguments}),D.hasFinished=!0))}},flush(v){var m,p,y,_,w,E;d&&v.enqueue({type:"reasoning-end",id:"reasoning-0"}),f&&v.enqueue({type:"text-end",id:"txt-0"});for(const T of l.filter(O=>!O.hasFinished))v.enqueue({type:"tool-input-end",id:T.id}),v.enqueue({type:"tool-call",toolCallId:(m=T.id)!=null?m:ir(),toolName:T.function.name,input:T.function.arguments});const P={[g]:{},...s==null?void 0:s.buildMetadata()};u.completionTokensDetails.acceptedPredictionTokens!=null&&(P[g].acceptedPredictionTokens=u.completionTokensDetails.acceptedPredictionTokens),u.completionTokensDetails.rejectedPredictionTokens!=null&&(P[g].rejectedPredictionTokens=u.completionTokensDetails.rejectedPredictionTokens),v.enqueue({type:"finish",finishReason:c,usage:{inputTokens:(p=u.promptTokens)!=null?p:void 0,outputTokens:(y=u.completionTokens)!=null?y:void 0,totalTokens:(_=u.totalTokens)!=null?_:void 0,reasoningTokens:(w=u.completionTokensDetails.reasoningTokens)!=null?w:void 0,cachedInputTokens:(E=u.promptTokensDetails.cachedTokens)!=null?E:void 0},providerMetadata:P})}})),request:{body:n},response:{headers:o}}}},ow=R({prompt_tokens:K().nullish(),completion_tokens:K().nullish(),total_tokens:K().nullish(),prompt_tokens_details:R({cached_tokens:K().nullish()}).nullish(),completion_tokens_details:R({reasoning_tokens:K().nullish(),accepted_prediction_tokens:K().nullish(),rejected_prediction_tokens:K().nullish()}).nullish()}).nullish(),JD=R({id:S().nullish(),created:K().nullish(),model:S().nullish(),choices:ce(R({message:R({role:ne("assistant").nullish(),content:S().nullish(),reasoning_content:S().nullish(),reasoning:S().nullish(),tool_calls:ce(R({id:S().nullish(),function:R({name:S(),arguments:S()})})).nullish()}),finish_reason:S().nullish()})),usage:ow}),GD=t=>Ve([R({id:S().nullish(),created:K().nullish(),model:S().nullish(),choices:ce(R({delta:R({role:zt(["assistant"]).nullish(),content:S().nullish(),reasoning_content:S().nullish(),reasoning:S().nullish(),tool_calls:ce(R({index:K(),id:S().nullish(),function:R({name:S().nullish(),arguments:S().nullish()})})).nullish()}).nullish(),finish_reason:S().nullish()})),usage:ow}),t]);R({echo:$t().optional(),logitBias:Qt(S(),K()).optional(),suffix:S().optional(),user:S().optional()});var KD=R({prompt_tokens:K(),completion_tokens:K(),total_tokens:K()});R({id:S().nullish(),created:K().nullish(),model:S().nullish(),choices:ce(R({text:S(),finish_reason:S()})),usage:KD.nullish()}),R({dimensions:K().optional(),user:S().optional()}),R({data:ce(R({embedding:ce(K())})),usage:R({prompt_tokens:K()}).nullish(),providerMetadata:Qt(S(),Qt(S(),pr())).optional()}),R({data:ce(R({b64_json:S()}))});var iw=t=>{var e,r;return t==null?void 0:{deepseek:{promptCacheHitTokens:(e=t.prompt_cache_hit_tokens)!=null?e:NaN,promptCacheMissTokens:(r=t.prompt_cache_miss_tokens)!=null?r:NaN}}},WD={extractMetadata:async({parsedBody:t})=>{const e=await go({value:t,schema:QD});return!e.success||e.value.usage==null?void 0:iw(e.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async e=>{var r,a;const n=await go({value:e,schema:YD});n.success&&((a=(r=n.value.choices)==null?void 0:r[0])==null?void 0:a.finish_reason)==="stop"&&n.value.usage&&(t=n.value.usage)},buildMetadata:()=>iw(t)}}},lw=R({prompt_cache_hit_tokens:K().nullish(),prompt_cache_miss_tokens:K().nullish()}),QD=R({usage:lw.nullish()}),YD=R({choices:ce(R({finish_reason:S().nullish()})).nullish(),usage:lw.nullish()});function cw(t={}){var e;const r=M0((e=t.baseURL)!=null?e:"https://api.deepseek.com/v1"),a=()=>({Authorization:`Bearer ${R0({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers}),n=o=>new BD(o,{provider:"deepseek.chat",url:({path:i})=>`${r}${i}`,headers:a,fetch:t.fetch,metadataExtractor:WD}),s=o=>n(o);return s.languageModel=n,s.chat=n,s.textEmbeddingModel=o=>{throw new _d({modelId:o,modelType:"textEmbeddingModel"})},s.imageModel=o=>{throw new _d({modelId:o,modelType:"imageModel"})},s}cw();const wf=async t=>{const e={};try{const r=await t.listTools();for(const{name:a,description:n,inputSchema:s}of r.tools){const o=async(i,l)=>t.callTool({name:a,arguments:i},{signal:l==null?void 0:l.abortSignal});e[a]=qA({description:n,inputSchema:il({...s,properties:s.properties??{},additionalProperties:!1}),execute:o})}return e}catch(r){throw r}},XD={openai:rw,deepseek:cw};class e3{constructor({llmConfig:e,mcpServers:r}){if(this.mcpServers={},this.mcpClients={},this.mcpTools={},this.ignoreToolnames=[],this.messages=[],!e)throw new Error("llmConfig is required to initialize AgentModelProvider");if(this.mcpServers=r||{},this.mcpClients={},this.mcpTools={},e.llm)this.llm=e.llm;else if(e.providerType){const a=e.providerType;let n;typeof a=="string"?n=XD[a]:n=a,this.llm=n({apiKey:e.apiKey,baseURL:e.baseURL})}else throw new Error("Either llmConfig.llm or llmConfig.providerType must be provided")}async _createOneClient(e){try{let r;"type"in e&&e.type.toLocaleLowerCase()==="streamablehttp"?r=new Us(new URL(e.url)):"type"in e&&e.type==="extension"?r=new pv(e.sessionId):r=e;const a=new uv({name:"mcp-web-client",version:"1.0.0"},{capabilities:{roots:{listChanged:!0},sampling:{},elicitation:{}}});return await a.connect(r),a.__transport__=r,a}catch(r){return this.onError&&this.onError((r==null?void 0:r.message)||"Failed to create MCP client",r),console.error("Failed to create MCP client",e,r),null}}async _closeOneClient(e){var r,a,n;try{const s=e.__transport__;if(s&&s instanceof Zs||s&&s instanceof qs)return;await((r=s==null?void 0:s.terminateSession)==null?void 0:r.call(s)),await((a=s==null?void 0:s.close)==null?void 0:a.call(s)),await((n=e==null?void 0:e.close)==null?void 0:n.call(e))}catch{}}async _createMpcClients(){const e=Object.entries(this.mcpServers),r=await Promise.all(e.map(async([a,n])=>{const s=await this._createOneClient(n);return{serverName:a,client:s}}));this.mcpClients={},r.forEach(({serverName:a,client:n})=>{this.mcpClients[a]=n})}async _createMpcTools(){const e=Object.entries(this.mcpClients),r=await Promise.all(e.map(async([a,n])=>{try{const s=n?await wf(n):null;return{serverName:a,tools:s}}catch(s){return this.onError&&this.onError((s==null?void 0:s.message)||"Failed to query tools",s),console.error("Failed to query tools",s),{serverName:a,tools:null}}}));this.mcpTools={},r.forEach(({serverName:a,tools:n})=>{const s=n&&typeof n=="object"?n:{};this.mcpTools[a]=s})}async closeAll(){await Promise.all(Object.values(this.mcpClients).map(async e=>{try{await this._closeOneClient(e)}catch(r){this.onError&&this.onError((r==null?void 0:r.message)||"Failed to close client",r),console.error("Failed to close client",r)}}))}async initClientsAndTools(){var e;await this._createMpcClients(),await this._createMpcTools(),(e=this.onUpdatedTools)==null||e.call(this)}async updateMcpServers(e){await this.closeAll(),this.mcpServers=e||this.mcpServers,await this.initClientsAndTools()}async insertMcpServer(e,r){var s,o;if(this.mcpServers[e])return!1;const a=await this._createOneClient(r);if(!a)return(s=this.onError)==null||s.call(this,`Failed to create MCP client: ${e}`),null;this.mcpClients[e]=a;const n=await wf(a);return this.mcpTools[e]=n&&typeof n=="object"?n:{},this.mcpServers[e]=r,(o=this.onUpdatedTools)==null||o.call(this),a}async removeMcpServer(e){var n;if(!this.mcpServers[e])return;delete this.mcpServers[e];const r=this.mcpClients[e];delete this.mcpClients[e];try{await this._closeOneClient(r)}catch{}const a=this.mcpTools[e];delete this.mcpTools[e],a&&Object.keys(a).forEach(s=>{this.ignoreToolnames=this.ignoreToolnames.filter(o=>o!==s)}),(n=this.onUpdatedTools)==null||n.call(this)}_tempMergeTools(e={}){const r=Object.values(this.mcpTools).reduce((a,n)=>({...a,...n}),{});return Object.assign(r,e),this.ignoreToolnames.forEach(a=>{delete r[a]}),r}async _chat(e,{model:r,maxSteps:a=5,...n}){var i;if(!this.llm)throw new Error("LLM is not initialized");await this.initClientsAndTools();const s={model:this.llm(r),stopWhen:uf(a),...n,tools:this._tempMergeTools(n.tools)};n.message&&!n.messages&&(this.messages.push({role:"user",content:n.message}),s.messages=[...this.messages]);const o=e(s);return(i=o==null?void 0:o.response)==null||i.then(l=>{this.messages.push(...l.messages)}),o}async chat(e){return this._chat(Cj,e)}async chatStream(e){return this._chat(Kj,e)}}Fe.AgentModelProvider=e3,Fe.Ajv=k$,Fe.AuthClientProvider=ik,Fe.ContentScriptServerTransport=fI,Fe.ExtensionClientTransport=pv,Fe.ExtensionPageServerTransport=dI,Fe.InMemoryTransport=Zs,Fe.QrCode=Nv,Fe.ResourceTemplate=Kk,Fe.UriTemplate=un,Fe.WebMcpClient=uv,Fe.WebMcpServer=eI,Fe.completable=Bk,Fe.createMessageChannelClientTransport=iI,Fe.createMessageChannelPairTransport=rI,Fe.createMessageChannelServerTransport=tI,Fe.createRemoter=rC,Fe.createSSEClientTransport=sI,Fe.createStreamableHTTPClientTransport=oI,Fe.getAISDKTools=wf,Fe.getDisplayName=Xk,Fe.isMcpClient=uI,Fe.isMcpServer=aI,Fe.isMessageChannelClientTransport=cI,Fe.isMessageChannelServerTransport=nI,Fe.isSSEClientTransport=lI,Fe.isStreamableHTTPClientTransport=dv,Fe.z=ES,Object.defineProperty(Fe,Symbol.toStringTag,{value:"Module"})});