@zuplo/runtime 6.70.24 → 6.70.26

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.
@@ -22,14 +22,22 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as ge,H as Dp,I as rc,J as wv,K as jp,L as f,M as Hp,N as ee,O as ae,P as Lp,Q as Bp,R as we,S as C,T as I,U as Ce,V as me,W as nc,X as oc,Y as ce,Z as nt,_ as O,a as ir,aa as Gp,b as qp,ba as ac,ca as Vp,da as Fp,ea as u,fa as ue,j as po,k as Np,q as ec,z as Dt}from"../chunk-RQLHORT4.js";import{d as tc}from"../chunk-GDWI24KD.js";import{a as K}from"../chunk-NW4YQXGC.js";import{X as ln,Y as Or,Z as lo,a as o,c as x,e as Mp}from"../chunk-JAEQKE5H.js";var Po=x(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.regexpCode=te.getEsmExportName=te.getProperty=te.safeStringify=te.stringify=te.strConcat=te.addCodeArg=te.str=te._=te.nil=te._Code=te.Name=te.IDENTIFIER=te._CodeOrName=void 0;var Co=class{static{o(this,"_CodeOrName")}};te._CodeOrName=Co;te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Mr=class extends Co{static{o(this,"Name")}constructor(t){if(super(),!te.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};te.Name=Mr;var ut=class extends Co{static{o(this,"_Code")}constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Mr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};te._Code=ut;te.nil=new ut("");function dm(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Dc(r,t[n]),r.push(e[++n]);return new ut(r)}o(dm,"_");te._=dm;var Nc=new ut("+");function lm(e,...t){let r=[Io(e[0])],n=0;for(;n<t.length;)r.push(Nc),Dc(r,t[n]),r.push(Nc,Io(e[++n]));return Vb(r),new ut(r)}o(lm,"str");te.str=lm;function Dc(e,t){t instanceof ut?e.push(...t._items):t instanceof Mr?e.push(t):e.push(Kb(t))}o(Dc,"addCodeArg");te.addCodeArg=Dc;function Vb(e){let t=1;for(;t<e.length-1;){if(e[t]===Nc){let r=Fb(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(Vb,"optimize");function Fb(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Mr||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Mr))return`"${e}${t.slice(1)}`}o(Fb,"mergeExprItems");function Zb(e,t){return t.emptyStr()?e:e.emptyStr()?t:lm`${e}${t}`}o(Zb,"strConcat");te.strConcat=Zb;function Kb(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Io(Array.isArray(e)?e.join(","):e)}o(Kb,"interpolate");function Wb(e){return new ut(Io(e))}o(Wb,"stringify");te.stringify=Wb;function Io(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(Io,"safeStringify");te.safeStringify=Io;function Jb(e){return typeof e=="string"&&te.IDENTIFIER.test(e)?new ut(`.${e}`):dm`[${e}]`}o(Jb,"getProperty");te.getProperty=Jb;function Yb(e){if(typeof e=="string"&&te.IDENTIFIER.test(e))return new ut(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(Yb,"getEsmExportName");te.getEsmExportName=Yb;function Qb(e){return new ut(e.toString())}o(Qb,"regexpCode");te.regexpCode=Qb});var Lc=x(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.ValueScope=We.ValueScopeName=We.Scope=We.varKinds=We.UsedValueState=void 0;var Ke=Po(),jc=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Xa;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Xa||(We.UsedValueState=Xa={}));We.varKinds={const:new Ke.Name("const"),let:new Ke.Name("let"),var:new Ke.Name("var")};var ei=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ke.Name?t:this.name(t)}name(t){return new Ke.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};We.Scope=ei;var ti=class extends Ke.Name{static{o(this,"ValueScopeName")}constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ke._)`.${new Ke.Name(r)}[${n}]`}};We.ValueScopeName=ti;var Xb=(0,Ke._)`\n`,Hc=class extends ei{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Xb:Ke.nil}}get(){return this._scope}name(t){return new ti(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let a=this.toName(t),{prefix:i}=a,s=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[i];if(c){let l=c.get(s);if(l)return l}else c=this._values[i]=new Map;c.set(s,a);let d=this._scope[i]||(this._scope[i]=[]),p=d.length;return d[p]=r.ref,a.setValue(r,{property:i,itemIndex:p}),a}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ke._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,a=>{if(a.value===void 0)throw new Error(`CodeGen: name "${a}" has no value`);return a.value.code},r,n)}_reduceValues(t,r,n={},a){let i=Ke.nil;for(let s in t){let c=t[s];if(!c)continue;let d=n[s]=n[s]||new Map;c.forEach(p=>{if(d.has(p))return;d.set(p,Xa.Started);let l=r(p);if(l){let m=this.opts.es5?We.varKinds.var:We.varKinds.const;i=(0,Ke._)`${i}${m} ${p} = ${l};${this.opts._n}`}else if(l=a?.(p))i=(0,Ke._)`${i}${l}${this.opts._n}`;else throw new jc(p);d.set(p,Xa.Completed)})}return i}};We.ValueScope=Hc});var F=x(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.or=Z.and=Z.not=Z.CodeGen=Z.operators=Z.varKinds=Z.ValueScopeName=Z.ValueScope=Z.Scope=Z.Name=Z.regexpCode=Z.stringify=Z.getProperty=Z.nil=Z.strConcat=Z.str=Z._=void 0;var Y=Po(),_t=Lc(),hr=Po();Object.defineProperty(Z,"_",{enumerable:!0,get:o(function(){return hr._},"get")});Object.defineProperty(Z,"str",{enumerable:!0,get:o(function(){return hr.str},"get")});Object.defineProperty(Z,"strConcat",{enumerable:!0,get:o(function(){return hr.strConcat},"get")});Object.defineProperty(Z,"nil",{enumerable:!0,get:o(function(){return hr.nil},"get")});Object.defineProperty(Z,"getProperty",{enumerable:!0,get:o(function(){return hr.getProperty},"get")});Object.defineProperty(Z,"stringify",{enumerable:!0,get:o(function(){return hr.stringify},"get")});Object.defineProperty(Z,"regexpCode",{enumerable:!0,get:o(function(){return hr.regexpCode},"get")});Object.defineProperty(Z,"Name",{enumerable:!0,get:o(function(){return hr.Name},"get")});var ai=Lc();Object.defineProperty(Z,"Scope",{enumerable:!0,get:o(function(){return ai.Scope},"get")});Object.defineProperty(Z,"ValueScope",{enumerable:!0,get:o(function(){return ai.ValueScope},"get")});Object.defineProperty(Z,"ValueScopeName",{enumerable:!0,get:o(function(){return ai.ValueScopeName},"get")});Object.defineProperty(Z,"varKinds",{enumerable:!0,get:o(function(){return ai.varKinds},"get")});Z.operators={GT:new Y._Code(">"),GTE:new Y._Code(">="),LT:new Y._Code("<"),LTE:new Y._Code("<="),EQ:new Y._Code("==="),NEQ:new Y._Code("!=="),NOT:new Y._Code("!"),OR:new Y._Code("||"),AND:new Y._Code("&&"),ADD:new Y._Code("+")};var Bt=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},Bc=class extends Bt{static{o(this,"Def")}constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?_t.varKinds.var:this.varKind,a=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${a};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=_n(this.rhs,t,r)),this}get names(){return this.rhs instanceof Y._CodeOrName?this.rhs.names:{}}},ri=class extends Bt{static{o(this,"Assign")}constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof Y.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=_n(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Y.Name?{}:{...this.lhs.names};return oi(t,this.rhs)}},Gc=class extends ri{static{o(this,"AssignOp")}constructor(t,r,n,a){super(t,n,a),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Vc=class extends Bt{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Fc=class extends Bt{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Zc=class extends Bt{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Kc=class extends Bt{static{o(this,"AnyCode")}constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=_n(this.code,t,r),this}get names(){return this.code instanceof Y._CodeOrName?this.code.names:{}}},xo=class extends Bt{static{o(this,"ParentNode")}constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,a=n.length;for(;a--;){let i=n[a];i.optimizeNames(t,r)||(eR(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Dr(t,r.names),{})}},Gt=class extends xo{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Wc=class extends xo{static{o(this,"Root")}},Sn=class extends Gt{static{o(this,"Else")}};Sn.kind="else";var qr=class e extends Gt{static{o(this,"If")}constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Sn(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(pm(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=_n(this.condition,t,r),this}get names(){let t=super.names;return oi(t,this.condition),this.else&&Dr(t,this.else.names),t}};qr.kind="if";var Nr=class extends Gt{static{o(this,"For")}};Nr.kind="for";var Jc=class extends Nr{static{o(this,"ForLoop")}constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=_n(this.iteration,t,r),this}get names(){return Dr(super.names,this.iteration.names)}},Yc=class extends Nr{static{o(this,"ForRange")}constructor(t,r,n,a){super(),this.varKind=t,this.name=r,this.from=n,this.to=a}render(t){let r=t.es5?_t.varKinds.var:this.varKind,{name:n,from:a,to:i}=this;return`for(${r} ${n}=${a}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=oi(super.names,this.from);return oi(t,this.to)}},ni=class extends Nr{static{o(this,"ForIter")}constructor(t,r,n,a){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=a}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=_n(this.iterable,t,r),this}get names(){return Dr(super.names,this.iterable.names)}},Ao=class extends Gt{static{o(this,"Func")}constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Ao.kind="func";var ko=class extends xo{static{o(this,"Return")}render(t){return"return "+super.render(t)}};ko.kind="return";var Qc=class extends Gt{static{o(this,"Try")}render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,a;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(a=this.finally)===null||a===void 0||a.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Dr(t,this.catch.names),this.finally&&Dr(t,this.finally.names),t}},To=class extends Gt{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};To.kind="catch";var Eo=class extends Gt{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};Eo.kind="finally";var Xc=class{static{o(this,"CodeGen")}constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
26
- `:""},this._extScope=t,this._scope=new _t.Scope({parent:t}),this._nodes=[new Wc]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,a){let i=this._scope.toName(r);return n!==void 0&&a&&(this._constants[i.str]=n),this._leafNode(new Bc(t,i,n)),i}const(t,r,n){return this._def(_t.varKinds.const,t,r,n)}let(t,r,n){return this._def(_t.varKinds.let,t,r,n)}var(t,r,n){return this._def(_t.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new ri(t,r,n))}add(t,r){return this._leafNode(new Gc(t,Z.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Y.nil&&this._leafNode(new Kc(t)),this}object(...t){let r=["{"];for(let[n,a]of t)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0,Y.addCodeArg)(r,a));return r.push("}"),new Y._Code(r)}if(t,r,n){if(this._blockNode(new qr(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new qr(t))}else(){return this._elseNode(new Sn)}endIf(){return this._endBlockNode(qr,Sn)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Jc(t),r)}forRange(t,r,n,a,i=this.opts.es5?_t.varKinds.var:_t.varKinds.let){let s=this._scope.toName(t);return this._for(new Yc(i,s,r,n),()=>a(s))}forOf(t,r,n,a=_t.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof Y.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Y._)`${s}.length`,c=>{this.var(i,(0,Y._)`${s}[${c}]`),n(i)})}return this._for(new ni("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?_t.varKinds.var:_t.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Y._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new ni("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(Nr)}label(t){return this._leafNode(new Vc(t))}break(t){return this._leafNode(new Fc(t))}return(t){let r=new ko;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ko)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new Qc;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new To(i),r(i)}return n&&(this._currNode=a.finally=new Eo,this.code(n)),this._endBlockNode(To,Eo)}throw(t){return this._leafNode(new Zc(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=Y.nil,n,a){return this._blockNode(new Ao(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(Ao)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof qr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};Z.CodeGen=Xc;function Dr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(Dr,"addNames");function oi(e,t){return t instanceof Y._CodeOrName?Dr(e,t.names):e}o(oi,"addExprNames");function _n(e,t,r){if(e instanceof Y.Name)return n(e);if(!a(e))return e;return new Y._Code(e._items.reduce((i,s)=>(s instanceof Y.Name&&(s=n(s)),s instanceof Y._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function a(i){return i instanceof Y._Code&&i._items.some(s=>s instanceof Y.Name&&t[s.str]===1&&r[s.str]!==void 0)}}o(_n,"optimizeExpr");function eR(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(eR,"subtractNames");function pm(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Y._)`!${eu(e)}`}o(pm,"not");Z.not=pm;var tR=mm(Z.operators.AND);function rR(...e){return e.reduce(tR)}o(rR,"and");Z.and=rR;var nR=mm(Z.operators.OR);function oR(...e){return e.reduce(nR)}o(oR,"or");Z.or=oR;function mm(e){return(t,r)=>t===Y.nil?r:r===Y.nil?t:(0,Y._)`${eu(t)} ${e} ${eu(r)}`}o(mm,"mappend");function eu(e){return e instanceof Y.Name?e:(0,Y._)`(${e})`}o(eu,"par")});var re=x(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var ie=F(),aR=Po();function iR(e){let t={};for(let r of e)t[r]=!0;return t}o(iR,"toHash");W.toHash=iR;function sR(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(gm(e,t),!ym(t,e.self.RULES.all))}o(sR,"alwaysValidSchema");W.alwaysValidSchema=sR;function gm(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let a=n.RULES.keywords;for(let i in t)a[i]||wm(e,`unknown keyword: "${i}"`)}o(gm,"checkUnknownRules");W.checkUnknownRules=gm;function ym(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(ym,"schemaHasRules");W.schemaHasRules=ym;function cR(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(cR,"schemaHasRulesButRef");W.schemaHasRulesButRef=cR;function uR({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ie._)`${r}`}return(0,ie._)`${e}${t}${(0,ie.getProperty)(n)}`}o(uR,"schemaRefOrVal");W.schemaRefOrVal=uR;function dR(e){return Sm(decodeURIComponent(e))}o(dR,"unescapeFragment");W.unescapeFragment=dR;function lR(e){return encodeURIComponent(ru(e))}o(lR,"escapeFragment");W.escapeFragment=lR;function ru(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(ru,"escapeJsonPointer");W.escapeJsonPointer=ru;function Sm(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(Sm,"unescapeJsonPointer");W.unescapeJsonPointer=Sm;function pR(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o(pR,"eachItem");W.eachItem=pR;function fm({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,s,c)=>{let d=s===void 0?i:s instanceof ie.Name?(i instanceof ie.Name?e(a,i,s):t(a,i,s),s):i instanceof ie.Name?(t(a,s,i),i):r(i,s);return c===ie.Name&&!(d instanceof ie.Name)?n(a,d):d}}o(fm,"makeMergeEvaluated");W.mergeEvaluated={props:fm({mergeNames:o((e,t,r)=>e.if((0,ie._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,ie._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,ie._)`${r} || {}`).code((0,ie._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,ie._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,ie._)`${r} || {}`),nu(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:_m}),items:fm({mergeNames:o((e,t,r)=>e.if((0,ie._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,ie._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,ie._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,ie._)`${r} > ${t} ? ${r} : ${t}`)),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:Math.max(e,t),"mergeValues"),resultToName:o((e,t)=>e.var("items",t),"resultToName")})};function _m(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,ie._)`{}`);return t!==void 0&&nu(e,r,t),r}o(_m,"evaluatedPropsToName");W.evaluatedPropsToName=_m;function nu(e,t,r){Object.keys(r).forEach(n=>e.assign((0,ie._)`${t}${(0,ie.getProperty)(n)}`,!0))}o(nu,"setEvaluated");W.setEvaluated=nu;var hm={};function mR(e,t){return e.scopeValue("func",{ref:t,code:hm[t.code]||(hm[t.code]=new aR._Code(t.code))})}o(mR,"useFunc");W.useFunc=mR;var tu;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(tu||(W.Type=tu={}));function fR(e,t,r){if(e instanceof ie.Name){let n=t===tu.Num;return r?n?(0,ie._)`"[" + ${e} + "]"`:(0,ie._)`"['" + ${e} + "']"`:n?(0,ie._)`"/" + ${e}`:(0,ie._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ie.getProperty)(e).toString():"/"+ru(e)}o(fR,"getErrorPath");W.getErrorPath=fR;function wm(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}o(wm,"checkStrictMode");W.checkStrictMode=wm});var Vt=x(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var Ne=F(),hR={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};ou.default=hR});var Uo=x(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.extendErrors=De.resetErrorsCount=De.reportExtraError=De.reportError=De.keyword$DataError=De.keywordError=void 0;var X=F(),ii=re(),Ve=Vt();De.keywordError={message:o(({keyword:e})=>(0,X.str)`must pass "${e}" keyword validation`,"message")};De.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,X.str)`"${e}" keyword must be ${t} ($data)`:(0,X.str)`"${e}" keyword is invalid ($data)`,"message")};function gR(e,t=De.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:s,allErrors:c}=a,d=Rm(e,t,r);n??(s||c)?vm(i,d):bm(a,(0,X._)`[${d}]`)}o(gR,"reportError");De.reportError=gR;function yR(e,t=De.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:s}=n,c=Rm(e,t,r);vm(a,c),i||s||bm(n,Ve.default.vErrors)}o(yR,"reportExtraError");De.reportExtraError=yR;function SR(e,t){e.assign(Ve.default.errors,t),e.if((0,X._)`${Ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,X._)`${Ve.default.vErrors}.length`,t),()=>e.assign(Ve.default.vErrors,null)))}o(SR,"resetErrorsCount");De.resetErrorsCount=SR;function _R({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:i}){if(a===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",a,Ve.default.errors,c=>{e.const(s,(0,X._)`${Ve.default.vErrors}[${c}]`),e.if((0,X._)`${s}.instancePath === undefined`,()=>e.assign((0,X._)`${s}.instancePath`,(0,X.strConcat)(Ve.default.instancePath,i.errorPath))),e.assign((0,X._)`${s}.schemaPath`,(0,X.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,X._)`${s}.schema`,r),e.assign((0,X._)`${s}.data`,n))})}o(_R,"extendErrors");De.extendErrors=_R;function vm(e,t){let r=e.const("err",t);e.if((0,X._)`${Ve.default.vErrors} === null`,()=>e.assign(Ve.default.vErrors,(0,X._)`[${r}]`),(0,X._)`${Ve.default.vErrors}.push(${r})`),e.code((0,X._)`${Ve.default.errors}++`)}o(vm,"addError");function bm(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,X._)`new ${e.ValidationError}(${t})`):(r.assign((0,X._)`${n}.errors`,t),r.return(!1))}o(bm,"returnErrors");var jr={keyword:new X.Name("keyword"),schemaPath:new X.Name("schemaPath"),params:new X.Name("params"),propertyName:new X.Name("propertyName"),message:new X.Name("message"),schema:new X.Name("schema"),parentSchema:new X.Name("parentSchema")};function Rm(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,X._)`{}`:wR(e,t,r)}o(Rm,"errorObjectCode");function wR(e,t,r={}){let{gen:n,it:a}=e,i=[vR(a,r),bR(e,r)];return RR(e,t,i),n.object(...i)}o(wR,"errorObject");function vR({errorPath:e},{instancePath:t}){let r=t?(0,X.str)`${e}${(0,ii.getErrorPath)(t,ii.Type.Str)}`:e;return[Ve.default.instancePath,(0,X.strConcat)(Ve.default.instancePath,r)]}o(vR,"errorInstancePath");function bR({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,X.str)`${t}/${e}`;return r&&(a=(0,X.str)`${a}${(0,ii.getErrorPath)(r,ii.Type.Str)}`),[jr.schemaPath,a]}o(bR,"errorSchemaPath");function RR(e,{params:t,message:r},n){let{keyword:a,data:i,schemaValue:s,it:c}=e,{opts:d,propertyName:p,topSchemaRef:l,schemaPath:m}=c;n.push([jr.keyword,a],[jr.params,typeof t=="function"?t(e):t||(0,X._)`{}`]),d.messages&&n.push([jr.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([jr.schema,s],[jr.parentSchema,(0,X._)`${l}${m}`],[Ve.default.data,i]),p&&n.push([jr.propertyName,p])}o(RR,"extraErrorProps")});var Im=x(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.boolOrEmptySchema=wn.topBoolOrEmptySchema=void 0;var CR=Uo(),IR=F(),PR=Vt(),xR={message:"boolean schema is false"};function AR(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Cm(e,!1):typeof r=="object"&&r.$async===!0?t.return(PR.default.data):(t.assign((0,IR._)`${n}.errors`,null),t.return(!0))}o(AR,"topBoolOrEmptySchema");wn.topBoolOrEmptySchema=AR;function kR(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Cm(e)):r.var(t,!0)}o(kR,"boolOrEmptySchema");wn.boolOrEmptySchema=kR;function Cm(e,t){let{gen:r,data:n}=e,a={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,CR.reportError)(a,xR,void 0,t)}o(Cm,"falseSchemaError")});var au=x(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.getRules=vn.isJSONType=void 0;var TR=["string","number","integer","boolean","null","object","array"],ER=new Set(TR);function UR(e){return typeof e=="string"&&ER.has(e)}o(UR,"isJSONType");vn.isJSONType=UR;function OR(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}o(OR,"getRules");vn.getRules=OR});var iu=x(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.shouldUseRule=gr.shouldUseGroup=gr.schemaHasRulesForType=void 0;function $R({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Pm(e,n)}o($R,"schemaHasRulesForType");gr.schemaHasRulesForType=$R;function Pm(e,t){return t.rules.some(r=>xm(e,r))}o(Pm,"shouldUseGroup");gr.shouldUseGroup=Pm;function xm(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}o(xm,"shouldUseRule");gr.shouldUseRule=xm});var Oo=x(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;var zR=au(),MR=iu(),qR=Uo(),V=F(),Am=re(),bn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(bn||(je.DataType=bn={}));function NR(e){let t=km(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}o(NR,"getSchemaTypes");je.getSchemaTypes=NR;function km(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(zR.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(km,"getJSONTypes");je.getJSONTypes=km;function DR(e,t){let{gen:r,data:n,opts:a}=e,i=jR(t,a.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,MR.schemaHasRulesForType)(e,t[0]));if(s){let c=cu(t,n,a.strictNumbers,bn.Wrong);r.if(c,()=>{i.length?HR(e,t,i):uu(e)})}return s}o(DR,"coerceAndCheckDataType");je.coerceAndCheckDataType=DR;var Tm=new Set(["string","number","integer","boolean","null"]);function jR(e,t){return t?e.filter(r=>Tm.has(r)||t==="array"&&r==="array"):[]}o(jR,"coerceToTypes");function HR(e,t,r){let{gen:n,data:a,opts:i}=e,s=n.let("dataType",(0,V._)`typeof ${a}`),c=n.let("coerced",(0,V._)`undefined`);i.coerceTypes==="array"&&n.if((0,V._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,V._)`${a}[0]`).assign(s,(0,V._)`typeof ${a}`).if(cu(t,a,i.strictNumbers),()=>n.assign(c,a))),n.if((0,V._)`${c} !== undefined`);for(let p of r)(Tm.has(p)||p==="array"&&i.coerceTypes==="array")&&d(p);n.else(),uu(e),n.endIf(),n.if((0,V._)`${c} !== undefined`,()=>{n.assign(a,c),LR(e,c)});function d(p){switch(p){case"string":n.elseIf((0,V._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,V._)`"" + ${a}`).elseIf((0,V._)`${a} === null`).assign(c,(0,V._)`""`);return;case"number":n.elseIf((0,V._)`${s} == "boolean" || ${a} === null
27
- || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,V._)`+${a}`);return;case"integer":n.elseIf((0,V._)`${s} === "boolean" || ${a} === null
28
- || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,V._)`+${a}`);return;case"boolean":n.elseIf((0,V._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,V._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case"null":n.elseIf((0,V._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(c,null);return;case"array":n.elseIf((0,V._)`${s} === "string" || ${s} === "number"
29
- || ${s} === "boolean" || ${a} === null`).assign(c,(0,V._)`[${a}]`)}}o(d,"coerceSpecificType")}o(HR,"coerceData");function LR({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,V._)`${t} !== undefined`,()=>e.assign((0,V._)`${t}[${r}]`,n))}o(LR,"assignParentData");function su(e,t,r,n=bn.Correct){let a=n===bn.Correct?V.operators.EQ:V.operators.NEQ,i;switch(e){case"null":return(0,V._)`${t} ${a} null`;case"array":i=(0,V._)`Array.isArray(${t})`;break;case"object":i=(0,V._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,V._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,V._)`typeof ${t} ${a} ${e}`}return n===bn.Correct?i:(0,V.not)(i);function s(c=V.nil){return(0,V.and)((0,V._)`typeof ${t} == "number"`,c,r?(0,V._)`isFinite(${t})`:V.nil)}}o(su,"checkDataType");je.checkDataType=su;function cu(e,t,r,n){if(e.length===1)return su(e[0],t,r,n);let a,i=(0,Am.toHash)(e);if(i.array&&i.object){let s=(0,V._)`typeof ${t} != "object"`;a=i.null?s:(0,V._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else a=V.nil;i.number&&delete i.integer;for(let s in i)a=(0,V.and)(a,su(s,t,r,n));return a}o(cu,"checkDataTypes");je.checkDataTypes=cu;var BR={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,V._)`{type: ${e}}`:(0,V._)`{type: ${t}}`,"params")};function uu(e){let t=GR(e);(0,qR.reportError)(t,BR)}o(uu,"reportTypeError");je.reportTypeError=uu;function GR(e){let{gen:t,data:r,schema:n}=e,a=(0,Am.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o(GR,"getTypeErrorContext")});var Um=x(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.assignDefaults=void 0;var Rn=F(),VR=re();function FR(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)Em(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>Em(e,i,a.default))}o(FR,"assignDefaults");si.assignDefaults=FR;function Em(e,t,r){let{gen:n,compositeRule:a,data:i,opts:s}=e;if(r===void 0)return;let c=(0,Rn._)`${i}${(0,Rn.getProperty)(t)}`;if(a){(0,VR.checkStrictMode)(e,`default is ignored for: ${c}`);return}let d=(0,Rn._)`${c} === undefined`;s.useDefaults==="empty"&&(d=(0,Rn._)`${d} || ${c} === null || ${c} === ""`),n.if(d,(0,Rn._)`${c} = ${(0,Rn.stringify)(r)}`)}o(Em,"assignDefault")});var dt=x(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.validateUnion=oe.validateArray=oe.usePattern=oe.callValidateCode=oe.schemaProperties=oe.allSchemaProperties=oe.noPropertyInData=oe.propertyInData=oe.isOwnProperty=oe.hasPropFunc=oe.reportMissingProp=oe.checkMissingProp=oe.checkReportMissingProp=void 0;var de=F(),du=re(),yr=Vt(),ZR=re();function KR(e,t){let{gen:r,data:n,it:a}=e;r.if(pu(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,de._)`${t}`},!0),e.error()})}o(KR,"checkReportMissingProp");oe.checkReportMissingProp=KR;function WR({gen:e,data:t,it:{opts:r}},n,a){return(0,de.or)(...n.map(i=>(0,de.and)(pu(e,t,i,r.ownProperties),(0,de._)`${a} = ${i}`)))}o(WR,"checkMissingProp");oe.checkMissingProp=WR;function JR(e,t){e.setParams({missingProperty:t},!0),e.error()}o(JR,"reportMissingProp");oe.reportMissingProp=JR;function Om(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}o(Om,"hasPropFunc");oe.hasPropFunc=Om;function lu(e,t,r){return(0,de._)`${Om(e)}.call(${t}, ${r})`}o(lu,"isOwnProperty");oe.isOwnProperty=lu;function YR(e,t,r,n){let a=(0,de._)`${t}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${a} && ${lu(e,t,r)}`:a}o(YR,"propertyInData");oe.propertyInData=YR;function pu(e,t,r,n){let a=(0,de._)`${t}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(a,(0,de.not)(lu(e,t,r))):a}o(pu,"noPropertyInData");oe.noPropertyInData=pu;function $m(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o($m,"allSchemaProperties");oe.allSchemaProperties=$m;function QR(e,t){return $m(t).filter(r=>!(0,du.alwaysValidSchema)(e,t[r]))}o(QR,"schemaProperties");oe.schemaProperties=QR;function XR({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:s},c,d,p){let l=p?(0,de._)`${e}, ${t}, ${n}${a}`:t,m=[[yr.default.instancePath,(0,de.strConcat)(yr.default.instancePath,i)],[yr.default.parentData,s.parentData],[yr.default.parentDataProperty,s.parentDataProperty],[yr.default.rootData,yr.default.rootData]];s.opts.dynamicRef&&m.push([yr.default.dynamicAnchors,yr.default.dynamicAnchors]);let h=(0,de._)`${l}, ${r.object(...m)}`;return d!==de.nil?(0,de._)`${c}.call(${d}, ${h})`:(0,de._)`${c}(${h})`}o(XR,"callValidateCode");oe.callValidateCode=XR;var eC=(0,de._)`new RegExp`;function tC({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,i=a(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,de._)`${a.code==="new RegExp"?eC:(0,ZR.useFunc)(e,a)}(${r}, ${n})`})}o(tC,"usePattern");oe.usePattern=tC;function rC(e){let{gen:t,data:r,keyword:n,it:a}=e,i=t.name("valid");if(a.allErrors){let c=t.let("valid",!0);return s(()=>t.assign(c,!1)),c}return t.var(i,!0),s(()=>t.break()),i;function s(c){let d=t.const("len",(0,de._)`${r}.length`);t.forRange("i",0,d,p=>{e.subschema({keyword:n,dataProp:p,dataPropType:du.Type.Num},i),t.if((0,de.not)(i),c)})}o(s,"validateItems")}o(rC,"validateArray");oe.validateArray=rC;function nC(e){let{gen:t,schema:r,keyword:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(d=>(0,du.alwaysValidSchema)(a,d))&&!a.opts.unevaluated)return;let s=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((d,p)=>{let l=e.subschema({keyword:n,schemaProp:p,compositeRule:!0},c);t.assign(s,(0,de._)`${s} || ${c}`),e.mergeValidEvaluated(l,c)||t.if((0,de.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}o(nC,"validateUnion");oe.validateUnion=nC});var qm=x(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.validateKeywordUsage=Pt.validSchemaType=Pt.funcKeywordCode=Pt.macroKeywordCode=void 0;var Fe=F(),Hr=Vt(),oC=dt(),aC=Uo();function iC(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:s}=e,c=t.macro.call(s.self,a,i,s),d=Mm(r,n,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let p=r.name("valid");e.subschema({schema:c,schemaPath:Fe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},p),e.pass(p,()=>e.error(!0))}o(iC,"macroKeywordCode");Pt.macroKeywordCode=iC;function sC(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:s,$data:c,it:d}=e;uC(d,t);let p=!c&&t.compile?t.compile.call(d.self,i,s,d):t.validate,l=Mm(n,a,p),m=n.let("valid");e.block$data(m,h),e.ok((r=t.valid)!==null&&r!==void 0?r:m);function h(){if(t.errors===!1)S(),t.modifying&&zm(e),w(()=>e.error());else{let v=t.async?y():_();t.modifying&&zm(e),w(()=>cC(e,v))}}o(h,"validateKeyword");function y(){let v=n.let("ruleErrs",null);return n.try(()=>S((0,Fe._)`await `),b=>n.assign(m,!1).if((0,Fe._)`${b} instanceof ${d.ValidationError}`,()=>n.assign(v,(0,Fe._)`${b}.errors`),()=>n.throw(b))),v}o(y,"validateAsync");function _(){let v=(0,Fe._)`${l}.errors`;return n.assign(v,null),S(Fe.nil),v}o(_,"validateSync");function S(v=t.async?(0,Fe._)`await `:Fe.nil){let b=d.opts.passContext?Hr.default.this:Hr.default.self,R=!("compile"in t&&!c||t.schema===!1);n.assign(m,(0,Fe._)`${v}${(0,oC.callValidateCode)(e,l,b,R)}`,t.modifying)}o(S,"assignValid");function w(v){var b;n.if((0,Fe.not)((b=t.valid)!==null&&b!==void 0?b:m),v)}o(w,"reportErrs")}o(sC,"funcKeywordCode");Pt.funcKeywordCode=sC;function zm(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Fe._)`${n.parentData}[${n.parentDataProperty}]`))}o(zm,"modifyData");function cC(e,t){let{gen:r}=e;r.if((0,Fe._)`Array.isArray(${t})`,()=>{r.assign(Hr.default.vErrors,(0,Fe._)`${Hr.default.vErrors} === null ? ${t} : ${Hr.default.vErrors}.concat(${t})`).assign(Hr.default.errors,(0,Fe._)`${Hr.default.vErrors}.length`),(0,aC.extendErrors)(e)},()=>e.error())}o(cC,"addErrs");function uC({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o(uC,"checkAsyncKeyword");function Mm(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Fe.stringify)(r)})}o(Mm,"useKeyword");function dC(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}o(dC,"validSchemaType");Pt.validSchemaType=dC;function lC({schema:e,opts:t,self:r,errSchemaPath:n},a,i){if(Array.isArray(a.keyword)?!a.keyword.includes(i):a.keyword!==i)throw new Error("ajv implementation error");let s=a.dependencies;if(s?.some(c=>!Object.prototype.hasOwnProperty.call(e,c)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(a.validateSchema&&!a.validateSchema(e[i])){let d=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(a.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(d);else throw new Error(d)}}o(lC,"validateKeywordUsage");Pt.validateKeywordUsage=lC});var Dm=x(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.extendSubschemaMode=Sr.extendSubschemaData=Sr.getSubschema=void 0;var xt=F(),Nm=re();function pC(e,{keyword:t,schemaProp:r,schema:n,schemaPath:a,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let c=e.schema[t];return r===void 0?{schema:c,schemaPath:(0,xt._)`${e.schemaPath}${(0,xt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,xt._)`${e.schemaPath}${(0,xt.getProperty)(t)}${(0,xt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Nm.escapeFragment)(r)}`}}if(n!==void 0){if(a===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:a,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}o(pC,"getSubschema");Sr.getSubschema=pC;function mC(e,t,{dataProp:r,dataPropType:n,data:a,dataTypes:i,propertyName:s}){if(a!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=t;if(r!==void 0){let{errorPath:p,dataPathArr:l,opts:m}=t,h=c.let("data",(0,xt._)`${t.data}${(0,xt.getProperty)(r)}`,!0);d(h),e.errorPath=(0,xt.str)`${p}${(0,Nm.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,xt._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let p=a instanceof xt.Name?a:c.let("data",a,!0);d(p),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function d(p){e.data=p,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,p]}o(d,"dataContextProps")}o(mC,"extendSubschemaData");Sr.extendSubschemaData=mC;function fC(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:i}){n!==void 0&&(e.compositeRule=n),a!==void 0&&(e.createErrors=a),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}o(fC,"extendSubschemaMode");Sr.extendSubschemaMode=fC});var mu=x((xH,jm)=>{"use strict";jm.exports=o(function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!e(t[a],r[a]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;a--!==0;){var s=i[a];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r},"equal")});var Lm=x((kH,Hm)=>{"use strict";var _r=Hm.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},a=r.post||function(){};ci(t,n,a,e,"",e)};_r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};_r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};_r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};_r.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 ci(e,t,r,n,a,i,s,c,d,p){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,a,i,s,c,d,p);for(var l in n){var m=n[l];if(Array.isArray(m)){if(l in _r.arrayKeywords)for(var h=0;h<m.length;h++)ci(e,t,r,m[h],a+"/"+l+"/"+h,i,a,l,n,h)}else if(l in _r.propsKeywords){if(m&&typeof m=="object")for(var y in m)ci(e,t,r,m[y],a+"/"+l+"/"+hC(y),i,a,l,n,y)}else(l in _r.keywords||e.allKeys&&!(l in _r.skipKeywords))&&ci(e,t,r,m,a+"/"+l,i,a,l,n)}r(n,a,i,s,c,d,p)}}o(ci,"_traverse");function hC(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(hC,"escapeJsonPtr")});var $o=x(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.getSchemaRefs=Je.resolveUrl=Je.normalizeId=Je._getFullPath=Je.getFullPath=Je.inlineRef=void 0;var gC=re(),yC=mu(),SC=Lm(),_C=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function wC(e,t=!0){return typeof e=="boolean"?!0:t===!0?!fu(e):t?Bm(e)<=t:!1}o(wC,"inlineRef");Je.inlineRef=wC;var vC=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function fu(e){for(let t in e){if(vC.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(fu)||typeof r=="object"&&fu(r))return!0}return!1}o(fu,"hasRef");function Bm(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!_C.has(r)&&(typeof e[r]=="object"&&(0,gC.eachItem)(e[r],n=>t+=Bm(n)),t===1/0))return 1/0}return t}o(Bm,"countKeys");function Gm(e,t="",r){r!==!1&&(t=Cn(t));let n=e.parse(t);return Vm(e,n)}o(Gm,"getFullPath");Je.getFullPath=Gm;function Vm(e,t){return e.serialize(t).split("#")[0]+"#"}o(Vm,"_getFullPath");Je._getFullPath=Vm;var bC=/#\/?$/;function Cn(e){return e?e.replace(bC,""):""}o(Cn,"normalizeId");Je.normalizeId=Cn;function RC(e,t,r){return r=Cn(r),e.resolve(t,r)}o(RC,"resolveUrl");Je.resolveUrl=RC;var CC=/^[a-z_][-a-z0-9._]*$/i;function IC(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=Cn(e[r]||t),i={"":a},s=Gm(n,a,!1),c={},d=new Set;return SC(e,{allKeys:!0},(m,h,y,_)=>{if(_===void 0)return;let S=s+h,w=i[_];typeof m[r]=="string"&&(w=v.call(this,m[r])),b.call(this,m.$anchor),b.call(this,m.$dynamicAnchor),i[h]=w;function v(R){let q=this.opts.uriResolver.resolve;if(R=Cn(w?q(w,R):R),d.has(R))throw l(R);d.add(R);let N=this.refs[R];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?p(m,N.schema,R):R!==Cn(S)&&(R[0]==="#"?(p(m,c[R],R),c[R]=m):this.refs[R]=S),R}o(v,"addRef");function b(R){if(typeof R=="string"){if(!CC.test(R))throw new Error(`invalid anchor "${R}"`);v.call(this,`#${R}`)}}o(b,"addAnchor")}),c;function p(m,h,y){if(h!==void 0&&!yC(m,h))throw l(y)}o(p,"checkAmbiguosRef");function l(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(l,"ambiguos")}o(IC,"getSchemaRefs");Je.getSchemaRefs=IC});var qo=x(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.getData=wr.KeywordCxt=wr.validateFunctionCode=void 0;var Jm=Im(),Fm=Oo(),gu=iu(),ui=Oo(),PC=Um(),Mo=qm(),hu=Dm(),$=F(),L=Vt(),xC=$o(),Ft=re(),zo=Uo();function AC(e){if(Xm(e)&&(ef(e),Qm(e))){EC(e);return}Ym(e,()=>(0,Jm.topBoolOrEmptySchema)(e))}o(AC,"validateFunctionCode");wr.validateFunctionCode=AC;function Ym({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,$._)`${L.default.data}, ${L.default.valCxt}`,n.$async,()=>{e.code((0,$._)`"use strict"; ${Zm(r,a)}`),TC(e,a),e.code(i)}):e.func(t,(0,$._)`${L.default.data}, ${kC(a)}`,n.$async,()=>e.code(Zm(r,a)).code(i))}o(Ym,"validateFunction");function kC(e){return(0,$._)`{${L.default.instancePath}="", ${L.default.parentData}, ${L.default.parentDataProperty}, ${L.default.rootData}=${L.default.data}${e.dynamicRef?(0,$._)`, ${L.default.dynamicAnchors}={}`:$.nil}}={}`}o(kC,"destructureValCxt");function TC(e,t){e.if(L.default.valCxt,()=>{e.var(L.default.instancePath,(0,$._)`${L.default.valCxt}.${L.default.instancePath}`),e.var(L.default.parentData,(0,$._)`${L.default.valCxt}.${L.default.parentData}`),e.var(L.default.parentDataProperty,(0,$._)`${L.default.valCxt}.${L.default.parentDataProperty}`),e.var(L.default.rootData,(0,$._)`${L.default.valCxt}.${L.default.rootData}`),t.dynamicRef&&e.var(L.default.dynamicAnchors,(0,$._)`${L.default.valCxt}.${L.default.dynamicAnchors}`)},()=>{e.var(L.default.instancePath,(0,$._)`""`),e.var(L.default.parentData,(0,$._)`undefined`),e.var(L.default.parentDataProperty,(0,$._)`undefined`),e.var(L.default.rootData,L.default.data),t.dynamicRef&&e.var(L.default.dynamicAnchors,(0,$._)`{}`)})}o(TC,"destructureValCxtES5");function EC(e){let{schema:t,opts:r,gen:n}=e;Ym(e,()=>{r.$comment&&t.$comment&&rf(e),MC(e),n.let(L.default.vErrors,null),n.let(L.default.errors,0),r.unevaluated&&UC(e),tf(e),DC(e)})}o(EC,"topSchemaObjCode");function UC(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,$._)`${r}.evaluated`),t.if((0,$._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,$._)`${e.evaluated}.props`,(0,$._)`undefined`)),t.if((0,$._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,$._)`${e.evaluated}.items`,(0,$._)`undefined`))}o(UC,"resetEvaluated");function Zm(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,$._)`/*# sourceURL=${r} */`:$.nil}o(Zm,"funcSourceUrl");function OC(e,t){if(Xm(e)&&(ef(e),Qm(e))){$C(e,t);return}(0,Jm.boolOrEmptySchema)(e,t)}o(OC,"subschemaCode");function Qm({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}o(Qm,"schemaCxtHasRules");function Xm(e){return typeof e.schema!="boolean"}o(Xm,"isSchemaObj");function $C(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&rf(e),qC(e),NC(e);let i=n.const("_errs",L.default.errors);tf(e,i),n.var(t,(0,$._)`${i} === ${L.default.errors}`)}o($C,"subSchemaObjCode");function ef(e){(0,Ft.checkUnknownRules)(e),zC(e)}o(ef,"checkKeywords");function tf(e,t){if(e.opts.jtd)return Km(e,[],!1,t);let r=(0,Fm.getSchemaTypes)(e.schema),n=(0,Fm.coerceAndCheckDataType)(e,r);Km(e,r,!n,t)}o(tf,"typeAndKeywords");function zC(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Ft.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(zC,"checkRefsAndKeywords");function MC(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ft.checkStrictMode)(e,"default is ignored in the schema root")}o(MC,"checkNoDefault");function qC(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,xC.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o(qC,"updateContext");function NC(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(NC,"checkAsyncSchema");function rf({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,$._)`${L.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let s=(0,$.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,$._)`${L.default.self}.opts.$comment(${i}, ${s}, ${c}.schema)`)}}o(rf,"commentKeyword");function DC(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,$._)`${L.default.errors} === 0`,()=>t.return(L.default.data),()=>t.throw((0,$._)`new ${a}(${L.default.vErrors})`)):(t.assign((0,$._)`${n}.errors`,L.default.vErrors),i.unevaluated&&jC(e),t.return((0,$._)`${L.default.errors} === 0`))}o(DC,"returnResults");function jC({gen:e,evaluated:t,props:r,items:n}){r instanceof $.Name&&e.assign((0,$._)`${t}.props`,r),n instanceof $.Name&&e.assign((0,$._)`${t}.items`,n)}o(jC,"assignEvaluated");function Km(e,t,r,n){let{gen:a,schema:i,data:s,allErrors:c,opts:d,self:p}=e,{RULES:l}=p;if(i.$ref&&(d.ignoreKeywordsWithRef||!(0,Ft.schemaHasRulesButRef)(i,l))){a.block(()=>of(e,"$ref",l.all.$ref.definition));return}d.jtd||HC(e,t),a.block(()=>{for(let h of l.rules)m(h);m(l.post)});function m(h){(0,gu.shouldUseGroup)(i,h)&&(h.type?(a.if((0,ui.checkDataType)(h.type,s,d.strictNumbers)),Wm(e,h),t.length===1&&t[0]===h.type&&r&&(a.else(),(0,ui.reportTypeError)(e)),a.endIf()):Wm(e,h),c||a.if((0,$._)`${L.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(Km,"schemaKeywords");function Wm(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,PC.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,gu.shouldUseRule)(n,i)&&of(e,i.keyword,i.definition,t.type)})}o(Wm,"iterateKeywords");function HC(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(LC(e,t),e.opts.allowUnionTypes||BC(e,t),GC(e,e.dataTypes))}o(HC,"checkStrictTypes");function LC(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{nf(e.dataTypes,r)||yu(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),FC(e,t)}}o(LC,"checkContextTypes");function BC(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&yu(e,"use allowUnionTypes to allow union type keyword")}o(BC,"checkMultipleTypes");function GC(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,gu.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(s=>VC(t,s))&&yu(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}o(GC,"checkKeywordTypes");function VC(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(VC,"hasApplicableType");function nf(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(nf,"includesType");function FC(e,t){let r=[];for(let n of e.dataTypes)nf(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(FC,"narrowSchemaTypes");function yu(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Ft.checkStrictMode)(e,t,e.opts.strictTypes)}o(yu,"strictTypesError");var di=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,Mo.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Ft.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",af(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,Mo.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",L.default.errors))}result(t,r,n){this.failResult((0,$.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,$.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,$._)`${r} !== undefined && (${(0,$.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?zo.reportExtraError:zo.reportError)(this,this.def.error,r)}$dataError(){(0,zo.reportError)(this,this.def.$dataError||zo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,zo.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=$.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=$.nil,r=$.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:s}=this;n.if((0,$.or)((0,$._)`${a} === undefined`,r)),t!==$.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==$.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,$.or)(s(),c());function s(){if(n.length){if(!(r instanceof $.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,$._)`${(0,ui.checkDataTypes)(d,r,i.opts.strictNumbers,ui.DataType.Wrong)}`}return $.nil}function c(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,$._)`!${d}(${r})`}return $.nil}}subschema(t,r){let n=(0,hu.getSubschema)(this.it,t);(0,hu.extendSubschemaData)(n,this.it,t),(0,hu.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return OC(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Ft.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Ft.mergeEvaluated.items(a,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:a}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return a.if(r,()=>this.mergeEvaluated(t,$.Name)),!0}};wr.KeywordCxt=di;function of(e,t,r,n){let a=new di(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,Mo.funcKeywordCode)(a,r):"macro"in r?(0,Mo.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,Mo.funcKeywordCode)(a,r)}o(of,"keywordCode");var ZC=/^\/(?:[^~]|~0|~1)*$/,KC=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function af(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return L.default.rootData;if(e[0]==="/"){if(!ZC.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=L.default.rootData}else{let p=KC.exec(e);if(!p)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+p[1];if(a=p[2],a==="#"){if(l>=t)throw new Error(d("property/index",l));return n[t-l]}if(l>t)throw new Error(d("data",l));if(i=r[t-l],!a)return i}let s=i,c=a.split("/");for(let p of c)p&&(i=(0,$._)`${i}${(0,$.getProperty)((0,Ft.unescapeJsonPointer)(p))}`,s=(0,$._)`${s} && ${i}`);return s;function d(p,l){return`Cannot access ${p} ${l} levels up, current level is ${t}`}}o(af,"getData");wr.getData=af});var li=x(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var Su=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};_u.default=Su});var No=x(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var wu=$o(),vu=class extends Error{static{o(this,"MissingRefError")}constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,wu.resolveUrl)(t,r,n),this.missingSchema=(0,wu.normalizeId)((0,wu.getFullPath)(t,this.missingRef))}};bu.default=vu});var mi=x(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var wt=F(),WC=li(),Lr=Vt(),vt=$o(),sf=re(),JC=qo(),In=class{static{o(this,"SchemaEnv")}constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,vt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};lt.SchemaEnv=In;function Cu(e){let t=cf.call(this,e);if(t)return t;let r=(0,vt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,s=new wt.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),c;e.$async&&(c=s.scopeValue("Error",{ref:WC.default,code:(0,wt._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");e.validateName=d;let p={gen:s,allErrors:this.opts.allErrors,data:Lr.default.data,parentData:Lr.default.parentData,parentDataProperty:Lr.default.parentDataProperty,dataNames:[Lr.default.data],dataPathArr:[wt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,wt.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:wt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,wt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,JC.validateFunctionCode)(p),s.optimize(this.opts.code.optimize);let m=s.toString();l=`${s.scopeRefs(Lr.default.scope)}return ${m}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let y=new Function(`${Lr.default.self}`,`${Lr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{ref:y}),y.errors=null,y.schema=e.schema,y.schemaEnv=e,e.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:d,validateCode:m,scopeValues:s._values}),this.opts.unevaluated){let{props:_,items:S}=p;y.evaluated={props:_ instanceof wt.Name?void 0:_,items:S instanceof wt.Name?void 0:S,dynamicProps:_ instanceof wt.Name,dynamicItems:S instanceof wt.Name},y.source&&(y.source.evaluated=(0,wt.stringify)(y.evaluated))}return e.validate=y,e}catch(m){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),m}finally{this._compilations.delete(e)}}o(Cu,"compileSchema");lt.compileSchema=Cu;function YC(e,t,r){var n;r=(0,vt.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=eI.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;s&&(i=new In({schema:s,schemaId:c,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=QC.call(this,i)}o(YC,"resolveRef");lt.resolveRef=YC;function QC(e){return(0,vt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Cu.call(this,e)}o(QC,"inlineOrCompile");function cf(e){for(let t of this._compilations)if(XC(t,e))return t}o(cf,"getCompilingSchema");lt.getCompilingSchema=cf;function XC(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(XC,"sameSchemaEnv");function eI(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||pi.call(this,e,t)}o(eI,"resolve");function pi(e,t){let r=this.opts.uriResolver.parse(t),n=(0,vt._getFullPath)(this.opts.uriResolver,r),a=(0,vt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return Ru.call(this,r,e);let i=(0,vt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let c=pi.call(this,e,s);return typeof c?.schema!="object"?void 0:Ru.call(this,r,c)}if(typeof s?.schema=="object"){if(s.validate||Cu.call(this,s),i===(0,vt.normalizeId)(t)){let{schema:c}=s,{schemaId:d}=this.opts,p=c[d];return p&&(a=(0,vt.resolveUrl)(this.opts.uriResolver,a,p)),new In({schema:c,schemaId:d,root:e,baseId:a})}return Ru.call(this,r,s)}}o(pi,"resolveSchema");lt.resolveSchema=pi;var tI=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ru(e,{baseId:t,schema:r,root:n}){var a;if(((a=e.fragment)===null||a===void 0?void 0:a[0])!=="/")return;for(let c of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let d=r[(0,sf.unescapeFragment)(c)];if(d===void 0)return;r=d;let p=typeof r=="object"&&r[this.opts.schemaId];!tI.has(c)&&p&&(t=(0,vt.resolveUrl)(this.opts.uriResolver,t,p))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,sf.schemaHasRulesButRef)(r,this.RULES)){let c=(0,vt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=pi.call(this,n,c)}let{schemaId:s}=this.opts;if(i=i||new In({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}o(Ru,"getJsonPointer")});var uf=x((HH,rI)=>{rI.exports={$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 Pu=x((LH,mf)=>{"use strict";var nI=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),lf=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 Iu(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}o(Iu,"stringArrayToHexStripped");var oI=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function df(e){return e.length=0,!0}o(df,"consumeIsZone");function aI(e,t,r){if(e.length){let n=Iu(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(aI,"consumeHextets");function iI(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,s=!1,c=aI;for(let d=0;d<e.length;d++){let p=e[d];if(!(p==="["||p==="]"))if(p===":"){if(i===!0&&(s=!0),!c(a,n,r))break;if(++t>7){r.error=!0;break}d>0&&e[d-1]===":"&&(i=!0),n.push(":");continue}else if(p==="%"){if(!c(a,n,r))break;c=df}else{a.push(p);continue}}return a.length&&(c===df?r.zone=a.join(""):s?n.push(a.join("")):n.push(Iu(a))),r.address=n.join(""),r}o(iI,"getIPV6");function pf(e){if(sI(e,":")<2)return{host:e,isIPV6:!1};let t=iI(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}o(pf,"normalizeIPv6");function sI(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(sI,"findToken");function cI(e){let t=e,r=[],n=-1,a=0;for(;a=t.length;){if(a===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(a===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(a===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}o(cI,"removeDotSegments");function uI(e,t){let r=t!==!0?escape:unescape;return e.scheme!==void 0&&(e.scheme=r(e.scheme)),e.userinfo!==void 0&&(e.userinfo=r(e.userinfo)),e.host!==void 0&&(e.host=r(e.host)),e.path!==void 0&&(e.path=r(e.path)),e.query!==void 0&&(e.query=r(e.query)),e.fragment!==void 0&&(e.fragment=r(e.fragment)),e}o(uI,"normalizeComponentEncoding");function dI(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!lf(r)){let n=pf(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=e.host}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}o(dI,"recomposeAuthority");mf.exports={nonSimpleDomain:oI,recomposeAuthority:dI,normalizeComponentEncoding:uI,removeDotSegments:cI,isIPv4:lf,isUUID:nI,normalizeIPv6:pf,stringArrayToHexStripped:Iu}});var Sf=x((GH,yf)=>{"use strict";var{isUUID:lI}=Pu(),pI=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,mI=["http","https","ws","wss","urn","urn:uuid"];function fI(e){return mI.indexOf(e)!==-1}o(fI,"isValidSchemeName");function xu(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}o(xu,"wsIsSecure");function ff(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(ff,"httpParse");function hf(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}o(hf,"httpSerialize");function hI(e){return e.secure=xu(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(hI,"wsParse");function gI(e){if((e.port===(xu(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}o(gI,"wsSerialize");function yI(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(pI);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let a=`${n}:${t.nid||e.nid}`,i=Au(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(yI,"urnParse");function SI(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=`${r}:${t.nid||n}`,i=Au(a);i&&(e=i.serialize(e,t));let s=e,c=e.nss;return s.path=`${n||t.nid}:${c}`,t.skipEscape=!0,s}o(SI,"urnSerialize");function _I(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!lI(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}o(_I,"urnuuidParse");function wI(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(wI,"urnuuidSerialize");var gf={scheme:"http",domainHost:!0,parse:ff,serialize:hf},vI={scheme:"https",domainHost:gf.domainHost,parse:ff,serialize:hf},fi={scheme:"ws",domainHost:!0,parse:hI,serialize:gI},bI={scheme:"wss",domainHost:fi.domainHost,parse:fi.parse,serialize:fi.serialize},RI={scheme:"urn",parse:yI,serialize:SI,skipNormalize:!0},CI={scheme:"urn:uuid",parse:_I,serialize:wI,skipNormalize:!0},hi={http:gf,https:vI,ws:fi,wss:bI,urn:RI,"urn:uuid":CI};Object.setPrototypeOf(hi,null);function Au(e){return e&&(hi[e]||hi[e.toLowerCase()])||void 0}o(Au,"getSchemeHandler");yf.exports={wsIsSecure:xu,SCHEMES:hi,isValidSchemeName:fI,getSchemeHandler:Au}});var vf=x((FH,yi)=>{"use strict";var{normalizeIPv6:II,removeDotSegments:Do,recomposeAuthority:PI,normalizeComponentEncoding:gi,isIPv4:xI,nonSimpleDomain:AI}=Pu(),{SCHEMES:kI,getSchemeHandler:_f}=Sf();function TI(e,t){return typeof e=="string"?e=At(Zt(e,t),t):typeof e=="object"&&(e=Zt(At(e,t),t)),e}o(TI,"normalize");function EI(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=wf(Zt(e,n),Zt(t,n),n,!0);return n.skipEscape=!0,At(a,n)}o(EI,"resolve");function wf(e,t,r,n){let a={};return n||(e=Zt(At(e,r),r),t=Zt(At(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=Do(t.path||""),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=Do(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=Do(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path="/"+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path,a.path=Do(a.path)),a.query=t.query):(a.path=e.path,t.query!==void 0?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}o(wf,"resolveComponent");function UI(e,t,r){return typeof e=="string"?(e=unescape(e),e=At(gi(Zt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=At(gi(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=At(gi(Zt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=At(gi(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(UI,"equal");function At(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),a=[],i=_f(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&a.push(r.scheme,":");let s=PI(r);if(s!==void 0&&(n.reference!=="suffix"&&a.push("//"),a.push(s),r.path&&r.path[0]!=="/"&&a.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(c=Do(c)),s===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),a.push(c)}return r.query!==void 0&&a.push("?",r.query),r.fragment!==void 0&&a.push("#",r.fragment),a.join("")}o(At,"serialize");var OI=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Zt(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},a=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(OI);if(i){if(n.scheme=i[1],n.userinfo=i[3],n.host=i[4],n.port=parseInt(i[5],10),n.path=i[6]||"",n.query=i[7],n.fragment=i[8],isNaN(n.port)&&(n.port=i[5]),n.host)if(xI(n.host)===!1){let d=II(n.host);n.host=d.host.toLowerCase(),a=d.isIPV6}else a=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=_f(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&a===!1&&AI(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(c){n.error=n.error||"Host's domain name can not be converted to ASCII: "+c}(!s||s&&!s.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}o(Zt,"parse");var ku={SCHEMES:kI,normalize:TI,resolve:EI,resolveComponent:wf,equal:UI,serialize:At,parse:Zt};yi.exports=ku;yi.exports.default=ku;yi.exports.fastUri=ku});var Rf=x(Tu=>{"use strict";Object.defineProperty(Tu,"__esModule",{value:!0});var bf=vf();bf.code='require("ajv/dist/runtime/uri").default';Tu.default=bf});var Ef=x(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.CodeGen=Ee.Name=Ee.nil=Ee.stringify=Ee.str=Ee._=Ee.KeywordCxt=void 0;var $I=qo();Object.defineProperty(Ee,"KeywordCxt",{enumerable:!0,get:o(function(){return $I.KeywordCxt},"get")});var Pn=F();Object.defineProperty(Ee,"_",{enumerable:!0,get:o(function(){return Pn._},"get")});Object.defineProperty(Ee,"str",{enumerable:!0,get:o(function(){return Pn.str},"get")});Object.defineProperty(Ee,"stringify",{enumerable:!0,get:o(function(){return Pn.stringify},"get")});Object.defineProperty(Ee,"nil",{enumerable:!0,get:o(function(){return Pn.nil},"get")});Object.defineProperty(Ee,"Name",{enumerable:!0,get:o(function(){return Pn.Name},"get")});Object.defineProperty(Ee,"CodeGen",{enumerable:!0,get:o(function(){return Pn.CodeGen},"get")});var zI=li(),Af=No(),MI=au(),jo=mi(),qI=F(),Ho=$o(),Si=Oo(),Uu=re(),Cf=uf(),NI=Rf(),kf=o((e,t)=>new RegExp(e,t),"defaultRegExp");kf.code="new RegExp";var DI=["removeAdditional","useDefaults","coerceTypes"],jI=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),HI={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."},LI={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},If=200;function BI(e){var t,r,n,a,i,s,c,d,p,l,m,h,y,_,S,w,v,b,R,q,N,qe,it,dn,ar;let qt=e.strict,Tr=(t=e.code)===null||t===void 0?void 0:t.optimize,oo=Tr===!0||Tr===void 0?1:Tr||0,ao=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:kf,io=(a=e.uriResolver)!==null&&a!==void 0?a:NI.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:qt)!==null&&s!==void 0?s:!0,strictNumbers:(d=(c=e.strictNumbers)!==null&&c!==void 0?c:qt)!==null&&d!==void 0?d:!0,strictTypes:(l=(p=e.strictTypes)!==null&&p!==void 0?p:qt)!==null&&l!==void 0?l:"log",strictTuples:(h=(m=e.strictTuples)!==null&&m!==void 0?m:qt)!==null&&h!==void 0?h:"log",strictRequired:(_=(y=e.strictRequired)!==null&&y!==void 0?y:qt)!==null&&_!==void 0?_:!1,code:e.code?{...e.code,optimize:oo,regExp:ao}:{optimize:oo,regExp:ao},loopRequired:(S=e.loopRequired)!==null&&S!==void 0?S:If,loopEnum:(w=e.loopEnum)!==null&&w!==void 0?w:If,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(R=e.inlineRefs)!==null&&R!==void 0?R:!0,schemaId:(q=e.schemaId)!==null&&q!==void 0?q:"$id",addUsedSchema:(N=e.addUsedSchema)!==null&&N!==void 0?N:!0,validateSchema:(qe=e.validateSchema)!==null&&qe!==void 0?qe:!0,validateFormats:(it=e.validateFormats)!==null&&it!==void 0?it:!0,unicodeRegExp:(dn=e.unicodeRegExp)!==null&&dn!==void 0?dn:!0,int32range:(ar=e.int32range)!==null&&ar!==void 0?ar:!0,uriResolver:io}}o(BI,"requiredOptions");var Lo=class{static{o(this,"Ajv")}constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...BI(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new qI.ValueScope({scope:{},prefixes:jI,es5:r,lines:n}),this.logger=WI(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,MI.getRules)(),Pf.call(this,HI,t,"NOT SUPPORTED"),Pf.call(this,LI,t,"DEPRECATED","warn"),this._metaOpts=ZI.call(this),t.formats&&VI.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&FI.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),GI.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=Cf;n==="id"&&(a={...Cf},a.id=a.$id,delete a.$id),r&&t&&this.addMetaSchema(a,a[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let a=n(r);return"$async"in n||(this.errors=n.errors),a}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return a.call(this,t,r);async function a(l,m){await i.call(this,l.$schema);let h=this._addSchema(l,m);return h.validate||s.call(this,h)}async function i(l){l&&!this.getSchema(l)&&await a.call(this,{$ref:l},!0)}async function s(l){try{return this._compileSchemaEnv(l)}catch(m){if(!(m instanceof Af.default))throw m;return c.call(this,m),await d.call(this,m.missingSchema),s.call(this,l)}}function c({missingSchema:l,missingRef:m}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${m} cannot be resolved`)}async function d(l){let m=await p.call(this,l);this.refs[l]||await i.call(this,m.$schema),this.refs[l]||this.addSchema(m,l,r)}async function p(l){let m=this._loading[l];if(m)return m;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,a=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,a);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Ho.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,a,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$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;let a=this.validate(n,t);if(!a&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return a}getSchema(t){let r;for(;typeof(r=xf.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new jo.SchemaEnv({schema:{},schemaId:n});if(r=jo.resolveSchema.call(this,a,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=xf.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,Ho.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.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(YI.call(this,n,r),!r)return(0,Uu.eachItem)(n,i=>Eu.call(this,i)),this;XI.call(this,r);let a={...r,type:(0,Si.getJSONTypes)(r.type),schemaType:(0,Si.getJSONTypes)(r.schemaType)};return(0,Uu.eachItem)(n,a.type.length===0?i=>Eu.call(this,i,a):i=>a.type.forEach(s=>Eu.call(this,i,a,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let a=n.rules.findIndex(i=>i.keyword===t);a>=0&&n.rules.splice(a,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(a=>`${n}${a.instancePath} ${a.message}`).reduce((a,i)=>a+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let i=a.split("/").slice(1),s=t;for(let c of i)s=s[c];for(let c in n){let d=n[c];if(typeof d!="object")continue;let{$data:p}=d.definition,l=s[c];p&&l&&(s[c]=Tf(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let a=t[n];(!r||r.test(n))&&(typeof a=="string"?delete t[n]:a&&!a.meta&&(this._cache.delete(a.schema),delete t[n]))}}_addSchema(t,r,n,a=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:c}=this.opts;if(typeof t=="object")s=t[c];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let d=this._cache.get(t);if(d!==void 0)return d;n=(0,Ho.normalizeId)(s||n);let p=Ho.getSchemaRefs.call(this,t,n);return d=new jo.SchemaEnv({schema:t,schemaId:c,meta:r,baseId:n,localRefs:p}),this._cache.set(d.schema,d),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),a&&this.validateSchema(t,!0),d}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):jo.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{jo.compileSchema.call(this,t)}finally{this.opts=r}}};Lo.ValidationError=zI.default;Lo.MissingRefError=Af.default;Ee.default=Lo;function Pf(e,t,r,n="error"){for(let a in e){let i=a;i in t&&this.logger[n](`${r}: option ${a}. ${e[i]}`)}}o(Pf,"checkOptions");function xf(e){return e=(0,Ho.normalizeId)(e),this.schemas[e]||this.refs[e]}o(xf,"getSchEnv");function GI(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}o(GI,"addInitialSchemas");function VI(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(VI,"addInitialFormats");function FI(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}o(FI,"addInitialKeywords");function ZI(){let e={...this.opts};for(let t of DI)delete e[t];return e}o(ZI,"getMetaSchemaOptions");var KI={log(){},warn(){},error(){}};function WI(e){if(e===!1)return KI;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}o(WI,"getLogger");var JI=/^[a-z_$][a-z0-9_$:-]*$/i;function YI(e,t){let{RULES:r}=this;if((0,Uu.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!JI.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}o(YI,"checkKeyword");function Eu(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=a?i.post:i.rules.find(({type:d})=>d===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,Si.getJSONTypes)(t.type),schemaType:(0,Si.getJSONTypes)(t.schemaType)}};t.before?QI.call(this,s,c,t.before):s.rules.push(c),i.all[e]=c,(n=t.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}o(Eu,"addRule");function QI(e,t,r){let n=e.rules.findIndex(a=>a.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}o(QI,"addBeforeRule");function XI(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Tf(t)),e.validateSchema=this.compile(t,!0))}o(XI,"keywordMetaschema");var eP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Tf(e){return{anyOf:[e,eP]}}o(Tf,"schemaOrData")});var Uf=x(Ou=>{"use strict";Object.defineProperty(Ou,"__esModule",{value:!0});var tP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ou.default=tP});var Mf=x(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.callRef=Br.getValidate=void 0;var rP=No(),Of=dt(),Ye=F(),xn=Vt(),$f=mi(),_i=re(),nP={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:a,schemaEnv:i,validateName:s,opts:c,self:d}=n,{root:p}=i;if((r==="#"||r==="#/")&&a===p.baseId)return m();let l=$f.resolveRef.call(d,p,a,r);if(l===void 0)throw new rP.default(n.opts.uriResolver,a,r);if(l instanceof $f.SchemaEnv)return h(l);return y(l);function m(){if(i===p)return wi(e,s,i,i.$async);let _=t.scopeValue("root",{ref:p});return wi(e,(0,Ye._)`${_}.validate`,p,p.$async)}function h(_){let S=zf(e,_);wi(e,S,_,_.$async)}function y(_){let S=t.scopeValue("schema",c.code.source===!0?{ref:_,code:(0,Ye.stringify)(_)}:{ref:_}),w=t.name("valid"),v=e.subschema({schema:_,dataTypes:[],schemaPath:Ye.nil,topSchemaRef:S,errSchemaPath:r},w);e.mergeEvaluated(v),e.ok(w)}}};function zf(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ye._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(zf,"getValidate");Br.getValidate=zf;function wi(e,t,r,n){let{gen:a,it:i}=e,{allErrors:s,schemaEnv:c,opts:d}=i,p=d.passContext?xn.default.this:Ye.nil;n?l():m();function l(){if(!c.$async)throw new Error("async schema referenced by sync schema");let _=a.let("valid");a.try(()=>{a.code((0,Ye._)`await ${(0,Of.callValidateCode)(e,t,p)}`),y(t),s||a.assign(_,!0)},S=>{a.if((0,Ye._)`!(${S} instanceof ${i.ValidationError})`,()=>a.throw(S)),h(S),s||a.assign(_,!1)}),e.ok(_)}o(l,"callAsyncRef");function m(){e.result((0,Of.callValidateCode)(e,t,p),()=>y(t),()=>h(t))}o(m,"callSyncRef");function h(_){let S=(0,Ye._)`${_}.errors`;a.assign(xn.default.vErrors,(0,Ye._)`${xn.default.vErrors} === null ? ${S} : ${xn.default.vErrors}.concat(${S})`),a.assign(xn.default.errors,(0,Ye._)`${xn.default.vErrors}.length`)}o(h,"addErrorsFrom");function y(_){var S;if(!i.opts.unevaluated)return;let w=(S=r?.validate)===null||S===void 0?void 0:S.evaluated;if(i.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(i.props=_i.mergeEvaluated.props(a,w.props,i.props));else{let v=a.var("props",(0,Ye._)`${_}.evaluated.props`);i.props=_i.mergeEvaluated.props(a,v,i.props,Ye.Name)}if(i.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(i.items=_i.mergeEvaluated.items(a,w.items,i.items));else{let v=a.var("items",(0,Ye._)`${_}.evaluated.items`);i.items=_i.mergeEvaluated.items(a,v,i.items,Ye.Name)}}o(y,"addEvaluatedFrom")}o(wi,"callRef");Br.callRef=wi;Br.default=nP});var qf=x($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var oP=Uf(),aP=Mf(),iP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",oP.default,aP.default];$u.default=iP});var Nf=x(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var vi=F(),vr=vi.operators,bi={maximum:{okStr:"<=",ok:vr.LTE,fail:vr.GT},minimum:{okStr:">=",ok:vr.GTE,fail:vr.LT},exclusiveMaximum:{okStr:"<",ok:vr.LT,fail:vr.GTE},exclusiveMinimum:{okStr:">",ok:vr.GT,fail:vr.LTE}},sP={message:o(({keyword:e,schemaCode:t})=>(0,vi.str)`must be ${bi[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,vi._)`{comparison: ${bi[e].okStr}, limit: ${t}}`,"params")},cP={keyword:Object.keys(bi),type:"number",schemaType:"number",$data:!0,error:sP,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,vi._)`${r} ${bi[t].fail} ${n} || isNaN(${r})`)}};zu.default=cP});var Df=x(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});var Bo=F(),uP={message:o(({schemaCode:e})=>(0,Bo.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,Bo._)`{multipleOf: ${e}}`,"params")},dP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:uP,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,s=t.let("res"),c=i?(0,Bo._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Bo._)`${s} !== parseInt(${s})`;e.fail$data((0,Bo._)`(${n} === 0 || (${s} = ${r}/${n}, ${c}))`)}};Mu.default=dP});var Hf=x(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});function jf(e){let t=e.length,r=0,n=0,a;for(;n<t;)r++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<t&&(a=e.charCodeAt(n),(a&64512)===56320&&n++);return r}o(jf,"ucs2length");qu.default=jf;jf.code='require("ajv/dist/runtime/ucs2length").default'});var Lf=x(Nu=>{"use strict";Object.defineProperty(Nu,"__esModule",{value:!0});var Gr=F(),lP=re(),pP=Hf(),mP={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Gr.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,Gr._)`{limit: ${e}}`,"params")},fP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:mP,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?Gr.operators.GT:Gr.operators.LT,s=a.opts.unicode===!1?(0,Gr._)`${r}.length`:(0,Gr._)`${(0,lP.useFunc)(e.gen,pP.default)}(${r})`;e.fail$data((0,Gr._)`${s} ${i} ${n}`)}};Nu.default=fP});var Bf=x(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});var hP=dt(),Ri=F(),gP={message:o(({schemaCode:e})=>(0,Ri.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Ri._)`{pattern: ${e}}`,"params")},yP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:gP,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:i}=e,s=i.opts.unicodeRegExp?"u":"",c=r?(0,Ri._)`(new RegExp(${a}, ${s}))`:(0,hP.usePattern)(e,n);e.fail$data((0,Ri._)`!${c}.test(${t})`)}};Du.default=yP});var Gf=x(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});var Go=F(),SP={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Go.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,Go._)`{limit: ${e}}`,"params")},_P={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:SP,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?Go.operators.GT:Go.operators.LT;e.fail$data((0,Go._)`Object.keys(${r}).length ${a} ${n}`)}};ju.default=_P});var Vf=x(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});var Vo=dt(),Fo=F(),wP=re(),vP={message:o(({params:{missingProperty:e}})=>(0,Fo.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,Fo._)`{missingProperty: ${e}}`,"params")},bP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:vP,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:i,it:s}=e,{opts:c}=s;if(!i&&r.length===0)return;let d=r.length>=c.loopRequired;if(s.allErrors?p():l(),c.strictRequired){let y=e.parentSchema.properties,{definedProperties:_}=e.it;for(let S of r)if(y?.[S]===void 0&&!_.has(S)){let w=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${S}" is not defined at "${w}" (strictRequired)`;(0,wP.checkStrictMode)(s,v,s.opts.strictRequired)}}function p(){if(d||i)e.block$data(Fo.nil,m);else for(let y of r)(0,Vo.checkReportMissingProp)(e,y)}o(p,"allErrorsMode");function l(){let y=t.let("missing");if(d||i){let _=t.let("valid",!0);e.block$data(_,()=>h(y,_)),e.ok(_)}else t.if((0,Vo.checkMissingProp)(e,r,y)),(0,Vo.reportMissingProp)(e,y),t.else()}o(l,"exitOnErrorMode");function m(){t.forOf("prop",n,y=>{e.setParams({missingProperty:y}),t.if((0,Vo.noPropertyInData)(t,a,y,c.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function h(y,_){e.setParams({missingProperty:y}),t.forOf(y,n,()=>{t.assign(_,(0,Vo.propertyInData)(t,a,y,c.ownProperties)),t.if((0,Fo.not)(_),()=>{e.error(),t.break()})},Fo.nil)}o(h,"loopUntilMissing")}};Hu.default=bP});var Ff=x(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});var Zo=F(),RP={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Zo.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,Zo._)`{limit: ${e}}`,"params")},CP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:RP,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?Zo.operators.GT:Zo.operators.LT;e.fail$data((0,Zo._)`${r}.length ${a} ${n}`)}};Lu.default=CP});var Ci=x(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});var Zf=mu();Zf.code='require("ajv/dist/runtime/equal").default';Bu.default=Zf});var Kf=x(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});var Gu=Oo(),Ue=F(),IP=re(),PP=Ci(),xP={message:o(({params:{i:e,j:t}})=>(0,Ue.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,Ue._)`{i: ${e}, j: ${t}}`,"params")},AP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:xP,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:i,schemaCode:s,it:c}=e;if(!n&&!a)return;let d=t.let("valid"),p=i.items?(0,Gu.getSchemaTypes)(i.items):[];e.block$data(d,l,(0,Ue._)`${s} === false`),e.ok(d);function l(){let _=t.let("i",(0,Ue._)`${r}.length`),S=t.let("j");e.setParams({i:_,j:S}),t.assign(d,!0),t.if((0,Ue._)`${_} > 1`,()=>(m()?h:y)(_,S))}o(l,"validateUniqueItems");function m(){return p.length>0&&!p.some(_=>_==="object"||_==="array")}o(m,"canOptimize");function h(_,S){let w=t.name("item"),v=(0,Gu.checkDataTypes)(p,w,c.opts.strictNumbers,Gu.DataType.Wrong),b=t.const("indices",(0,Ue._)`{}`);t.for((0,Ue._)`;${_}--;`,()=>{t.let(w,(0,Ue._)`${r}[${_}]`),t.if(v,(0,Ue._)`continue`),p.length>1&&t.if((0,Ue._)`typeof ${w} == "string"`,(0,Ue._)`${w} += "_"`),t.if((0,Ue._)`typeof ${b}[${w}] == "number"`,()=>{t.assign(S,(0,Ue._)`${b}[${w}]`),e.error(),t.assign(d,!1).break()}).code((0,Ue._)`${b}[${w}] = ${_}`)})}o(h,"loopN");function y(_,S){let w=(0,IP.useFunc)(t,PP.default),v=t.name("outer");t.label(v).for((0,Ue._)`;${_}--;`,()=>t.for((0,Ue._)`${S} = ${_}; ${S}--;`,()=>t.if((0,Ue._)`${w}(${r}[${_}], ${r}[${S}])`,()=>{e.error(),t.assign(d,!1).break(v)})))}o(y,"loopN2")}};Vu.default=AP});var Wf=x(Zu=>{"use strict";Object.defineProperty(Zu,"__esModule",{value:!0});var Fu=F(),kP=re(),TP=Ci(),EP={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,Fu._)`{allowedValue: ${e}}`,"params")},UP={keyword:"const",$data:!0,error:EP,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Fu._)`!${(0,kP.useFunc)(t,TP.default)}(${r}, ${a})`):e.fail((0,Fu._)`${i} !== ${r}`)}};Zu.default=UP});var Jf=x(Ku=>{"use strict";Object.defineProperty(Ku,"__esModule",{value:!0});var Ko=F(),OP=re(),$P=Ci(),zP={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,Ko._)`{allowedValues: ${e}}`,"params")},MP={keyword:"enum",schemaType:"array",$data:!0,error:zP,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:i,it:s}=e;if(!n&&a.length===0)throw new Error("enum must have non-empty array");let c=a.length>=s.opts.loopEnum,d,p=o(()=>d??(d=(0,OP.useFunc)(t,$P.default)),"getEql"),l;if(c||n)l=t.let("valid"),e.block$data(l,m);else{if(!Array.isArray(a))throw new Error("ajv implementation error");let y=t.const("vSchema",i);l=(0,Ko.or)(...a.map((_,S)=>h(y,S)))}e.pass(l);function m(){t.assign(l,!1),t.forOf("v",i,y=>t.if((0,Ko._)`${p()}(${r}, ${y})`,()=>t.assign(l,!0).break()))}o(m,"loopEnum");function h(y,_){let S=a[_];return typeof S=="object"&&S!==null?(0,Ko._)`${p()}(${r}, ${y}[${_}])`:(0,Ko._)`${r} === ${S}`}o(h,"equalCode")}};Ku.default=MP});var Yf=x(Wu=>{"use strict";Object.defineProperty(Wu,"__esModule",{value:!0});var qP=Nf(),NP=Df(),DP=Lf(),jP=Bf(),HP=Gf(),LP=Vf(),BP=Ff(),GP=Kf(),VP=Wf(),FP=Jf(),ZP=[qP.default,NP.default,DP.default,jP.default,HP.default,LP.default,BP.default,GP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},VP.default,FP.default];Wu.default=ZP});var Yu=x(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.validateAdditionalItems=void 0;var Vr=F(),Ju=re(),KP={message:o(({params:{len:e}})=>(0,Vr.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,Vr._)`{limit: ${e}}`,"params")},WP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:KP,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Ju.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Qf(e,n)}};function Qf(e,t){let{gen:r,schema:n,data:a,keyword:i,it:s}=e;s.items=!0;let c=r.const("len",(0,Vr._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Vr._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,Ju.alwaysValidSchema)(s,n)){let p=r.var("valid",(0,Vr._)`${c} <= ${t.length}`);r.if((0,Vr.not)(p),()=>d(p)),e.ok(p)}function d(p){r.forRange("i",t.length,c,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:Ju.Type.Num},p),s.allErrors||r.if((0,Vr.not)(p),()=>r.break())})}o(d,"validateItems")}o(Qf,"validateAdditionalItems");Wo.validateAdditionalItems=Qf;Wo.default=WP});var Qu=x(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.validateTuple=void 0;var Xf=F(),Ii=re(),JP=dt(),YP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return eh(e,"additionalItems",t);r.items=!0,!(0,Ii.alwaysValidSchema)(r,t)&&e.ok((0,JP.validateArray)(e))}};function eh(e,t,r=e.schema){let{gen:n,parentSchema:a,data:i,keyword:s,it:c}=e;l(a),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=Ii.mergeEvaluated.items(n,r.length,c.items));let d=n.name("valid"),p=n.const("len",(0,Xf._)`${i}.length`);r.forEach((m,h)=>{(0,Ii.alwaysValidSchema)(c,m)||(n.if((0,Xf._)`${p} > ${h}`,()=>e.subschema({keyword:s,schemaProp:h,dataProp:h},d)),e.ok(d))});function l(m){let{opts:h,errSchemaPath:y}=c,_=r.length,S=_===m.minItems&&(_===m.maxItems||m[t]===!1);if(h.strictTuples&&!S){let w=`"${s}" is ${_}-tuple, but minItems or maxItems/${t} are not specified or different at path "${y}"`;(0,Ii.checkStrictMode)(c,w,h.strictTuples)}}o(l,"checkStrictTuple")}o(eh,"validateTuple");Jo.validateTuple=eh;Jo.default=YP});var th=x(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});var QP=Qu(),XP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,QP.validateTuple)(e,"items"),"code")};Xu.default=XP});var nh=x(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var rh=F(),ex=re(),tx=dt(),rx=Yu(),nx={message:o(({params:{len:e}})=>(0,rh.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,rh._)`{limit: ${e}}`,"params")},ox={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:nx,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,ex.alwaysValidSchema)(n,t)&&(a?(0,rx.validateAdditionalItems)(e,a):e.ok((0,tx.validateArray)(e)))}};ed.default=ox});var oh=x(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var pt=F(),Pi=re(),ax={message:o(({params:{min:e,max:t}})=>t===void 0?(0,pt.str)`must contain at least ${e} valid item(s)`:(0,pt.str)`must contain at least ${e} and no more than ${t} valid item(s)`,"message"),params:o(({params:{min:e,max:t}})=>t===void 0?(0,pt._)`{minContains: ${e}}`:(0,pt._)`{minContains: ${e}, maxContains: ${t}}`,"params")},ix={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:ax,code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e,s,c,{minContains:d,maxContains:p}=n;i.opts.next?(s=d===void 0?1:d,c=p):s=1;let l=t.const("len",(0,pt._)`${a}.length`);if(e.setParams({min:s,max:c}),c===void 0&&s===0){(0,Pi.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&s>c){(0,Pi.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Pi.alwaysValidSchema)(i,r)){let S=(0,pt._)`${l} >= ${s}`;c!==void 0&&(S=(0,pt._)`${S} && ${l} <= ${c}`),e.pass(S);return}i.items=!0;let m=t.name("valid");c===void 0&&s===1?y(m,()=>t.if(m,()=>t.break())):s===0?(t.let(m,!0),c!==void 0&&t.if((0,pt._)`${a}.length > 0`,h)):(t.let(m,!1),h()),e.result(m,()=>e.reset());function h(){let S=t.name("_valid"),w=t.let("count",0);y(S,()=>t.if(S,()=>_(w)))}o(h,"validateItemsWithCount");function y(S,w){t.forRange("i",0,l,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:Pi.Type.Num,compositeRule:!0},S),w()})}o(y,"validateItems");function _(S){t.code((0,pt._)`${S}++`),c===void 0?t.if((0,pt._)`${S} >= ${s}`,()=>t.assign(m,!0).break()):(t.if((0,pt._)`${S} > ${c}`,()=>t.assign(m,!1).break()),s===1?t.assign(m,!0):t.if((0,pt._)`${S} >= ${s}`,()=>t.assign(m,!0)))}o(_,"checkLimits")}};td.default=ix});var sh=x(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.validateSchemaDeps=kt.validatePropertyDeps=kt.error=void 0;var rd=F(),sx=re(),Yo=dt();kt.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,rd.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,rd._)`{property: ${e},
25
+ import{$ as U,A as It,I as Zp,J as dc,K as Cv,L as Kp,M as f,N as Jp,O as X,P as oe,Q as Wp,R as Yp,S as we,T as C,U as I,V as Ce,W as fe,X as lc,Y as pc,Z as de,_ as nt,a as Ct,aa as ye,b as Vp,ba as Qp,ca as mc,da as Xp,ea as em,fa as u,ga as ae,j as _o,k as Fp,q as sc,s as wn,x as cc}from"../chunk-LCNCH3K2.js";import{d as uc}from"../chunk-W6JQ5D4W.js";import{a as Z}from"../chunk-NW4YQXGC.js";import{X as _n,Y as ue,Z as So,a as o,c as x,e as Gp}from"../chunk-JAEQKE5H.js";var oa=x(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.regexpCode=ee.getEsmExportName=ee.getProperty=ee.safeStringify=ee.stringify=ee.strConcat=ee.addCodeArg=ee.str=ee._=ee.nil=ee._Code=ee.Name=ee.IDENTIFIER=ee._CodeOrName=void 0;var ra=class{static{o(this,"_CodeOrName")}};ee._CodeOrName=ra;ee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Wr=class extends ra{static{o(this,"Name")}constructor(t){if(super(),!ee.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ee.Name=Wr;var pt=class extends ra{static{o(this,"_Code")}constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Wr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ee._Code=pt;ee.nil=new pt("");function vg(e,...t){let r=[e[0]],n=0;for(;n<t.length;)pd(r,t[n]),r.push(e[++n]);return new pt(r)}o(vg,"_");ee._=vg;var ld=new pt("+");function bg(e,...t){let r=[na(e[0])],n=0;for(;n<t.length;)r.push(ld),pd(r,t[n]),r.push(ld,na(e[++n]));return tA(r),new pt(r)}o(bg,"str");ee.str=bg;function pd(e,t){t instanceof pt?e.push(...t._items):t instanceof Wr?e.push(t):e.push(oA(t))}o(pd,"addCodeArg");ee.addCodeArg=pd;function tA(e){let t=1;for(;t<e.length-1;){if(e[t]===ld){let r=rA(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(tA,"optimize");function rA(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Wr||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Wr))return`"${e}${t.slice(1)}`}o(rA,"mergeExprItems");function nA(e,t){return t.emptyStr()?e:e.emptyStr()?t:bg`${e}${t}`}o(nA,"strConcat");ee.strConcat=nA;function oA(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:na(Array.isArray(e)?e.join(","):e)}o(oA,"interpolate");function aA(e){return new pt(na(e))}o(aA,"stringify");ee.stringify=aA;function na(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(na,"safeStringify");ee.safeStringify=na;function iA(e){return typeof e=="string"&&ee.IDENTIFIER.test(e)?new pt(`.${e}`):vg`[${e}]`}o(iA,"getProperty");ee.getProperty=iA;function sA(e){if(typeof e=="string"&&ee.IDENTIFIER.test(e))return new pt(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(sA,"getEsmExportName");ee.getEsmExportName=sA;function cA(e){return new pt(e.toString())}o(cA,"regexpCode");ee.regexpCode=cA});var hd=x(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.ValueScope=et.ValueScopeName=et.Scope=et.varKinds=et.UsedValueState=void 0;var Xe=oa(),md=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Li;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Li||(et.UsedValueState=Li={}));et.varKinds={const:new Xe.Name("const"),let:new Xe.Name("let"),var:new Xe.Name("var")};var Bi=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Xe.Name?t:this.name(t)}name(t){return new Xe.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};et.Scope=Bi;var Gi=class extends Xe.Name{static{o(this,"ValueScopeName")}constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Xe._)`.${new Xe.Name(r)}[${n}]`}};et.ValueScopeName=Gi;var uA=(0,Xe._)`\n`,fd=class extends Bi{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?uA:Xe.nil}}get(){return this._scope}name(t){return new Gi(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let a=this.toName(t),{prefix:i}=a,s=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[i];if(c){let l=c.get(s);if(l)return l}else c=this._values[i]=new Map;c.set(s,a);let d=this._scope[i]||(this._scope[i]=[]),p=d.length;return d[p]=r.ref,a.setValue(r,{property:i,itemIndex:p}),a}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Xe._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,a=>{if(a.value===void 0)throw new Error(`CodeGen: name "${a}" has no value`);return a.value.code},r,n)}_reduceValues(t,r,n={},a){let i=Xe.nil;for(let s in t){let c=t[s];if(!c)continue;let d=n[s]=n[s]||new Map;c.forEach(p=>{if(d.has(p))return;d.set(p,Li.Started);let l=r(p);if(l){let m=this.opts.es5?et.varKinds.var:et.varKinds.const;i=(0,Xe._)`${i}${m} ${p} = ${l};${this.opts._n}`}else if(l=a?.(p))i=(0,Xe._)`${i}${l}${this.opts._n}`;else throw new md(p);d.set(p,Li.Completed)})}return i}};et.ValueScope=fd});var V=x(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.or=F.and=F.not=F.CodeGen=F.operators=F.varKinds=F.ValueScopeName=F.ValueScope=F.Scope=F.Name=F.regexpCode=F.stringify=F.getProperty=F.nil=F.strConcat=F.str=F._=void 0;var Y=oa(),_t=hd(),_r=oa();Object.defineProperty(F,"_",{enumerable:!0,get:o(function(){return _r._},"get")});Object.defineProperty(F,"str",{enumerable:!0,get:o(function(){return _r.str},"get")});Object.defineProperty(F,"strConcat",{enumerable:!0,get:o(function(){return _r.strConcat},"get")});Object.defineProperty(F,"nil",{enumerable:!0,get:o(function(){return _r.nil},"get")});Object.defineProperty(F,"getProperty",{enumerable:!0,get:o(function(){return _r.getProperty},"get")});Object.defineProperty(F,"stringify",{enumerable:!0,get:o(function(){return _r.stringify},"get")});Object.defineProperty(F,"regexpCode",{enumerable:!0,get:o(function(){return _r.regexpCode},"get")});Object.defineProperty(F,"Name",{enumerable:!0,get:o(function(){return _r.Name},"get")});var Ki=hd();Object.defineProperty(F,"Scope",{enumerable:!0,get:o(function(){return Ki.Scope},"get")});Object.defineProperty(F,"ValueScope",{enumerable:!0,get:o(function(){return Ki.ValueScope},"get")});Object.defineProperty(F,"ValueScopeName",{enumerable:!0,get:o(function(){return Ki.ValueScopeName},"get")});Object.defineProperty(F,"varKinds",{enumerable:!0,get:o(function(){return Ki.varKinds},"get")});F.operators={GT:new Y._Code(">"),GTE:new Y._Code(">="),LT:new Y._Code("<"),LTE:new Y._Code("<="),EQ:new Y._Code("==="),NEQ:new Y._Code("!=="),NOT:new Y._Code("!"),OR:new Y._Code("||"),AND:new Y._Code("&&"),ADD:new Y._Code("+")};var Kt=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},gd=class extends Kt{static{o(this,"Def")}constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?_t.varKinds.var:this.varKind,a=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${a};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Gn(this.rhs,t,r)),this}get names(){return this.rhs instanceof Y._CodeOrName?this.rhs.names:{}}},Vi=class extends Kt{static{o(this,"Assign")}constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof Y.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Gn(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Y.Name?{}:{...this.lhs.names};return Zi(t,this.rhs)}},yd=class extends Vi{static{o(this,"AssignOp")}constructor(t,r,n,a){super(t,n,a),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Sd=class extends Kt{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},_d=class extends Kt{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},wd=class extends Kt{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},vd=class extends Kt{static{o(this,"AnyCode")}constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Gn(this.code,t,r),this}get names(){return this.code instanceof Y._CodeOrName?this.code.names:{}}},aa=class extends Kt{static{o(this,"ParentNode")}constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,a=n.length;for(;a--;){let i=n[a];i.optimizeNames(t,r)||(dA(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Xr(t,r.names),{})}},Jt=class extends aa{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},bd=class extends aa{static{o(this,"Root")}},Bn=class extends Jt{static{o(this,"Else")}};Bn.kind="else";var Yr=class e extends Jt{static{o(this,"If")}constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Bn(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Rg(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Gn(this.condition,t,r),this}get names(){let t=super.names;return Zi(t,this.condition),this.else&&Xr(t,this.else.names),t}};Yr.kind="if";var Qr=class extends Jt{static{o(this,"For")}};Qr.kind="for";var Rd=class extends Qr{static{o(this,"ForLoop")}constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Gn(this.iteration,t,r),this}get names(){return Xr(super.names,this.iteration.names)}},Cd=class extends Qr{static{o(this,"ForRange")}constructor(t,r,n,a){super(),this.varKind=t,this.name=r,this.from=n,this.to=a}render(t){let r=t.es5?_t.varKinds.var:this.varKind,{name:n,from:a,to:i}=this;return`for(${r} ${n}=${a}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=Zi(super.names,this.from);return Zi(t,this.to)}},Fi=class extends Qr{static{o(this,"ForIter")}constructor(t,r,n,a){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=a}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Gn(this.iterable,t,r),this}get names(){return Xr(super.names,this.iterable.names)}},ia=class extends Jt{static{o(this,"Func")}constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};ia.kind="func";var sa=class extends aa{static{o(this,"Return")}render(t){return"return "+super.render(t)}};sa.kind="return";var Id=class extends Jt{static{o(this,"Try")}render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,a;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(a=this.finally)===null||a===void 0||a.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Xr(t,this.catch.names),this.finally&&Xr(t,this.finally.names),t}},ca=class extends Jt{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};ca.kind="catch";var ua=class extends Jt{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};ua.kind="finally";var Pd=class{static{o(this,"CodeGen")}constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
26
+ `:""},this._extScope=t,this._scope=new _t.Scope({parent:t}),this._nodes=[new bd]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,a){let i=this._scope.toName(r);return n!==void 0&&a&&(this._constants[i.str]=n),this._leafNode(new gd(t,i,n)),i}const(t,r,n){return this._def(_t.varKinds.const,t,r,n)}let(t,r,n){return this._def(_t.varKinds.let,t,r,n)}var(t,r,n){return this._def(_t.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Vi(t,r,n))}add(t,r){return this._leafNode(new yd(t,F.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Y.nil&&this._leafNode(new vd(t)),this}object(...t){let r=["{"];for(let[n,a]of t)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0,Y.addCodeArg)(r,a));return r.push("}"),new Y._Code(r)}if(t,r,n){if(this._blockNode(new Yr(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Yr(t))}else(){return this._elseNode(new Bn)}endIf(){return this._endBlockNode(Yr,Bn)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Rd(t),r)}forRange(t,r,n,a,i=this.opts.es5?_t.varKinds.var:_t.varKinds.let){let s=this._scope.toName(t);return this._for(new Cd(i,s,r,n),()=>a(s))}forOf(t,r,n,a=_t.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof Y.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Y._)`${s}.length`,c=>{this.var(i,(0,Y._)`${s}[${c}]`),n(i)})}return this._for(new Fi("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?_t.varKinds.var:_t.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Y._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Fi("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(Qr)}label(t){return this._leafNode(new Sd(t))}break(t){return this._leafNode(new _d(t))}return(t){let r=new sa;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(sa)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new Id;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new ca(i),r(i)}return n&&(this._currNode=a.finally=new ua,this.code(n)),this._endBlockNode(ca,ua)}throw(t){return this._leafNode(new wd(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=Y.nil,n,a){return this._blockNode(new ia(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(ia)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Yr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};F.CodeGen=Pd;function Xr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(Xr,"addNames");function Zi(e,t){return t instanceof Y._CodeOrName?Xr(e,t.names):e}o(Zi,"addExprNames");function Gn(e,t,r){if(e instanceof Y.Name)return n(e);if(!a(e))return e;return new Y._Code(e._items.reduce((i,s)=>(s instanceof Y.Name&&(s=n(s)),s instanceof Y._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function a(i){return i instanceof Y._Code&&i._items.some(s=>s instanceof Y.Name&&t[s.str]===1&&r[s.str]!==void 0)}}o(Gn,"optimizeExpr");function dA(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(dA,"subtractNames");function Rg(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Y._)`!${xd(e)}`}o(Rg,"not");F.not=Rg;var lA=Cg(F.operators.AND);function pA(...e){return e.reduce(lA)}o(pA,"and");F.and=pA;var mA=Cg(F.operators.OR);function fA(...e){return e.reduce(mA)}o(fA,"or");F.or=fA;function Cg(e){return(t,r)=>t===Y.nil?r:r===Y.nil?t:(0,Y._)`${xd(t)} ${e} ${xd(r)}`}o(Cg,"mappend");function xd(e){return e instanceof Y.Name?e:(0,Y._)`(${e})`}o(xd,"par")});var te=x(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var se=V(),hA=oa();function gA(e){let t={};for(let r of e)t[r]=!0;return t}o(gA,"toHash");J.toHash=gA;function yA(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(xg(e,t),!Ag(t,e.self.RULES.all))}o(yA,"alwaysValidSchema");J.alwaysValidSchema=yA;function xg(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let a=n.RULES.keywords;for(let i in t)a[i]||Eg(e,`unknown keyword: "${i}"`)}o(xg,"checkUnknownRules");J.checkUnknownRules=xg;function Ag(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(Ag,"schemaHasRules");J.schemaHasRules=Ag;function SA(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(SA,"schemaHasRulesButRef");J.schemaHasRulesButRef=SA;function _A({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,se._)`${r}`}return(0,se._)`${e}${t}${(0,se.getProperty)(n)}`}o(_A,"schemaRefOrVal");J.schemaRefOrVal=_A;function wA(e){return kg(decodeURIComponent(e))}o(wA,"unescapeFragment");J.unescapeFragment=wA;function vA(e){return encodeURIComponent(kd(e))}o(vA,"escapeFragment");J.escapeFragment=vA;function kd(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(kd,"escapeJsonPointer");J.escapeJsonPointer=kd;function kg(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(kg,"unescapeJsonPointer");J.unescapeJsonPointer=kg;function bA(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o(bA,"eachItem");J.eachItem=bA;function Ig({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,s,c)=>{let d=s===void 0?i:s instanceof se.Name?(i instanceof se.Name?e(a,i,s):t(a,i,s),s):i instanceof se.Name?(t(a,s,i),i):r(i,s);return c===se.Name&&!(d instanceof se.Name)?n(a,d):d}}o(Ig,"makeMergeEvaluated");J.mergeEvaluated={props:Ig({mergeNames:o((e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,se._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,se._)`${r} || {}`).code((0,se._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,se._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,se._)`${r} || {}`),Td(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:Tg}),items:Ig({mergeNames:o((e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,se._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,se._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,se._)`${r} > ${t} ? ${r} : ${t}`)),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:Math.max(e,t),"mergeValues"),resultToName:o((e,t)=>e.var("items",t),"resultToName")})};function Tg(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,se._)`{}`);return t!==void 0&&Td(e,r,t),r}o(Tg,"evaluatedPropsToName");J.evaluatedPropsToName=Tg;function Td(e,t,r){Object.keys(r).forEach(n=>e.assign((0,se._)`${t}${(0,se.getProperty)(n)}`,!0))}o(Td,"setEvaluated");J.setEvaluated=Td;var Pg={};function RA(e,t){return e.scopeValue("func",{ref:t,code:Pg[t.code]||(Pg[t.code]=new hA._Code(t.code))})}o(RA,"useFunc");J.useFunc=RA;var Ad;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Ad||(J.Type=Ad={}));function CA(e,t,r){if(e instanceof se.Name){let n=t===Ad.Num;return r?n?(0,se._)`"[" + ${e} + "]"`:(0,se._)`"['" + ${e} + "']"`:n?(0,se._)`"/" + ${e}`:(0,se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,se.getProperty)(e).toString():"/"+kd(e)}o(CA,"getErrorPath");J.getErrorPath=CA;function Eg(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}o(Eg,"checkStrictMode");J.checkStrictMode=Eg});var Wt=x(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var De=V(),IA={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};Ed.default=IA});var da=x(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.extendErrors=He.resetErrorsCount=He.reportExtraError=He.reportError=He.keyword$DataError=He.keywordError=void 0;var Q=V(),Ji=te(),Ve=Wt();He.keywordError={message:o(({keyword:e})=>(0,Q.str)`must pass "${e}" keyword validation`,"message")};He.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,Q.str)`"${e}" keyword must be ${t} ($data)`:(0,Q.str)`"${e}" keyword is invalid ($data)`,"message")};function PA(e,t=He.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:s,allErrors:c}=a,d=$g(e,t,r);n??(s||c)?Ug(i,d):Og(a,(0,Q._)`[${d}]`)}o(PA,"reportError");He.reportError=PA;function xA(e,t=He.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:s}=n,c=$g(e,t,r);Ug(a,c),i||s||Og(n,Ve.default.vErrors)}o(xA,"reportExtraError");He.reportExtraError=xA;function AA(e,t){e.assign(Ve.default.errors,t),e.if((0,Q._)`${Ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Q._)`${Ve.default.vErrors}.length`,t),()=>e.assign(Ve.default.vErrors,null)))}o(AA,"resetErrorsCount");He.resetErrorsCount=AA;function kA({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:i}){if(a===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",a,Ve.default.errors,c=>{e.const(s,(0,Q._)`${Ve.default.vErrors}[${c}]`),e.if((0,Q._)`${s}.instancePath === undefined`,()=>e.assign((0,Q._)`${s}.instancePath`,(0,Q.strConcat)(Ve.default.instancePath,i.errorPath))),e.assign((0,Q._)`${s}.schemaPath`,(0,Q.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Q._)`${s}.schema`,r),e.assign((0,Q._)`${s}.data`,n))})}o(kA,"extendErrors");He.extendErrors=kA;function Ug(e,t){let r=e.const("err",t);e.if((0,Q._)`${Ve.default.vErrors} === null`,()=>e.assign(Ve.default.vErrors,(0,Q._)`[${r}]`),(0,Q._)`${Ve.default.vErrors}.push(${r})`),e.code((0,Q._)`${Ve.default.errors}++`)}o(Ug,"addError");function Og(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,Q._)`new ${e.ValidationError}(${t})`):(r.assign((0,Q._)`${n}.errors`,t),r.return(!1))}o(Og,"returnErrors");var en={keyword:new Q.Name("keyword"),schemaPath:new Q.Name("schemaPath"),params:new Q.Name("params"),propertyName:new Q.Name("propertyName"),message:new Q.Name("message"),schema:new Q.Name("schema"),parentSchema:new Q.Name("parentSchema")};function $g(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Q._)`{}`:TA(e,t,r)}o($g,"errorObjectCode");function TA(e,t,r={}){let{gen:n,it:a}=e,i=[EA(a,r),UA(e,r)];return OA(e,t,i),n.object(...i)}o(TA,"errorObject");function EA({errorPath:e},{instancePath:t}){let r=t?(0,Q.str)`${e}${(0,Ji.getErrorPath)(t,Ji.Type.Str)}`:e;return[Ve.default.instancePath,(0,Q.strConcat)(Ve.default.instancePath,r)]}o(EA,"errorInstancePath");function UA({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,Q.str)`${t}/${e}`;return r&&(a=(0,Q.str)`${a}${(0,Ji.getErrorPath)(r,Ji.Type.Str)}`),[en.schemaPath,a]}o(UA,"errorSchemaPath");function OA(e,{params:t,message:r},n){let{keyword:a,data:i,schemaValue:s,it:c}=e,{opts:d,propertyName:p,topSchemaRef:l,schemaPath:m}=c;n.push([en.keyword,a],[en.params,typeof t=="function"?t(e):t||(0,Q._)`{}`]),d.messages&&n.push([en.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([en.schema,s],[en.parentSchema,(0,Q._)`${l}${m}`],[Ve.default.data,i]),p&&n.push([en.propertyName,p])}o(OA,"extraErrorProps")});var Mg=x(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.boolOrEmptySchema=Vn.topBoolOrEmptySchema=void 0;var $A=da(),zA=V(),MA=Wt(),qA={message:"boolean schema is false"};function NA(e){let{gen:t,schema:r,validateName:n}=e;r===!1?zg(e,!1):typeof r=="object"&&r.$async===!0?t.return(MA.default.data):(t.assign((0,zA._)`${n}.errors`,null),t.return(!0))}o(NA,"topBoolOrEmptySchema");Vn.topBoolOrEmptySchema=NA;function jA(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),zg(e)):r.var(t,!0)}o(jA,"boolOrEmptySchema");Vn.boolOrEmptySchema=jA;function zg(e,t){let{gen:r,data:n}=e,a={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,$A.reportError)(a,qA,void 0,t)}o(zg,"falseSchemaError")});var Ud=x(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.getRules=Fn.isJSONType=void 0;var DA=["string","number","integer","boolean","null","object","array"],HA=new Set(DA);function LA(e){return typeof e=="string"&&HA.has(e)}o(LA,"isJSONType");Fn.isJSONType=LA;function BA(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}o(BA,"getRules");Fn.getRules=BA});var Od=x(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.shouldUseRule=wr.shouldUseGroup=wr.schemaHasRulesForType=void 0;function GA({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&qg(e,n)}o(GA,"schemaHasRulesForType");wr.schemaHasRulesForType=GA;function qg(e,t){return t.rules.some(r=>Ng(e,r))}o(qg,"shouldUseGroup");wr.shouldUseGroup=qg;function Ng(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}o(Ng,"shouldUseRule");wr.shouldUseRule=Ng});var la=x(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var VA=Ud(),FA=Od(),ZA=da(),G=V(),jg=te(),Zn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Zn||(Le.DataType=Zn={}));function KA(e){let t=Dg(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}o(KA,"getSchemaTypes");Le.getSchemaTypes=KA;function Dg(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(VA.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(Dg,"getJSONTypes");Le.getJSONTypes=Dg;function JA(e,t){let{gen:r,data:n,opts:a}=e,i=WA(t,a.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,FA.schemaHasRulesForType)(e,t[0]));if(s){let c=zd(t,n,a.strictNumbers,Zn.Wrong);r.if(c,()=>{i.length?YA(e,t,i):Md(e)})}return s}o(JA,"coerceAndCheckDataType");Le.coerceAndCheckDataType=JA;var Hg=new Set(["string","number","integer","boolean","null"]);function WA(e,t){return t?e.filter(r=>Hg.has(r)||t==="array"&&r==="array"):[]}o(WA,"coerceToTypes");function YA(e,t,r){let{gen:n,data:a,opts:i}=e,s=n.let("dataType",(0,G._)`typeof ${a}`),c=n.let("coerced",(0,G._)`undefined`);i.coerceTypes==="array"&&n.if((0,G._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,G._)`${a}[0]`).assign(s,(0,G._)`typeof ${a}`).if(zd(t,a,i.strictNumbers),()=>n.assign(c,a))),n.if((0,G._)`${c} !== undefined`);for(let p of r)(Hg.has(p)||p==="array"&&i.coerceTypes==="array")&&d(p);n.else(),Md(e),n.endIf(),n.if((0,G._)`${c} !== undefined`,()=>{n.assign(a,c),QA(e,c)});function d(p){switch(p){case"string":n.elseIf((0,G._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,G._)`"" + ${a}`).elseIf((0,G._)`${a} === null`).assign(c,(0,G._)`""`);return;case"number":n.elseIf((0,G._)`${s} == "boolean" || ${a} === null
27
+ || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,G._)`+${a}`);return;case"integer":n.elseIf((0,G._)`${s} === "boolean" || ${a} === null
28
+ || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,G._)`+${a}`);return;case"boolean":n.elseIf((0,G._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,G._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case"null":n.elseIf((0,G._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(c,null);return;case"array":n.elseIf((0,G._)`${s} === "string" || ${s} === "number"
29
+ || ${s} === "boolean" || ${a} === null`).assign(c,(0,G._)`[${a}]`)}}o(d,"coerceSpecificType")}o(YA,"coerceData");function QA({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,G._)`${t} !== undefined`,()=>e.assign((0,G._)`${t}[${r}]`,n))}o(QA,"assignParentData");function $d(e,t,r,n=Zn.Correct){let a=n===Zn.Correct?G.operators.EQ:G.operators.NEQ,i;switch(e){case"null":return(0,G._)`${t} ${a} null`;case"array":i=(0,G._)`Array.isArray(${t})`;break;case"object":i=(0,G._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,G._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,G._)`typeof ${t} ${a} ${e}`}return n===Zn.Correct?i:(0,G.not)(i);function s(c=G.nil){return(0,G.and)((0,G._)`typeof ${t} == "number"`,c,r?(0,G._)`isFinite(${t})`:G.nil)}}o($d,"checkDataType");Le.checkDataType=$d;function zd(e,t,r,n){if(e.length===1)return $d(e[0],t,r,n);let a,i=(0,jg.toHash)(e);if(i.array&&i.object){let s=(0,G._)`typeof ${t} != "object"`;a=i.null?s:(0,G._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else a=G.nil;i.number&&delete i.integer;for(let s in i)a=(0,G.and)(a,$d(s,t,r,n));return a}o(zd,"checkDataTypes");Le.checkDataTypes=zd;var XA={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,G._)`{type: ${e}}`:(0,G._)`{type: ${t}}`,"params")};function Md(e){let t=ek(e);(0,ZA.reportError)(t,XA)}o(Md,"reportTypeError");Le.reportTypeError=Md;function ek(e){let{gen:t,data:r,schema:n}=e,a=(0,jg.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o(ek,"getTypeErrorContext")});var Bg=x(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.assignDefaults=void 0;var Kn=V(),tk=te();function rk(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)Lg(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>Lg(e,i,a.default))}o(rk,"assignDefaults");Wi.assignDefaults=rk;function Lg(e,t,r){let{gen:n,compositeRule:a,data:i,opts:s}=e;if(r===void 0)return;let c=(0,Kn._)`${i}${(0,Kn.getProperty)(t)}`;if(a){(0,tk.checkStrictMode)(e,`default is ignored for: ${c}`);return}let d=(0,Kn._)`${c} === undefined`;s.useDefaults==="empty"&&(d=(0,Kn._)`${d} || ${c} === null || ${c} === ""`),n.if(d,(0,Kn._)`${c} = ${(0,Kn.stringify)(r)}`)}o(Lg,"assignDefault")});var mt=x(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.validateUnion=ne.validateArray=ne.usePattern=ne.callValidateCode=ne.schemaProperties=ne.allSchemaProperties=ne.noPropertyInData=ne.propertyInData=ne.isOwnProperty=ne.hasPropFunc=ne.reportMissingProp=ne.checkMissingProp=ne.checkReportMissingProp=void 0;var pe=V(),qd=te(),vr=Wt(),nk=te();function ok(e,t){let{gen:r,data:n,it:a}=e;r.if(jd(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,pe._)`${t}`},!0),e.error()})}o(ok,"checkReportMissingProp");ne.checkReportMissingProp=ok;function ak({gen:e,data:t,it:{opts:r}},n,a){return(0,pe.or)(...n.map(i=>(0,pe.and)(jd(e,t,i,r.ownProperties),(0,pe._)`${a} = ${i}`)))}o(ak,"checkMissingProp");ne.checkMissingProp=ak;function ik(e,t){e.setParams({missingProperty:t},!0),e.error()}o(ik,"reportMissingProp");ne.reportMissingProp=ik;function Gg(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,pe._)`Object.prototype.hasOwnProperty`})}o(Gg,"hasPropFunc");ne.hasPropFunc=Gg;function Nd(e,t,r){return(0,pe._)`${Gg(e)}.call(${t}, ${r})`}o(Nd,"isOwnProperty");ne.isOwnProperty=Nd;function sk(e,t,r,n){let a=(0,pe._)`${t}${(0,pe.getProperty)(r)} !== undefined`;return n?(0,pe._)`${a} && ${Nd(e,t,r)}`:a}o(sk,"propertyInData");ne.propertyInData=sk;function jd(e,t,r,n){let a=(0,pe._)`${t}${(0,pe.getProperty)(r)} === undefined`;return n?(0,pe.or)(a,(0,pe.not)(Nd(e,t,r))):a}o(jd,"noPropertyInData");ne.noPropertyInData=jd;function Vg(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o(Vg,"allSchemaProperties");ne.allSchemaProperties=Vg;function ck(e,t){return Vg(t).filter(r=>!(0,qd.alwaysValidSchema)(e,t[r]))}o(ck,"schemaProperties");ne.schemaProperties=ck;function uk({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:s},c,d,p){let l=p?(0,pe._)`${e}, ${t}, ${n}${a}`:t,m=[[vr.default.instancePath,(0,pe.strConcat)(vr.default.instancePath,i)],[vr.default.parentData,s.parentData],[vr.default.parentDataProperty,s.parentDataProperty],[vr.default.rootData,vr.default.rootData]];s.opts.dynamicRef&&m.push([vr.default.dynamicAnchors,vr.default.dynamicAnchors]);let h=(0,pe._)`${l}, ${r.object(...m)}`;return d!==pe.nil?(0,pe._)`${c}.call(${d}, ${h})`:(0,pe._)`${c}(${h})`}o(uk,"callValidateCode");ne.callValidateCode=uk;var dk=(0,pe._)`new RegExp`;function lk({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,i=a(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,pe._)`${a.code==="new RegExp"?dk:(0,nk.useFunc)(e,a)}(${r}, ${n})`})}o(lk,"usePattern");ne.usePattern=lk;function pk(e){let{gen:t,data:r,keyword:n,it:a}=e,i=t.name("valid");if(a.allErrors){let c=t.let("valid",!0);return s(()=>t.assign(c,!1)),c}return t.var(i,!0),s(()=>t.break()),i;function s(c){let d=t.const("len",(0,pe._)`${r}.length`);t.forRange("i",0,d,p=>{e.subschema({keyword:n,dataProp:p,dataPropType:qd.Type.Num},i),t.if((0,pe.not)(i),c)})}o(s,"validateItems")}o(pk,"validateArray");ne.validateArray=pk;function mk(e){let{gen:t,schema:r,keyword:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(d=>(0,qd.alwaysValidSchema)(a,d))&&!a.opts.unevaluated)return;let s=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((d,p)=>{let l=e.subschema({keyword:n,schemaProp:p,compositeRule:!0},c);t.assign(s,(0,pe._)`${s} || ${c}`),e.mergeValidEvaluated(l,c)||t.if((0,pe.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}o(mk,"validateUnion");ne.validateUnion=mk});var Kg=x(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.validateKeywordUsage=kt.validSchemaType=kt.funcKeywordCode=kt.macroKeywordCode=void 0;var Fe=V(),tn=Wt(),fk=mt(),hk=da();function gk(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:s}=e,c=t.macro.call(s.self,a,i,s),d=Zg(r,n,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let p=r.name("valid");e.subschema({schema:c,schemaPath:Fe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},p),e.pass(p,()=>e.error(!0))}o(gk,"macroKeywordCode");kt.macroKeywordCode=gk;function yk(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:s,$data:c,it:d}=e;_k(d,t);let p=!c&&t.compile?t.compile.call(d.self,i,s,d):t.validate,l=Zg(n,a,p),m=n.let("valid");e.block$data(m,h),e.ok((r=t.valid)!==null&&r!==void 0?r:m);function h(){if(t.errors===!1)S(),t.modifying&&Fg(e),w(()=>e.error());else{let v=t.async?y():_();t.modifying&&Fg(e),w(()=>Sk(e,v))}}o(h,"validateKeyword");function y(){let v=n.let("ruleErrs",null);return n.try(()=>S((0,Fe._)`await `),b=>n.assign(m,!1).if((0,Fe._)`${b} instanceof ${d.ValidationError}`,()=>n.assign(v,(0,Fe._)`${b}.errors`),()=>n.throw(b))),v}o(y,"validateAsync");function _(){let v=(0,Fe._)`${l}.errors`;return n.assign(v,null),S(Fe.nil),v}o(_,"validateSync");function S(v=t.async?(0,Fe._)`await `:Fe.nil){let b=d.opts.passContext?tn.default.this:tn.default.self,R=!("compile"in t&&!c||t.schema===!1);n.assign(m,(0,Fe._)`${v}${(0,fk.callValidateCode)(e,l,b,R)}`,t.modifying)}o(S,"assignValid");function w(v){var b;n.if((0,Fe.not)((b=t.valid)!==null&&b!==void 0?b:m),v)}o(w,"reportErrs")}o(yk,"funcKeywordCode");kt.funcKeywordCode=yk;function Fg(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Fe._)`${n.parentData}[${n.parentDataProperty}]`))}o(Fg,"modifyData");function Sk(e,t){let{gen:r}=e;r.if((0,Fe._)`Array.isArray(${t})`,()=>{r.assign(tn.default.vErrors,(0,Fe._)`${tn.default.vErrors} === null ? ${t} : ${tn.default.vErrors}.concat(${t})`).assign(tn.default.errors,(0,Fe._)`${tn.default.vErrors}.length`),(0,hk.extendErrors)(e)},()=>e.error())}o(Sk,"addErrs");function _k({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o(_k,"checkAsyncKeyword");function Zg(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Fe.stringify)(r)})}o(Zg,"useKeyword");function wk(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}o(wk,"validSchemaType");kt.validSchemaType=wk;function vk({schema:e,opts:t,self:r,errSchemaPath:n},a,i){if(Array.isArray(a.keyword)?!a.keyword.includes(i):a.keyword!==i)throw new Error("ajv implementation error");let s=a.dependencies;if(s?.some(c=>!Object.prototype.hasOwnProperty.call(e,c)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(a.validateSchema&&!a.validateSchema(e[i])){let d=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(a.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(d);else throw new Error(d)}}o(vk,"validateKeywordUsage");kt.validateKeywordUsage=vk});var Wg=x(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.extendSubschemaMode=br.extendSubschemaData=br.getSubschema=void 0;var Tt=V(),Jg=te();function bk(e,{keyword:t,schemaProp:r,schema:n,schemaPath:a,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let c=e.schema[t];return r===void 0?{schema:c,schemaPath:(0,Tt._)`${e.schemaPath}${(0,Tt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,Tt._)`${e.schemaPath}${(0,Tt.getProperty)(t)}${(0,Tt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Jg.escapeFragment)(r)}`}}if(n!==void 0){if(a===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:a,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}o(bk,"getSubschema");br.getSubschema=bk;function Rk(e,t,{dataProp:r,dataPropType:n,data:a,dataTypes:i,propertyName:s}){if(a!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=t;if(r!==void 0){let{errorPath:p,dataPathArr:l,opts:m}=t,h=c.let("data",(0,Tt._)`${t.data}${(0,Tt.getProperty)(r)}`,!0);d(h),e.errorPath=(0,Tt.str)`${p}${(0,Jg.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,Tt._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let p=a instanceof Tt.Name?a:c.let("data",a,!0);d(p),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function d(p){e.data=p,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,p]}o(d,"dataContextProps")}o(Rk,"extendSubschemaData");br.extendSubschemaData=Rk;function Ck(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:i}){n!==void 0&&(e.compositeRule=n),a!==void 0&&(e.createErrors=a),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}o(Ck,"extendSubschemaMode");br.extendSubschemaMode=Ck});var Dd=x((X4,Yg)=>{"use strict";Yg.exports=o(function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,a,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(a=n;a--!==0;)if(!e(t[a],r[a]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[a]))return!1;for(a=n;a--!==0;){var s=i[a];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r},"equal")});var Xg=x((t9,Qg)=>{"use strict";var Rr=Qg.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},a=r.post||function(){};Yi(t,n,a,e,"",e)};Rr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Rr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Rr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Rr.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 Yi(e,t,r,n,a,i,s,c,d,p){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,a,i,s,c,d,p);for(var l in n){var m=n[l];if(Array.isArray(m)){if(l in Rr.arrayKeywords)for(var h=0;h<m.length;h++)Yi(e,t,r,m[h],a+"/"+l+"/"+h,i,a,l,n,h)}else if(l in Rr.propsKeywords){if(m&&typeof m=="object")for(var y in m)Yi(e,t,r,m[y],a+"/"+l+"/"+Ik(y),i,a,l,n,y)}else(l in Rr.keywords||e.allKeys&&!(l in Rr.skipKeywords))&&Yi(e,t,r,m,a+"/"+l,i,a,l,n)}r(n,a,i,s,c,d,p)}}o(Yi,"_traverse");function Ik(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(Ik,"escapeJsonPtr")});var pa=x(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.getSchemaRefs=tt.resolveUrl=tt.normalizeId=tt._getFullPath=tt.getFullPath=tt.inlineRef=void 0;var Pk=te(),xk=Dd(),Ak=Xg(),kk=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Tk(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Hd(e):t?ey(e)<=t:!1}o(Tk,"inlineRef");tt.inlineRef=Tk;var Ek=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Hd(e){for(let t in e){if(Ek.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Hd)||typeof r=="object"&&Hd(r))return!0}return!1}o(Hd,"hasRef");function ey(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!kk.has(r)&&(typeof e[r]=="object"&&(0,Pk.eachItem)(e[r],n=>t+=ey(n)),t===1/0))return 1/0}return t}o(ey,"countKeys");function ty(e,t="",r){r!==!1&&(t=Jn(t));let n=e.parse(t);return ry(e,n)}o(ty,"getFullPath");tt.getFullPath=ty;function ry(e,t){return e.serialize(t).split("#")[0]+"#"}o(ry,"_getFullPath");tt._getFullPath=ry;var Uk=/#\/?$/;function Jn(e){return e?e.replace(Uk,""):""}o(Jn,"normalizeId");tt.normalizeId=Jn;function Ok(e,t,r){return r=Jn(r),e.resolve(t,r)}o(Ok,"resolveUrl");tt.resolveUrl=Ok;var $k=/^[a-z_][-a-z0-9._]*$/i;function zk(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=Jn(e[r]||t),i={"":a},s=ty(n,a,!1),c={},d=new Set;return Ak(e,{allKeys:!0},(m,h,y,_)=>{if(_===void 0)return;let S=s+h,w=i[_];typeof m[r]=="string"&&(w=v.call(this,m[r])),b.call(this,m.$anchor),b.call(this,m.$dynamicAnchor),i[h]=w;function v(R){let M=this.opts.uriResolver.resolve;if(R=Jn(w?M(w,R):R),d.has(R))throw l(R);d.add(R);let q=this.refs[R];return typeof q=="string"&&(q=this.refs[q]),typeof q=="object"?p(m,q.schema,R):R!==Jn(S)&&(R[0]==="#"?(p(m,c[R],R),c[R]=m):this.refs[R]=S),R}o(v,"addRef");function b(R){if(typeof R=="string"){if(!$k.test(R))throw new Error(`invalid anchor "${R}"`);v.call(this,`#${R}`)}}o(b,"addAnchor")}),c;function p(m,h,y){if(h!==void 0&&!xk(m,h))throw l(y)}o(p,"checkAmbiguosRef");function l(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(l,"ambiguos")}o(zk,"getSchemaRefs");tt.getSchemaRefs=zk});var ha=x(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.getData=Cr.KeywordCxt=Cr.validateFunctionCode=void 0;var sy=Mg(),ny=la(),Bd=Od(),Qi=la(),Mk=Bg(),fa=Kg(),Ld=Wg(),O=V(),H=Wt(),qk=pa(),Yt=te(),ma=da();function Nk(e){if(dy(e)&&(ly(e),uy(e))){Hk(e);return}cy(e,()=>(0,sy.topBoolOrEmptySchema)(e))}o(Nk,"validateFunctionCode");Cr.validateFunctionCode=Nk;function cy({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,O._)`${H.default.data}, ${H.default.valCxt}`,n.$async,()=>{e.code((0,O._)`"use strict"; ${oy(r,a)}`),Dk(e,a),e.code(i)}):e.func(t,(0,O._)`${H.default.data}, ${jk(a)}`,n.$async,()=>e.code(oy(r,a)).code(i))}o(cy,"validateFunction");function jk(e){return(0,O._)`{${H.default.instancePath}="", ${H.default.parentData}, ${H.default.parentDataProperty}, ${H.default.rootData}=${H.default.data}${e.dynamicRef?(0,O._)`, ${H.default.dynamicAnchors}={}`:O.nil}}={}`}o(jk,"destructureValCxt");function Dk(e,t){e.if(H.default.valCxt,()=>{e.var(H.default.instancePath,(0,O._)`${H.default.valCxt}.${H.default.instancePath}`),e.var(H.default.parentData,(0,O._)`${H.default.valCxt}.${H.default.parentData}`),e.var(H.default.parentDataProperty,(0,O._)`${H.default.valCxt}.${H.default.parentDataProperty}`),e.var(H.default.rootData,(0,O._)`${H.default.valCxt}.${H.default.rootData}`),t.dynamicRef&&e.var(H.default.dynamicAnchors,(0,O._)`${H.default.valCxt}.${H.default.dynamicAnchors}`)},()=>{e.var(H.default.instancePath,(0,O._)`""`),e.var(H.default.parentData,(0,O._)`undefined`),e.var(H.default.parentDataProperty,(0,O._)`undefined`),e.var(H.default.rootData,H.default.data),t.dynamicRef&&e.var(H.default.dynamicAnchors,(0,O._)`{}`)})}o(Dk,"destructureValCxtES5");function Hk(e){let{schema:t,opts:r,gen:n}=e;cy(e,()=>{r.$comment&&t.$comment&&my(e),Fk(e),n.let(H.default.vErrors,null),n.let(H.default.errors,0),r.unevaluated&&Lk(e),py(e),Jk(e)})}o(Hk,"topSchemaObjCode");function Lk(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,O._)`${r}.evaluated`),t.if((0,O._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,O._)`${e.evaluated}.props`,(0,O._)`undefined`)),t.if((0,O._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,O._)`${e.evaluated}.items`,(0,O._)`undefined`))}o(Lk,"resetEvaluated");function oy(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,O._)`/*# sourceURL=${r} */`:O.nil}o(oy,"funcSourceUrl");function Bk(e,t){if(dy(e)&&(ly(e),uy(e))){Gk(e,t);return}(0,sy.boolOrEmptySchema)(e,t)}o(Bk,"subschemaCode");function uy({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}o(uy,"schemaCxtHasRules");function dy(e){return typeof e.schema!="boolean"}o(dy,"isSchemaObj");function Gk(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&my(e),Zk(e),Kk(e);let i=n.const("_errs",H.default.errors);py(e,i),n.var(t,(0,O._)`${i} === ${H.default.errors}`)}o(Gk,"subSchemaObjCode");function ly(e){(0,Yt.checkUnknownRules)(e),Vk(e)}o(ly,"checkKeywords");function py(e,t){if(e.opts.jtd)return ay(e,[],!1,t);let r=(0,ny.getSchemaTypes)(e.schema),n=(0,ny.coerceAndCheckDataType)(e,r);ay(e,r,!n,t)}o(py,"typeAndKeywords");function Vk(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Yt.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(Vk,"checkRefsAndKeywords");function Fk(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Yt.checkStrictMode)(e,"default is ignored in the schema root")}o(Fk,"checkNoDefault");function Zk(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,qk.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o(Zk,"updateContext");function Kk(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(Kk,"checkAsyncSchema");function my({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,O._)`${H.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let s=(0,O.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,O._)`${H.default.self}.opts.$comment(${i}, ${s}, ${c}.schema)`)}}o(my,"commentKeyword");function Jk(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,O._)`${H.default.errors} === 0`,()=>t.return(H.default.data),()=>t.throw((0,O._)`new ${a}(${H.default.vErrors})`)):(t.assign((0,O._)`${n}.errors`,H.default.vErrors),i.unevaluated&&Wk(e),t.return((0,O._)`${H.default.errors} === 0`))}o(Jk,"returnResults");function Wk({gen:e,evaluated:t,props:r,items:n}){r instanceof O.Name&&e.assign((0,O._)`${t}.props`,r),n instanceof O.Name&&e.assign((0,O._)`${t}.items`,n)}o(Wk,"assignEvaluated");function ay(e,t,r,n){let{gen:a,schema:i,data:s,allErrors:c,opts:d,self:p}=e,{RULES:l}=p;if(i.$ref&&(d.ignoreKeywordsWithRef||!(0,Yt.schemaHasRulesButRef)(i,l))){a.block(()=>hy(e,"$ref",l.all.$ref.definition));return}d.jtd||Yk(e,t),a.block(()=>{for(let h of l.rules)m(h);m(l.post)});function m(h){(0,Bd.shouldUseGroup)(i,h)&&(h.type?(a.if((0,Qi.checkDataType)(h.type,s,d.strictNumbers)),iy(e,h),t.length===1&&t[0]===h.type&&r&&(a.else(),(0,Qi.reportTypeError)(e)),a.endIf()):iy(e,h),c||a.if((0,O._)`${H.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(ay,"schemaKeywords");function iy(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,Mk.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Bd.shouldUseRule)(n,i)&&hy(e,i.keyword,i.definition,t.type)})}o(iy,"iterateKeywords");function Yk(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Qk(e,t),e.opts.allowUnionTypes||Xk(e,t),eT(e,e.dataTypes))}o(Yk,"checkStrictTypes");function Qk(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{fy(e.dataTypes,r)||Gd(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),rT(e,t)}}o(Qk,"checkContextTypes");function Xk(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Gd(e,"use allowUnionTypes to allow union type keyword")}o(Xk,"checkMultipleTypes");function eT(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,Bd.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(s=>tT(t,s))&&Gd(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}o(eT,"checkKeywordTypes");function tT(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(tT,"hasApplicableType");function fy(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(fy,"includesType");function rT(e,t){let r=[];for(let n of e.dataTypes)fy(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(rT,"narrowSchemaTypes");function Gd(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Yt.checkStrictMode)(e,t,e.opts.strictTypes)}o(Gd,"strictTypesError");var Xi=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,fa.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Yt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",gy(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,fa.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",H.default.errors))}result(t,r,n){this.failResult((0,O.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,O.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,O._)`${r} !== undefined && (${(0,O.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?ma.reportExtraError:ma.reportError)(this,this.def.error,r)}$dataError(){(0,ma.reportError)(this,this.def.$dataError||ma.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ma.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=O.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=O.nil,r=O.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:s}=this;n.if((0,O.or)((0,O._)`${a} === undefined`,r)),t!==O.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==O.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,O.or)(s(),c());function s(){if(n.length){if(!(r instanceof O.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,O._)`${(0,Qi.checkDataTypes)(d,r,i.opts.strictNumbers,Qi.DataType.Wrong)}`}return O.nil}function c(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,O._)`!${d}(${r})`}return O.nil}}subschema(t,r){let n=(0,Ld.getSubschema)(this.it,t);(0,Ld.extendSubschemaData)(n,this.it,t),(0,Ld.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return Bk(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Yt.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Yt.mergeEvaluated.items(a,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:a}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return a.if(r,()=>this.mergeEvaluated(t,O.Name)),!0}};Cr.KeywordCxt=Xi;function hy(e,t,r,n){let a=new Xi(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,fa.funcKeywordCode)(a,r):"macro"in r?(0,fa.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,fa.funcKeywordCode)(a,r)}o(hy,"keywordCode");var nT=/^\/(?:[^~]|~0|~1)*$/,oT=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function gy(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return H.default.rootData;if(e[0]==="/"){if(!nT.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=H.default.rootData}else{let p=oT.exec(e);if(!p)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+p[1];if(a=p[2],a==="#"){if(l>=t)throw new Error(d("property/index",l));return n[t-l]}if(l>t)throw new Error(d("data",l));if(i=r[t-l],!a)return i}let s=i,c=a.split("/");for(let p of c)p&&(i=(0,O._)`${i}${(0,O.getProperty)((0,Yt.unescapeJsonPointer)(p))}`,s=(0,O._)`${s} && ${i}`);return s;function d(p,l){return`Cannot access ${p} ${l} levels up, current level is ${t}`}}o(gy,"getData");Cr.getData=gy});var es=x(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Vd=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Fd.default=Vd});var ga=x(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var Zd=pa(),Kd=class extends Error{static{o(this,"MissingRefError")}constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Zd.resolveUrl)(t,r,n),this.missingSchema=(0,Zd.normalizeId)((0,Zd.getFullPath)(t,this.missingRef))}};Jd.default=Kd});var rs=x(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.resolveSchema=ft.getCompilingSchema=ft.resolveRef=ft.compileSchema=ft.SchemaEnv=void 0;var wt=V(),aT=es(),rn=Wt(),vt=pa(),yy=te(),iT=ha(),Wn=class{static{o(this,"SchemaEnv")}constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,vt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};ft.SchemaEnv=Wn;function Yd(e){let t=Sy.call(this,e);if(t)return t;let r=(0,vt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,s=new wt.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),c;e.$async&&(c=s.scopeValue("Error",{ref:aT.default,code:(0,wt._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");e.validateName=d;let p={gen:s,allErrors:this.opts.allErrors,data:rn.default.data,parentData:rn.default.parentData,parentDataProperty:rn.default.parentDataProperty,dataNames:[rn.default.data],dataPathArr:[wt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,wt.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:wt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,wt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,iT.validateFunctionCode)(p),s.optimize(this.opts.code.optimize);let m=s.toString();l=`${s.scopeRefs(rn.default.scope)}return ${m}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let y=new Function(`${rn.default.self}`,`${rn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{ref:y}),y.errors=null,y.schema=e.schema,y.schemaEnv=e,e.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:d,validateCode:m,scopeValues:s._values}),this.opts.unevaluated){let{props:_,items:S}=p;y.evaluated={props:_ instanceof wt.Name?void 0:_,items:S instanceof wt.Name?void 0:S,dynamicProps:_ instanceof wt.Name,dynamicItems:S instanceof wt.Name},y.source&&(y.source.evaluated=(0,wt.stringify)(y.evaluated))}return e.validate=y,e}catch(m){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),m}finally{this._compilations.delete(e)}}o(Yd,"compileSchema");ft.compileSchema=Yd;function sT(e,t,r){var n;r=(0,vt.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=dT.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:c}=this.opts;s&&(i=new Wn({schema:s,schemaId:c,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=cT.call(this,i)}o(sT,"resolveRef");ft.resolveRef=sT;function cT(e){return(0,vt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Yd.call(this,e)}o(cT,"inlineOrCompile");function Sy(e){for(let t of this._compilations)if(uT(t,e))return t}o(Sy,"getCompilingSchema");ft.getCompilingSchema=Sy;function uT(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(uT,"sameSchemaEnv");function dT(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||ts.call(this,e,t)}o(dT,"resolve");function ts(e,t){let r=this.opts.uriResolver.parse(t),n=(0,vt._getFullPath)(this.opts.uriResolver,r),a=(0,vt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return Wd.call(this,r,e);let i=(0,vt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let c=ts.call(this,e,s);return typeof c?.schema!="object"?void 0:Wd.call(this,r,c)}if(typeof s?.schema=="object"){if(s.validate||Yd.call(this,s),i===(0,vt.normalizeId)(t)){let{schema:c}=s,{schemaId:d}=this.opts,p=c[d];return p&&(a=(0,vt.resolveUrl)(this.opts.uriResolver,a,p)),new Wn({schema:c,schemaId:d,root:e,baseId:a})}return Wd.call(this,r,s)}}o(ts,"resolveSchema");ft.resolveSchema=ts;var lT=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Wd(e,{baseId:t,schema:r,root:n}){var a;if(((a=e.fragment)===null||a===void 0?void 0:a[0])!=="/")return;for(let c of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let d=r[(0,yy.unescapeFragment)(c)];if(d===void 0)return;r=d;let p=typeof r=="object"&&r[this.opts.schemaId];!lT.has(c)&&p&&(t=(0,vt.resolveUrl)(this.opts.uriResolver,t,p))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,yy.schemaHasRulesButRef)(r,this.RULES)){let c=(0,vt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=ts.call(this,n,c)}let{schemaId:s}=this.opts;if(i=i||new Wn({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}o(Wd,"getJsonPointer")});var _y=x((m9,pT)=>{pT.exports={$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 Xd=x((f9,Ry)=>{"use strict";var mT=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),vy=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 Qd(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}o(Qd,"stringArrayToHexStripped");var fT=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function wy(e){return e.length=0,!0}o(wy,"consumeIsZone");function hT(e,t,r){if(e.length){let n=Qd(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(hT,"consumeHextets");function gT(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,s=!1,c=hT;for(let d=0;d<e.length;d++){let p=e[d];if(!(p==="["||p==="]"))if(p===":"){if(i===!0&&(s=!0),!c(a,n,r))break;if(++t>7){r.error=!0;break}d>0&&e[d-1]===":"&&(i=!0),n.push(":");continue}else if(p==="%"){if(!c(a,n,r))break;c=wy}else{a.push(p);continue}}return a.length&&(c===wy?r.zone=a.join(""):s?n.push(a.join("")):n.push(Qd(a))),r.address=n.join(""),r}o(gT,"getIPV6");function by(e){if(yT(e,":")<2)return{host:e,isIPV6:!1};let t=gT(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}o(by,"normalizeIPv6");function yT(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(yT,"findToken");function ST(e){let t=e,r=[],n=-1,a=0;for(;a=t.length;){if(a===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(a===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(a===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}o(ST,"removeDotSegments");function _T(e,t){let r=t!==!0?escape:unescape;return e.scheme!==void 0&&(e.scheme=r(e.scheme)),e.userinfo!==void 0&&(e.userinfo=r(e.userinfo)),e.host!==void 0&&(e.host=r(e.host)),e.path!==void 0&&(e.path=r(e.path)),e.query!==void 0&&(e.query=r(e.query)),e.fragment!==void 0&&(e.fragment=r(e.fragment)),e}o(_T,"normalizeComponentEncoding");function wT(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!vy(r)){let n=by(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=e.host}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}o(wT,"recomposeAuthority");Ry.exports={nonSimpleDomain:fT,recomposeAuthority:wT,normalizeComponentEncoding:_T,removeDotSegments:ST,isIPv4:vy,isUUID:mT,normalizeIPv6:by,stringArrayToHexStripped:Qd}});var Ay=x((g9,xy)=>{"use strict";var{isUUID:vT}=Xd(),bT=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,RT=["http","https","ws","wss","urn","urn:uuid"];function CT(e){return RT.indexOf(e)!==-1}o(CT,"isValidSchemeName");function el(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}o(el,"wsIsSecure");function Cy(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(Cy,"httpParse");function Iy(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}o(Iy,"httpSerialize");function IT(e){return e.secure=el(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(IT,"wsParse");function PT(e){if((e.port===(el(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}o(PT,"wsSerialize");function xT(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(bT);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let a=`${n}:${t.nid||e.nid}`,i=tl(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(xT,"urnParse");function AT(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=`${r}:${t.nid||n}`,i=tl(a);i&&(e=i.serialize(e,t));let s=e,c=e.nss;return s.path=`${n||t.nid}:${c}`,t.skipEscape=!0,s}o(AT,"urnSerialize");function kT(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!vT(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}o(kT,"urnuuidParse");function TT(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(TT,"urnuuidSerialize");var Py={scheme:"http",domainHost:!0,parse:Cy,serialize:Iy},ET={scheme:"https",domainHost:Py.domainHost,parse:Cy,serialize:Iy},ns={scheme:"ws",domainHost:!0,parse:IT,serialize:PT},UT={scheme:"wss",domainHost:ns.domainHost,parse:ns.parse,serialize:ns.serialize},OT={scheme:"urn",parse:xT,serialize:AT,skipNormalize:!0},$T={scheme:"urn:uuid",parse:kT,serialize:TT,skipNormalize:!0},os={http:Py,https:ET,ws:ns,wss:UT,urn:OT,"urn:uuid":$T};Object.setPrototypeOf(os,null);function tl(e){return e&&(os[e]||os[e.toLowerCase()])||void 0}o(tl,"getSchemeHandler");xy.exports={wsIsSecure:el,SCHEMES:os,isValidSchemeName:CT,getSchemeHandler:tl}});var Ey=x((S9,is)=>{"use strict";var{normalizeIPv6:zT,removeDotSegments:ya,recomposeAuthority:MT,normalizeComponentEncoding:as,isIPv4:qT,nonSimpleDomain:NT}=Xd(),{SCHEMES:jT,getSchemeHandler:ky}=Ay();function DT(e,t){return typeof e=="string"?e=Et(Qt(e,t),t):typeof e=="object"&&(e=Qt(Et(e,t),t)),e}o(DT,"normalize");function HT(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=Ty(Qt(e,n),Qt(t,n),n,!0);return n.skipEscape=!0,Et(a,n)}o(HT,"resolve");function Ty(e,t,r,n){let a={};return n||(e=Qt(Et(e,r),r),t=Qt(Et(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=ya(t.path||""),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=ya(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=ya(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path="/"+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path,a.path=ya(a.path)),a.query=t.query):(a.path=e.path,t.query!==void 0?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}o(Ty,"resolveComponent");function LT(e,t,r){return typeof e=="string"?(e=unescape(e),e=Et(as(Qt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Et(as(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=Et(as(Qt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Et(as(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(LT,"equal");function Et(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),a=[],i=ky(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&a.push(r.scheme,":");let s=MT(r);if(s!==void 0&&(n.reference!=="suffix"&&a.push("//"),a.push(s),r.path&&r.path[0]!=="/"&&a.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(c=ya(c)),s===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),a.push(c)}return r.query!==void 0&&a.push("?",r.query),r.fragment!==void 0&&a.push("#",r.fragment),a.join("")}o(Et,"serialize");var BT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Qt(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},a=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(BT);if(i){if(n.scheme=i[1],n.userinfo=i[3],n.host=i[4],n.port=parseInt(i[5],10),n.path=i[6]||"",n.query=i[7],n.fragment=i[8],isNaN(n.port)&&(n.port=i[5]),n.host)if(qT(n.host)===!1){let d=zT(n.host);n.host=d.host.toLowerCase(),a=d.isIPV6}else a=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=ky(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&a===!1&&NT(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(c){n.error=n.error||"Host's domain name can not be converted to ASCII: "+c}(!s||s&&!s.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}o(Qt,"parse");var rl={SCHEMES:jT,normalize:DT,resolve:HT,resolveComponent:Ty,equal:LT,serialize:Et,parse:Qt};is.exports=rl;is.exports.default=rl;is.exports.fastUri=rl});var Oy=x(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});var Uy=Ey();Uy.code='require("ajv/dist/runtime/uri").default';nl.default=Uy});var Hy=x(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.CodeGen=Oe.Name=Oe.nil=Oe.stringify=Oe.str=Oe._=Oe.KeywordCxt=void 0;var GT=ha();Object.defineProperty(Oe,"KeywordCxt",{enumerable:!0,get:o(function(){return GT.KeywordCxt},"get")});var Yn=V();Object.defineProperty(Oe,"_",{enumerable:!0,get:o(function(){return Yn._},"get")});Object.defineProperty(Oe,"str",{enumerable:!0,get:o(function(){return Yn.str},"get")});Object.defineProperty(Oe,"stringify",{enumerable:!0,get:o(function(){return Yn.stringify},"get")});Object.defineProperty(Oe,"nil",{enumerable:!0,get:o(function(){return Yn.nil},"get")});Object.defineProperty(Oe,"Name",{enumerable:!0,get:o(function(){return Yn.Name},"get")});Object.defineProperty(Oe,"CodeGen",{enumerable:!0,get:o(function(){return Yn.CodeGen},"get")});var VT=es(),Ny=ga(),FT=Ud(),Sa=rs(),ZT=V(),_a=pa(),ss=la(),al=te(),$y=_y(),KT=Oy(),jy=o((e,t)=>new RegExp(e,t),"defaultRegExp");jy.code="new RegExp";var JT=["removeAdditional","useDefaults","coerceTypes"],WT=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),YT={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."},QT={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},zy=200;function XT(e){var t,r,n,a,i,s,c,d,p,l,m,h,y,_,S,w,v,b,R,M,q,Me,it,Sn,or;let qt=e.strict,Ur=(t=e.code)===null||t===void 0?void 0:t.optimize,po=Ur===!0||Ur===void 0?1:Ur||0,mo=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:jy,fo=(a=e.uriResolver)!==null&&a!==void 0?a:KT.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:qt)!==null&&s!==void 0?s:!0,strictNumbers:(d=(c=e.strictNumbers)!==null&&c!==void 0?c:qt)!==null&&d!==void 0?d:!0,strictTypes:(l=(p=e.strictTypes)!==null&&p!==void 0?p:qt)!==null&&l!==void 0?l:"log",strictTuples:(h=(m=e.strictTuples)!==null&&m!==void 0?m:qt)!==null&&h!==void 0?h:"log",strictRequired:(_=(y=e.strictRequired)!==null&&y!==void 0?y:qt)!==null&&_!==void 0?_:!1,code:e.code?{...e.code,optimize:po,regExp:mo}:{optimize:po,regExp:mo},loopRequired:(S=e.loopRequired)!==null&&S!==void 0?S:zy,loopEnum:(w=e.loopEnum)!==null&&w!==void 0?w:zy,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(R=e.inlineRefs)!==null&&R!==void 0?R:!0,schemaId:(M=e.schemaId)!==null&&M!==void 0?M:"$id",addUsedSchema:(q=e.addUsedSchema)!==null&&q!==void 0?q:!0,validateSchema:(Me=e.validateSchema)!==null&&Me!==void 0?Me:!0,validateFormats:(it=e.validateFormats)!==null&&it!==void 0?it:!0,unicodeRegExp:(Sn=e.unicodeRegExp)!==null&&Sn!==void 0?Sn:!0,int32range:(or=e.int32range)!==null&&or!==void 0?or:!0,uriResolver:fo}}o(XT,"requiredOptions");var wa=class{static{o(this,"Ajv")}constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...XT(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new ZT.ValueScope({scope:{},prefixes:WT,es5:r,lines:n}),this.logger=a0(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,FT.getRules)(),My.call(this,YT,t,"NOT SUPPORTED"),My.call(this,QT,t,"DEPRECATED","warn"),this._metaOpts=n0.call(this),t.formats&&t0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&r0.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),e0.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=$y;n==="id"&&(a={...$y},a.id=a.$id,delete a.$id),r&&t&&this.addMetaSchema(a,a[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let a=n(r);return"$async"in n||(this.errors=n.errors),a}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return a.call(this,t,r);async function a(l,m){await i.call(this,l.$schema);let h=this._addSchema(l,m);return h.validate||s.call(this,h)}async function i(l){l&&!this.getSchema(l)&&await a.call(this,{$ref:l},!0)}async function s(l){try{return this._compileSchemaEnv(l)}catch(m){if(!(m instanceof Ny.default))throw m;return c.call(this,m),await d.call(this,m.missingSchema),s.call(this,l)}}function c({missingSchema:l,missingRef:m}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${m} cannot be resolved`)}async function d(l){let m=await p.call(this,l);this.refs[l]||await i.call(this,m.$schema),this.refs[l]||this.addSchema(m,l,r)}async function p(l){let m=this._loading[l];if(m)return m;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,a=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,a);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,_a.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,a,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$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;let a=this.validate(n,t);if(!a&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return a}getSchema(t){let r;for(;typeof(r=qy.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new Sa.SchemaEnv({schema:{},schemaId:n});if(r=Sa.resolveSchema.call(this,a,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=qy.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,_a.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.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(s0.call(this,n,r),!r)return(0,al.eachItem)(n,i=>ol.call(this,i)),this;u0.call(this,r);let a={...r,type:(0,ss.getJSONTypes)(r.type),schemaType:(0,ss.getJSONTypes)(r.schemaType)};return(0,al.eachItem)(n,a.type.length===0?i=>ol.call(this,i,a):i=>a.type.forEach(s=>ol.call(this,i,a,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let a=n.rules.findIndex(i=>i.keyword===t);a>=0&&n.rules.splice(a,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(a=>`${n}${a.instancePath} ${a.message}`).reduce((a,i)=>a+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let i=a.split("/").slice(1),s=t;for(let c of i)s=s[c];for(let c in n){let d=n[c];if(typeof d!="object")continue;let{$data:p}=d.definition,l=s[c];p&&l&&(s[c]=Dy(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let a=t[n];(!r||r.test(n))&&(typeof a=="string"?delete t[n]:a&&!a.meta&&(this._cache.delete(a.schema),delete t[n]))}}_addSchema(t,r,n,a=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:c}=this.opts;if(typeof t=="object")s=t[c];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let d=this._cache.get(t);if(d!==void 0)return d;n=(0,_a.normalizeId)(s||n);let p=_a.getSchemaRefs.call(this,t,n);return d=new Sa.SchemaEnv({schema:t,schemaId:c,meta:r,baseId:n,localRefs:p}),this._cache.set(d.schema,d),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),a&&this.validateSchema(t,!0),d}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):Sa.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{Sa.compileSchema.call(this,t)}finally{this.opts=r}}};wa.ValidationError=VT.default;wa.MissingRefError=Ny.default;Oe.default=wa;function My(e,t,r,n="error"){for(let a in e){let i=a;i in t&&this.logger[n](`${r}: option ${a}. ${e[i]}`)}}o(My,"checkOptions");function qy(e){return e=(0,_a.normalizeId)(e),this.schemas[e]||this.refs[e]}o(qy,"getSchEnv");function e0(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}o(e0,"addInitialSchemas");function t0(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(t0,"addInitialFormats");function r0(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}o(r0,"addInitialKeywords");function n0(){let e={...this.opts};for(let t of JT)delete e[t];return e}o(n0,"getMetaSchemaOptions");var o0={log(){},warn(){},error(){}};function a0(e){if(e===!1)return o0;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}o(a0,"getLogger");var i0=/^[a-z_$][a-z0-9_$:-]*$/i;function s0(e,t){let{RULES:r}=this;if((0,al.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!i0.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}o(s0,"checkKeyword");function ol(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=a?i.post:i.rules.find(({type:d})=>d===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,ss.getJSONTypes)(t.type),schemaType:(0,ss.getJSONTypes)(t.schemaType)}};t.before?c0.call(this,s,c,t.before):s.rules.push(c),i.all[e]=c,(n=t.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}o(ol,"addRule");function c0(e,t,r){let n=e.rules.findIndex(a=>a.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}o(c0,"addBeforeRule");function u0(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Dy(t)),e.validateSchema=this.compile(t,!0))}o(u0,"keywordMetaschema");var d0={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Dy(e){return{anyOf:[e,d0]}}o(Dy,"schemaOrData")});var Ly=x(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var l0={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};il.default=l0});var Fy=x(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.callRef=nn.getValidate=void 0;var p0=ga(),By=mt(),rt=V(),Qn=Wt(),Gy=rs(),cs=te(),m0={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:a,schemaEnv:i,validateName:s,opts:c,self:d}=n,{root:p}=i;if((r==="#"||r==="#/")&&a===p.baseId)return m();let l=Gy.resolveRef.call(d,p,a,r);if(l===void 0)throw new p0.default(n.opts.uriResolver,a,r);if(l instanceof Gy.SchemaEnv)return h(l);return y(l);function m(){if(i===p)return us(e,s,i,i.$async);let _=t.scopeValue("root",{ref:p});return us(e,(0,rt._)`${_}.validate`,p,p.$async)}function h(_){let S=Vy(e,_);us(e,S,_,_.$async)}function y(_){let S=t.scopeValue("schema",c.code.source===!0?{ref:_,code:(0,rt.stringify)(_)}:{ref:_}),w=t.name("valid"),v=e.subschema({schema:_,dataTypes:[],schemaPath:rt.nil,topSchemaRef:S,errSchemaPath:r},w);e.mergeEvaluated(v),e.ok(w)}}};function Vy(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,rt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(Vy,"getValidate");nn.getValidate=Vy;function us(e,t,r,n){let{gen:a,it:i}=e,{allErrors:s,schemaEnv:c,opts:d}=i,p=d.passContext?Qn.default.this:rt.nil;n?l():m();function l(){if(!c.$async)throw new Error("async schema referenced by sync schema");let _=a.let("valid");a.try(()=>{a.code((0,rt._)`await ${(0,By.callValidateCode)(e,t,p)}`),y(t),s||a.assign(_,!0)},S=>{a.if((0,rt._)`!(${S} instanceof ${i.ValidationError})`,()=>a.throw(S)),h(S),s||a.assign(_,!1)}),e.ok(_)}o(l,"callAsyncRef");function m(){e.result((0,By.callValidateCode)(e,t,p),()=>y(t),()=>h(t))}o(m,"callSyncRef");function h(_){let S=(0,rt._)`${_}.errors`;a.assign(Qn.default.vErrors,(0,rt._)`${Qn.default.vErrors} === null ? ${S} : ${Qn.default.vErrors}.concat(${S})`),a.assign(Qn.default.errors,(0,rt._)`${Qn.default.vErrors}.length`)}o(h,"addErrorsFrom");function y(_){var S;if(!i.opts.unevaluated)return;let w=(S=r?.validate)===null||S===void 0?void 0:S.evaluated;if(i.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(i.props=cs.mergeEvaluated.props(a,w.props,i.props));else{let v=a.var("props",(0,rt._)`${_}.evaluated.props`);i.props=cs.mergeEvaluated.props(a,v,i.props,rt.Name)}if(i.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(i.items=cs.mergeEvaluated.items(a,w.items,i.items));else{let v=a.var("items",(0,rt._)`${_}.evaluated.items`);i.items=cs.mergeEvaluated.items(a,v,i.items,rt.Name)}}o(y,"addEvaluatedFrom")}o(us,"callRef");nn.callRef=us;nn.default=m0});var Zy=x(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});var f0=Ly(),h0=Fy(),g0=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",f0.default,h0.default];sl.default=g0});var Ky=x(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var ds=V(),Ir=ds.operators,ls={maximum:{okStr:"<=",ok:Ir.LTE,fail:Ir.GT},minimum:{okStr:">=",ok:Ir.GTE,fail:Ir.LT},exclusiveMaximum:{okStr:"<",ok:Ir.LT,fail:Ir.GTE},exclusiveMinimum:{okStr:">",ok:Ir.GT,fail:Ir.LTE}},y0={message:o(({keyword:e,schemaCode:t})=>(0,ds.str)`must be ${ls[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,ds._)`{comparison: ${ls[e].okStr}, limit: ${t}}`,"params")},S0={keyword:Object.keys(ls),type:"number",schemaType:"number",$data:!0,error:y0,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ds._)`${r} ${ls[t].fail} ${n} || isNaN(${r})`)}};cl.default=S0});var Jy=x(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var va=V(),_0={message:o(({schemaCode:e})=>(0,va.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,va._)`{multipleOf: ${e}}`,"params")},w0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:_0,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,s=t.let("res"),c=i?(0,va._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,va._)`${s} !== parseInt(${s})`;e.fail$data((0,va._)`(${n} === 0 || (${s} = ${r}/${n}, ${c}))`)}};ul.default=w0});var Yy=x(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});function Wy(e){let t=e.length,r=0,n=0,a;for(;n<t;)r++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<t&&(a=e.charCodeAt(n),(a&64512)===56320&&n++);return r}o(Wy,"ucs2length");dl.default=Wy;Wy.code='require("ajv/dist/runtime/ucs2length").default'});var Qy=x(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var on=V(),v0=te(),b0=Yy(),R0={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,on.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,on._)`{limit: ${e}}`,"params")},C0={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:R0,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?on.operators.GT:on.operators.LT,s=a.opts.unicode===!1?(0,on._)`${r}.length`:(0,on._)`${(0,v0.useFunc)(e.gen,b0.default)}(${r})`;e.fail$data((0,on._)`${s} ${i} ${n}`)}};ll.default=C0});var Xy=x(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var I0=mt(),ps=V(),P0={message:o(({schemaCode:e})=>(0,ps.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,ps._)`{pattern: ${e}}`,"params")},x0={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:P0,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:i}=e,s=i.opts.unicodeRegExp?"u":"",c=r?(0,ps._)`(new RegExp(${a}, ${s}))`:(0,I0.usePattern)(e,n);e.fail$data((0,ps._)`!${c}.test(${t})`)}};pl.default=x0});var eS=x(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});var ba=V(),A0={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,ba.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,ba._)`{limit: ${e}}`,"params")},k0={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:A0,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?ba.operators.GT:ba.operators.LT;e.fail$data((0,ba._)`Object.keys(${r}).length ${a} ${n}`)}};ml.default=k0});var tS=x(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});var Ra=mt(),Ca=V(),T0=te(),E0={message:o(({params:{missingProperty:e}})=>(0,Ca.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,Ca._)`{missingProperty: ${e}}`,"params")},U0={keyword:"required",type:"object",schemaType:"array",$data:!0,error:E0,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:i,it:s}=e,{opts:c}=s;if(!i&&r.length===0)return;let d=r.length>=c.loopRequired;if(s.allErrors?p():l(),c.strictRequired){let y=e.parentSchema.properties,{definedProperties:_}=e.it;for(let S of r)if(y?.[S]===void 0&&!_.has(S)){let w=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${S}" is not defined at "${w}" (strictRequired)`;(0,T0.checkStrictMode)(s,v,s.opts.strictRequired)}}function p(){if(d||i)e.block$data(Ca.nil,m);else for(let y of r)(0,Ra.checkReportMissingProp)(e,y)}o(p,"allErrorsMode");function l(){let y=t.let("missing");if(d||i){let _=t.let("valid",!0);e.block$data(_,()=>h(y,_)),e.ok(_)}else t.if((0,Ra.checkMissingProp)(e,r,y)),(0,Ra.reportMissingProp)(e,y),t.else()}o(l,"exitOnErrorMode");function m(){t.forOf("prop",n,y=>{e.setParams({missingProperty:y}),t.if((0,Ra.noPropertyInData)(t,a,y,c.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function h(y,_){e.setParams({missingProperty:y}),t.forOf(y,n,()=>{t.assign(_,(0,Ra.propertyInData)(t,a,y,c.ownProperties)),t.if((0,Ca.not)(_),()=>{e.error(),t.break()})},Ca.nil)}o(h,"loopUntilMissing")}};fl.default=U0});var rS=x(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});var Ia=V(),O0={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Ia.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,Ia._)`{limit: ${e}}`,"params")},$0={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:O0,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?Ia.operators.GT:Ia.operators.LT;e.fail$data((0,Ia._)`${r}.length ${a} ${n}`)}};hl.default=$0});var ms=x(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});var nS=Dd();nS.code='require("ajv/dist/runtime/equal").default';gl.default=nS});var oS=x(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var yl=la(),$e=V(),z0=te(),M0=ms(),q0={message:o(({params:{i:e,j:t}})=>(0,$e.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,$e._)`{i: ${e}, j: ${t}}`,"params")},N0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:q0,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:i,schemaCode:s,it:c}=e;if(!n&&!a)return;let d=t.let("valid"),p=i.items?(0,yl.getSchemaTypes)(i.items):[];e.block$data(d,l,(0,$e._)`${s} === false`),e.ok(d);function l(){let _=t.let("i",(0,$e._)`${r}.length`),S=t.let("j");e.setParams({i:_,j:S}),t.assign(d,!0),t.if((0,$e._)`${_} > 1`,()=>(m()?h:y)(_,S))}o(l,"validateUniqueItems");function m(){return p.length>0&&!p.some(_=>_==="object"||_==="array")}o(m,"canOptimize");function h(_,S){let w=t.name("item"),v=(0,yl.checkDataTypes)(p,w,c.opts.strictNumbers,yl.DataType.Wrong),b=t.const("indices",(0,$e._)`{}`);t.for((0,$e._)`;${_}--;`,()=>{t.let(w,(0,$e._)`${r}[${_}]`),t.if(v,(0,$e._)`continue`),p.length>1&&t.if((0,$e._)`typeof ${w} == "string"`,(0,$e._)`${w} += "_"`),t.if((0,$e._)`typeof ${b}[${w}] == "number"`,()=>{t.assign(S,(0,$e._)`${b}[${w}]`),e.error(),t.assign(d,!1).break()}).code((0,$e._)`${b}[${w}] = ${_}`)})}o(h,"loopN");function y(_,S){let w=(0,z0.useFunc)(t,M0.default),v=t.name("outer");t.label(v).for((0,$e._)`;${_}--;`,()=>t.for((0,$e._)`${S} = ${_}; ${S}--;`,()=>t.if((0,$e._)`${w}(${r}[${_}], ${r}[${S}])`,()=>{e.error(),t.assign(d,!1).break(v)})))}o(y,"loopN2")}};Sl.default=N0});var aS=x(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});var _l=V(),j0=te(),D0=ms(),H0={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,_l._)`{allowedValue: ${e}}`,"params")},L0={keyword:"const",$data:!0,error:H0,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,_l._)`!${(0,j0.useFunc)(t,D0.default)}(${r}, ${a})`):e.fail((0,_l._)`${i} !== ${r}`)}};wl.default=L0});var iS=x(vl=>{"use strict";Object.defineProperty(vl,"__esModule",{value:!0});var Pa=V(),B0=te(),G0=ms(),V0={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,Pa._)`{allowedValues: ${e}}`,"params")},F0={keyword:"enum",schemaType:"array",$data:!0,error:V0,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:i,it:s}=e;if(!n&&a.length===0)throw new Error("enum must have non-empty array");let c=a.length>=s.opts.loopEnum,d,p=o(()=>d??(d=(0,B0.useFunc)(t,G0.default)),"getEql"),l;if(c||n)l=t.let("valid"),e.block$data(l,m);else{if(!Array.isArray(a))throw new Error("ajv implementation error");let y=t.const("vSchema",i);l=(0,Pa.or)(...a.map((_,S)=>h(y,S)))}e.pass(l);function m(){t.assign(l,!1),t.forOf("v",i,y=>t.if((0,Pa._)`${p()}(${r}, ${y})`,()=>t.assign(l,!0).break()))}o(m,"loopEnum");function h(y,_){let S=a[_];return typeof S=="object"&&S!==null?(0,Pa._)`${p()}(${r}, ${y}[${_}])`:(0,Pa._)`${r} === ${S}`}o(h,"equalCode")}};vl.default=F0});var sS=x(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var Z0=Ky(),K0=Jy(),J0=Qy(),W0=Xy(),Y0=eS(),Q0=tS(),X0=rS(),eE=oS(),tE=aS(),rE=iS(),nE=[Z0.default,K0.default,J0.default,W0.default,Y0.default,Q0.default,X0.default,eE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},tE.default,rE.default];bl.default=nE});var Cl=x(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.validateAdditionalItems=void 0;var an=V(),Rl=te(),oE={message:o(({params:{len:e}})=>(0,an.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,an._)`{limit: ${e}}`,"params")},aE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oE,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Rl.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}cS(e,n)}};function cS(e,t){let{gen:r,schema:n,data:a,keyword:i,it:s}=e;s.items=!0;let c=r.const("len",(0,an._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,an._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,Rl.alwaysValidSchema)(s,n)){let p=r.var("valid",(0,an._)`${c} <= ${t.length}`);r.if((0,an.not)(p),()=>d(p)),e.ok(p)}function d(p){r.forRange("i",t.length,c,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:Rl.Type.Num},p),s.allErrors||r.if((0,an.not)(p),()=>r.break())})}o(d,"validateItems")}o(cS,"validateAdditionalItems");xa.validateAdditionalItems=cS;xa.default=aE});var Il=x(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.validateTuple=void 0;var uS=V(),fs=te(),iE=mt(),sE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return dS(e,"additionalItems",t);r.items=!0,!(0,fs.alwaysValidSchema)(r,t)&&e.ok((0,iE.validateArray)(e))}};function dS(e,t,r=e.schema){let{gen:n,parentSchema:a,data:i,keyword:s,it:c}=e;l(a),c.opts.unevaluated&&r.length&&c.items!==!0&&(c.items=fs.mergeEvaluated.items(n,r.length,c.items));let d=n.name("valid"),p=n.const("len",(0,uS._)`${i}.length`);r.forEach((m,h)=>{(0,fs.alwaysValidSchema)(c,m)||(n.if((0,uS._)`${p} > ${h}`,()=>e.subschema({keyword:s,schemaProp:h,dataProp:h},d)),e.ok(d))});function l(m){let{opts:h,errSchemaPath:y}=c,_=r.length,S=_===m.minItems&&(_===m.maxItems||m[t]===!1);if(h.strictTuples&&!S){let w=`"${s}" is ${_}-tuple, but minItems or maxItems/${t} are not specified or different at path "${y}"`;(0,fs.checkStrictMode)(c,w,h.strictTuples)}}o(l,"checkStrictTuple")}o(dS,"validateTuple");Aa.validateTuple=dS;Aa.default=sE});var lS=x(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var cE=Il(),uE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,cE.validateTuple)(e,"items"),"code")};Pl.default=uE});var mS=x(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});var pS=V(),dE=te(),lE=mt(),pE=Cl(),mE={message:o(({params:{len:e}})=>(0,pS.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,pS._)`{limit: ${e}}`,"params")},fE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:mE,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,dE.alwaysValidSchema)(n,t)&&(a?(0,pE.validateAdditionalItems)(e,a):e.ok((0,lE.validateArray)(e)))}};xl.default=fE});var fS=x(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var ht=V(),hs=te(),hE={message:o(({params:{min:e,max:t}})=>t===void 0?(0,ht.str)`must contain at least ${e} valid item(s)`:(0,ht.str)`must contain at least ${e} and no more than ${t} valid item(s)`,"message"),params:o(({params:{min:e,max:t}})=>t===void 0?(0,ht._)`{minContains: ${e}}`:(0,ht._)`{minContains: ${e}, maxContains: ${t}}`,"params")},gE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:hE,code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e,s,c,{minContains:d,maxContains:p}=n;i.opts.next?(s=d===void 0?1:d,c=p):s=1;let l=t.const("len",(0,ht._)`${a}.length`);if(e.setParams({min:s,max:c}),c===void 0&&s===0){(0,hs.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&s>c){(0,hs.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,hs.alwaysValidSchema)(i,r)){let S=(0,ht._)`${l} >= ${s}`;c!==void 0&&(S=(0,ht._)`${S} && ${l} <= ${c}`),e.pass(S);return}i.items=!0;let m=t.name("valid");c===void 0&&s===1?y(m,()=>t.if(m,()=>t.break())):s===0?(t.let(m,!0),c!==void 0&&t.if((0,ht._)`${a}.length > 0`,h)):(t.let(m,!1),h()),e.result(m,()=>e.reset());function h(){let S=t.name("_valid"),w=t.let("count",0);y(S,()=>t.if(S,()=>_(w)))}o(h,"validateItemsWithCount");function y(S,w){t.forRange("i",0,l,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:hs.Type.Num,compositeRule:!0},S),w()})}o(y,"validateItems");function _(S){t.code((0,ht._)`${S}++`),c===void 0?t.if((0,ht._)`${S} >= ${s}`,()=>t.assign(m,!0).break()):(t.if((0,ht._)`${S} > ${c}`,()=>t.assign(m,!1).break()),s===1?t.assign(m,!0):t.if((0,ht._)`${S} >= ${s}`,()=>t.assign(m,!0)))}o(_,"checkLimits")}};Al.default=gE});var yS=x(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.validateSchemaDeps=Ut.validatePropertyDeps=Ut.error=void 0;var kl=V(),yE=te(),ka=mt();Ut.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,kl.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,kl._)`{property: ${e},
30
30
  missingProperty: ${n},
31
31
  depsCount: ${t},
32
- deps: ${r}}`,"params")};var cx={keyword:"dependencies",type:"object",schemaType:"object",error:kt.error,code(e){let[t,r]=ux(e);ah(e,t),ih(e,r)}};function ux({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let a=Array.isArray(e[n])?t:r;a[n]=e[n]}return[t,r]}o(ux,"splitDependencies");function ah(e,t=e.schema){let{gen:r,data:n,it:a}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let c=t[s];if(c.length===0)continue;let d=(0,Yo.propertyInData)(r,n,s,a.opts.ownProperties);e.setParams({property:s,depsCount:c.length,deps:c.join(", ")}),a.allErrors?r.if(d,()=>{for(let p of c)(0,Yo.checkReportMissingProp)(e,p)}):(r.if((0,rd._)`${d} && (${(0,Yo.checkMissingProp)(e,c,i)})`),(0,Yo.reportMissingProp)(e,i),r.else())}}o(ah,"validatePropertyDeps");kt.validatePropertyDeps=ah;function ih(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,s=r.name("valid");for(let c in t)(0,sx.alwaysValidSchema)(i,t[c])||(r.if((0,Yo.propertyInData)(r,n,c,i.opts.ownProperties),()=>{let d=e.subschema({keyword:a,schemaProp:c},s);e.mergeValidEvaluated(d,s)},()=>r.var(s,!0)),e.ok(s))}o(ih,"validateSchemaDeps");kt.validateSchemaDeps=ih;kt.default=cx});var uh=x(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var ch=F(),dx=re(),lx={message:"property name must be valid",params:o(({params:e})=>(0,ch._)`{propertyName: ${e.propertyName}}`,"params")},px={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:lx,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,dx.alwaysValidSchema)(a,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,ch.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};nd.default=px});var ad=x(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var xi=dt(),bt=F(),mx=Vt(),Ai=re(),fx={message:"must NOT have additional properties",params:o(({params:e})=>(0,bt._)`{additionalProperty: ${e.additionalProperty}}`,"params")},hx={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:fx,code(e){let{gen:t,schema:r,parentSchema:n,data:a,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:c,opts:d}=s;if(s.props=!0,d.removeAdditional!=="all"&&(0,Ai.alwaysValidSchema)(s,r))return;let p=(0,xi.allSchemaProperties)(n.properties),l=(0,xi.allSchemaProperties)(n.patternProperties);m(),e.ok((0,bt._)`${i} === ${mx.default.errors}`);function m(){t.forIn("key",a,w=>{!p.length&&!l.length?_(w):t.if(h(w),()=>_(w))})}o(m,"checkAdditionalProperties");function h(w){let v;if(p.length>8){let b=(0,Ai.schemaRefOrVal)(s,n.properties,"properties");v=(0,xi.isOwnProperty)(t,b,w)}else p.length?v=(0,bt.or)(...p.map(b=>(0,bt._)`${w} === ${b}`)):v=bt.nil;return l.length&&(v=(0,bt.or)(v,...l.map(b=>(0,bt._)`${(0,xi.usePattern)(e,b)}.test(${w})`))),(0,bt.not)(v)}o(h,"isAdditional");function y(w){t.code((0,bt._)`delete ${a}[${w}]`)}o(y,"deleteAdditional");function _(w){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){y(w);return}if(r===!1){e.setParams({additionalProperty:w}),e.error(),c||t.break();return}if(typeof r=="object"&&!(0,Ai.alwaysValidSchema)(s,r)){let v=t.name("valid");d.removeAdditional==="failing"?(S(w,v,!1),t.if((0,bt.not)(v),()=>{e.reset(),y(w)})):(S(w,v),c||t.if((0,bt.not)(v),()=>t.break()))}}o(_,"additionalPropertyCode");function S(w,v,b){let R={keyword:"additionalProperties",dataProp:w,dataPropType:Ai.Type.Str};b===!1&&Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(R,v)}o(S,"applyAdditionalSchema")}};od.default=hx});var ph=x(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var gx=qo(),dh=dt(),id=re(),lh=ad(),yx={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&lh.default.code(new gx.KeywordCxt(i,lh.default,"additionalProperties"));let s=(0,dh.allSchemaProperties)(r);for(let m of s)i.definedProperties.add(m);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=id.mergeEvaluated.props(t,(0,id.toHash)(s),i.props));let c=s.filter(m=>!(0,id.alwaysValidSchema)(i,r[m]));if(c.length===0)return;let d=t.name("valid");for(let m of c)p(m)?l(m):(t.if((0,dh.propertyInData)(t,a,m,i.opts.ownProperties)),l(m),i.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(m),e.ok(d);function p(m){return i.opts.useDefaults&&!i.compositeRule&&r[m].default!==void 0}o(p,"hasDefault");function l(m){e.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}o(l,"applyPropertySchema")}};sd.default=yx});var gh=x(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var mh=dt(),ki=F(),fh=re(),hh=re(),Sx={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:a,it:i}=e,{opts:s}=i,c=(0,mh.allSchemaProperties)(r),d=c.filter(S=>(0,fh.alwaysValidSchema)(i,r[S]));if(c.length===0||d.length===c.length&&(!i.opts.unevaluated||i.props===!0))return;let p=s.strictSchema&&!s.allowMatchingProperties&&a.properties,l=t.name("valid");i.props!==!0&&!(i.props instanceof ki.Name)&&(i.props=(0,hh.evaluatedPropsToName)(t,i.props));let{props:m}=i;h();function h(){for(let S of c)p&&y(S),i.allErrors?_(S):(t.var(l,!0),_(S),t.if(l))}o(h,"validatePatternProperties");function y(S){for(let w in p)new RegExp(S).test(w)&&(0,fh.checkStrictMode)(i,`property ${w} matches pattern ${S} (use allowMatchingProperties)`)}o(y,"checkMatchingProperties");function _(S){t.forIn("key",n,w=>{t.if((0,ki._)`${(0,mh.usePattern)(e,S)}.test(${w})`,()=>{let v=d.includes(S);v||e.subschema({keyword:"patternProperties",schemaProp:S,dataProp:w,dataPropType:hh.Type.Str},l),i.opts.unevaluated&&m!==!0?t.assign((0,ki._)`${m}[${w}]`,!0):!v&&!i.allErrors&&t.if((0,ki.not)(l),()=>t.break())})})}o(_,"validateProperties")}};cd.default=Sx});var yh=x(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var _x=re(),wx={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,_x.alwaysValidSchema)(n,r)){e.fail();return}let a=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};ud.default=wx});var Sh=x(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var vx=dt(),bx={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:vx.validateUnion,error:{message:"must match a schema in anyOf"}};dd.default=bx});var _h=x(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var Ti=F(),Rx=re(),Cx={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,Ti._)`{passingSchemas: ${e.passing}}`,"params")},Ix={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Cx,code(e){let{gen:t,schema:r,parentSchema:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&n.discriminator)return;let i=r,s=t.let("valid",!1),c=t.let("passing",null),d=t.name("_valid");e.setParams({passing:c}),t.block(p),e.result(s,()=>e.reset(),()=>e.error(!0));function p(){i.forEach((l,m)=>{let h;(0,Rx.alwaysValidSchema)(a,l)?t.var(d,!0):h=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,Ti._)`${d} && ${s}`).assign(s,!1).assign(c,(0,Ti._)`[${c}, ${m}]`).else(),t.if(d,()=>{t.assign(s,!0),t.assign(c,m),h&&e.mergeEvaluated(h,Ti.Name)})})}o(p,"validateOneOf")}};ld.default=Ix});var wh=x(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var Px=re(),xx={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let a=t.name("valid");r.forEach((i,s)=>{if((0,Px.alwaysValidSchema)(n,i))return;let c=e.subschema({keyword:"allOf",schemaProp:s},a);e.ok(a),e.mergeEvaluated(c)})}};pd.default=xx});var Rh=x(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Ei=F(),bh=re(),Ax={message:o(({params:e})=>(0,Ei.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,Ei._)`{failingKeyword: ${e.ifClause}}`,"params")},kx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Ax,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,bh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=vh(n,"then"),i=vh(n,"else");if(!a&&!i)return;let s=t.let("valid",!0),c=t.name("_valid");if(d(),e.reset(),a&&i){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(c,p("then",l),p("else",l))}else a?t.if(c,p("then")):t.if((0,Ei.not)(c),p("else"));e.pass(s,()=>e.error(!0));function d(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);e.mergeEvaluated(l)}o(d,"validateIf");function p(l,m){return()=>{let h=e.subschema({keyword:l},c);t.assign(s,c),e.mergeValidEvaluated(h,s),m?t.assign(m,(0,Ei._)`${l}`):e.setParams({ifClause:l})}}o(p,"validateClause")}};function vh(e,t){let r=e.schema[t];return r!==void 0&&!(0,bh.alwaysValidSchema)(e,r)}o(vh,"hasSchema");md.default=kx});var Ch=x(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var Tx=re(),Ex={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,Tx.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};fd.default=Ex});var Ih=x(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var Ux=Yu(),Ox=th(),$x=Qu(),zx=nh(),Mx=oh(),qx=sh(),Nx=uh(),Dx=ad(),jx=ph(),Hx=gh(),Lx=yh(),Bx=Sh(),Gx=_h(),Vx=wh(),Fx=Rh(),Zx=Ch();function Kx(e=!1){let t=[Lx.default,Bx.default,Gx.default,Vx.default,Fx.default,Zx.default,Nx.default,Dx.default,qx.default,jx.default,Hx.default];return e?t.push(Ox.default,zx.default):t.push(Ux.default,$x.default),t.push(Mx.default),t}o(Kx,"getApplicator");hd.default=Kx});var Ph=x(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var ve=F(),Wx={message:o(({schemaCode:e})=>(0,ve.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,ve._)`{format: ${e}}`,"params")},Jx={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Wx,code(e,t){let{gen:r,data:n,$data:a,schema:i,schemaCode:s,it:c}=e,{opts:d,errSchemaPath:p,schemaEnv:l,self:m}=c;if(!d.validateFormats)return;a?h():y();function h(){let _=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),S=r.const("fDef",(0,ve._)`${_}[${s}]`),w=r.let("fType"),v=r.let("format");r.if((0,ve._)`typeof ${S} == "object" && !(${S} instanceof RegExp)`,()=>r.assign(w,(0,ve._)`${S}.type || "string"`).assign(v,(0,ve._)`${S}.validate`),()=>r.assign(w,(0,ve._)`"string"`).assign(v,S)),e.fail$data((0,ve.or)(b(),R()));function b(){return d.strictSchema===!1?ve.nil:(0,ve._)`${s} && !${v}`}o(b,"unknownFmt");function R(){let q=l.$async?(0,ve._)`(${S}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ve._)`${v}(${n})`,N=(0,ve._)`(typeof ${v} == "function" ? ${q} : ${v}.test(${n}))`;return(0,ve._)`${v} && ${v} !== true && ${w} === ${t} && !${N}`}o(R,"invalidFmt")}o(h,"validate$DataFormat");function y(){let _=m.formats[i];if(!_){b();return}if(_===!0)return;let[S,w,v]=R(_);S===t&&e.pass(q());function b(){if(d.strictSchema===!1){m.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${i}" ignored in schema at path "${p}"`}}o(b,"unknownFormat");function R(N){let qe=N instanceof RegExp?(0,ve.regexpCode)(N):d.code.formats?(0,ve._)`${d.code.formats}${(0,ve.getProperty)(i)}`:void 0,it=r.scopeValue("formats",{key:i,ref:N,code:qe});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,ve._)`${it}.validate`]:["string",N,it]}o(R,"getFormat");function q(){if(typeof _=="object"&&!(_ instanceof RegExp)&&_.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ve._)`await ${v}(${n})`}return typeof w=="function"?(0,ve._)`${v}(${n})`:(0,ve._)`${v}.test(${n})`}o(q,"validCondition")}o(y,"validateFormat")}};gd.default=Jx});var xh=x(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var Yx=Ph(),Qx=[Yx.default];yd.default=Qx});var Ah=x(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.contentVocabulary=An.metadataVocabulary=void 0;An.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];An.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Th=x(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Xx=qf(),eA=Yf(),tA=Ih(),rA=xh(),kh=Ah(),nA=[Xx.default,eA.default,(0,tA.default)(),rA.default,kh.metadataVocabulary,kh.contentVocabulary];Sd.default=nA});var Uh=x(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.DiscrError=void 0;var Eh;(function(e){e.Tag="tag",e.Mapping="mapping"})(Eh||(Ui.DiscrError=Eh={}))});var $h=x(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var kn=F(),_d=Uh(),Oh=mi(),oA=No(),aA=re(),iA={message:o(({params:{discrError:e,tagName:t}})=>e===_d.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,"message"),params:o(({params:{discrError:e,tag:t,tagName:r}})=>(0,kn._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},sA={keyword:"discriminator",type:"object",schemaType:"object",error:iA,code(e){let{gen:t,data:r,schema:n,parentSchema:a,it:i}=e,{oneOf:s}=a;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let d=t.let("valid",!1),p=t.const("tag",(0,kn._)`${r}${(0,kn.getProperty)(c)}`);t.if((0,kn._)`typeof ${p} == "string"`,()=>l(),()=>e.error(!1,{discrError:_d.DiscrError.Tag,tag:p,tagName:c})),e.ok(d);function l(){let y=h();t.if(!1);for(let _ in y)t.elseIf((0,kn._)`${p} === ${_}`),t.assign(d,m(y[_]));t.else(),e.error(!1,{discrError:_d.DiscrError.Mapping,tag:p,tagName:c}),t.endIf()}o(l,"validateMapping");function m(y){let _=t.name("valid"),S=e.subschema({keyword:"oneOf",schemaProp:y},_);return e.mergeEvaluated(S,kn.Name),_}o(m,"applyTagSchema");function h(){var y;let _={},S=v(a),w=!0;for(let q=0;q<s.length;q++){let N=s[q];if(N?.$ref&&!(0,aA.schemaHasRulesButRef)(N,i.self.RULES)){let it=N.$ref;if(N=Oh.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,it),N instanceof Oh.SchemaEnv&&(N=N.schema),N===void 0)throw new oA.default(i.opts.uriResolver,i.baseId,it)}let qe=(y=N?.properties)===null||y===void 0?void 0:y[c];if(typeof qe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);w=w&&(S||v(N)),b(qe,q)}if(!w)throw new Error(`discriminator: "${c}" must be required`);return _;function v({required:q}){return Array.isArray(q)&&q.includes(c)}function b(q,N){if(q.const)R(q.const,N);else if(q.enum)for(let qe of q.enum)R(qe,N);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function R(q,N){if(typeof q!="string"||q in _)throw new Error(`discriminator: "${c}" values must be unique strings`);_[q]=N}}o(h,"getMapping")}};wd.default=sA});var zh=x((uB,cA)=>{cA.exports={$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 bd=x((le,vd)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var uA=Ef(),dA=Th(),lA=$h(),Mh=zh(),pA=["/properties"],Oi="http://json-schema.org/draft-07/schema",Tn=class extends uA.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),dA.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(lA.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Mh,pA):Mh;this.addMetaSchema(t,Oi,!1),this.refs["http://json-schema.org/schema"]=Oi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Oi)?Oi:void 0)}};le.Ajv=Tn;vd.exports=le=Tn;vd.exports.Ajv=Tn;Object.defineProperty(le,"__esModule",{value:!0});le.default=Tn;var mA=qo();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:o(function(){return mA.KeywordCxt},"get")});var En=F();Object.defineProperty(le,"_",{enumerable:!0,get:o(function(){return En._},"get")});Object.defineProperty(le,"str",{enumerable:!0,get:o(function(){return En.str},"get")});Object.defineProperty(le,"stringify",{enumerable:!0,get:o(function(){return En.stringify},"get")});Object.defineProperty(le,"nil",{enumerable:!0,get:o(function(){return En.nil},"get")});Object.defineProperty(le,"Name",{enumerable:!0,get:o(function(){return En.Name},"get")});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:o(function(){return En.CodeGen},"get")});var fA=li();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:o(function(){return fA.default},"get")});var hA=No();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:o(function(){return hA.default},"get")})});var Gh=x(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.formatNames=Et.fastFormats=Et.fullFormats=void 0;function Tt(e,t){return{validate:e,compare:t}}o(Tt,"fmtDef");Et.fullFormats={date:Tt(jh,Pd),time:Tt(Cd(!0),xd),"date-time":Tt(qh(!0),Lh),"iso-time":Tt(Cd(),Hh),"iso-date-time":Tt(qh(),Bh),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:vA,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:AA,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:bA,int32:{type:"number",validate:IA},int64:{type:"number",validate:PA},float:{type:"number",validate:Dh},double:{type:"number",validate:Dh},password:!0,binary:!0};Et.fastFormats={...Et.fullFormats,date:Tt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pd),time:Tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,xd),"date-time":Tt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Lh),"iso-time":Tt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Hh),"iso-date-time":Tt(/^\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,Bh),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Et.formatNames=Object.keys(Et.fullFormats);function gA(e){return e%4===0&&(e%100!==0||e%400===0)}o(gA,"isLeapYear");var yA=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,SA=[0,31,28,31,30,31,30,31,31,30,31,30,31];function jh(e){let t=yA.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n===2&&gA(r)?29:SA[n])}o(jh,"date");function Pd(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(Pd,"compareDate");var Rd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Cd(e){return o(function(r){let n=Rd.exec(r);if(!n)return!1;let a=+n[1],i=+n[2],s=+n[3],c=n[4],d=n[5]==="-"?-1:1,p=+(n[6]||0),l=+(n[7]||0);if(p>23||l>59||e&&!c)return!1;if(a<=23&&i<=59&&s<60)return!0;let m=i-l*d,h=a-p*d-(m<0?1:0);return(h===23||h===-1)&&(m===59||m===-1)&&s<61},"time")}o(Cd,"getTime");function xd(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}o(xd,"compareTime");function Hh(e,t){if(!(e&&t))return;let r=Rd.exec(e),n=Rd.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}o(Hh,"compareIsoTime");var Id=/t|\s/i;function qh(e){let t=Cd(e);return o(function(n){let a=n.split(Id);return a.length===2&&jh(a[0])&&t(a[1])},"date_time")}o(qh,"getDateTime");function Lh(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(Lh,"compareDateTime");function Bh(e,t){if(!(e&&t))return;let[r,n]=e.split(Id),[a,i]=t.split(Id),s=Pd(r,a);if(s!==void 0)return s||xd(n,i)}o(Bh,"compareIsoDateTime");var _A=/\/|:/,wA=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function vA(e){return _A.test(e)&&wA.test(e)}o(vA,"uri");var Nh=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function bA(e){return Nh.lastIndex=0,Nh.test(e)}o(bA,"byte");var RA=-(2**31),CA=2**31-1;function IA(e){return Number.isInteger(e)&&e<=CA&&e>=RA}o(IA,"validateInt32");function PA(e){return Number.isInteger(e)}o(PA,"validateInt64");function Dh(){return!0}o(Dh,"validateNumber");var xA=/[^\\]\\Z/;function AA(e){if(xA.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(AA,"regex")});var Vh=x(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.formatLimitDefinition=void 0;var kA=bd(),Rt=F(),br=Rt.operators,$i={formatMaximum:{okStr:"<=",ok:br.LTE,fail:br.GT},formatMinimum:{okStr:">=",ok:br.GTE,fail:br.LT},formatExclusiveMaximum:{okStr:"<",ok:br.LT,fail:br.GTE},formatExclusiveMinimum:{okStr:">",ok:br.GT,fail:br.LTE}},TA={message:o(({keyword:e,schemaCode:t})=>(0,Rt.str)`should be ${$i[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,Rt._)`{comparison: ${$i[e].okStr}, limit: ${t}}`,"params")};Un.formatLimitDefinition={keyword:Object.keys($i),type:"string",schemaType:"string",$data:!0,error:TA,code(e){let{gen:t,data:r,schemaCode:n,keyword:a,it:i}=e,{opts:s,self:c}=i;if(!s.validateFormats)return;let d=new kA.KeywordCxt(i,c.RULES.all.format.definition,"format");d.$data?p():l();function p(){let h=t.scopeValue("formats",{ref:c.formats,code:s.code.formats}),y=t.const("fmt",(0,Rt._)`${h}[${d.schemaCode}]`);e.fail$data((0,Rt.or)((0,Rt._)`typeof ${y} != "object"`,(0,Rt._)`${y} instanceof RegExp`,(0,Rt._)`typeof ${y}.compare != "function"`,m(y)))}o(p,"validate$DataFormat");function l(){let h=d.schema,y=c.formats[h];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${a}": format "${h}" does not define "compare" function`);let _=t.scopeValue("formats",{key:h,ref:y,code:s.code.formats?(0,Rt._)`${s.code.formats}${(0,Rt.getProperty)(h)}`:void 0});e.fail$data(m(_))}o(l,"validateFormat");function m(h){return(0,Rt._)`${h}.compare(${r}, ${n}) ${$i[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var EA=o(e=>(e.addKeyword(Un.formatLimitDefinition),e),"formatLimitPlugin");Un.default=EA});var Wh=x((Qo,Kh)=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});var On=Gh(),UA=Vh(),Ad=F(),Fh=new Ad.Name("fullFormats"),OA=new Ad.Name("fastFormats"),kd=o((e,t={keywords:!0})=>{if(Array.isArray(t))return Zh(e,t,On.fullFormats,Fh),e;let[r,n]=t.mode==="fast"?[On.fastFormats,OA]:[On.fullFormats,Fh],a=t.formats||On.formatNames;return Zh(e,a,r,n),t.keywords&&(0,UA.default)(e),e},"formatsPlugin");kd.get=(e,t="full")=>{let n=(t==="fast"?On.fastFormats:On.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function Zh(e,t,r,n){var a,i;(a=(i=e.opts.code).formats)!==null&&a!==void 0||(i.formats=(0,Ad._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}o(Zh,"addFormats");Kh.exports=Qo=kd;Object.defineProperty(Qo,"__esModule",{value:!0});Qo.default=kd});wv();function sr(e){return!!e._zod}o(sr,"isZ4Schema");function Ge(e,t){return sr(e)?rc(e,t):e.safeParse(t)}o(Ge,"safeParse");function pn(e){if(!e)return;let t;if(sr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}o(pn,"getObjectShape");function Zp(e){if(sr(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}o(Zp,"getLiteralValue");ue();var ur="2025-11-25",Kp="2025-03-26",dr=[ur,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],lr="io.modelcontextprotocol/related-task",Da="2.0",Ie=Gp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Wp=me([f(),ee().int()]),Jp=f(),xq=Ce({ttl:ee().optional(),pollInterval:ee().optional()}),Rv=I({ttl:ee().optional()}),Cv=I({taskId:f()}),ic=Ce({progressToken:Wp.optional(),[lr]:Cv.optional()}),ot=I({_meta:ic.optional()}),mo=ot.extend({task:Rv.optional()}),Yp=o(e=>mo.safeParse(e).success,"isTaskAugmentedRequestParams"),Ae=I({method:f(),params:ot.loose().optional()}),st=I({_meta:ic.optional()}),ct=I({method:f(),params:st.loose().optional()}),ke=Ce({_meta:ic.optional()}),ja=me([f(),ee().int()]),Qp=I({jsonrpc:O(Da),id:ja,...Ae.shape}).strict(),It=o(e=>Qp.safeParse(e).success,"isJSONRPCRequest"),Xp=I({jsonrpc:O(Da),...ct.shape}).strict(),em=o(e=>Xp.safeParse(e).success,"isJSONRPCNotification"),sc=I({jsonrpc:O(Da),id:ja,result:ke}).strict(),St=o(e=>sc.safeParse(e).success,"isJSONRPCResultResponse");var U;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(U||(U={}));var cc=I({jsonrpc:O(Da),id:ja.optional(),error:I({code:ee().int(),message:f(),data:we().optional()})}).strict();var fn=o(e=>cc.safeParse(e).success,"isJSONRPCErrorResponse");var $r=me([Qp,Xp,sc,cc]),Aq=me([sc,cc]),jt=ke.strict(),Iv=st.extend({requestId:ja.optional(),reason:f().optional()}),Ha=ct.extend({method:O("notifications/cancelled"),params:Iv}),Pv=I({src:f(),mimeType:f().optional(),sizes:C(f()).optional(),theme:nt(["light","dark"]).optional()}),fo=I({icons:C(Pv).optional()}),mn=I({name:f(),title:f().optional()}),hn=mn.extend({...mn.shape,...fo.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),xv=oc(I({applyDefaults:ae().optional()}),ce(f(),we())),Av=ac(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,oc(I({form:xv.optional(),url:Ie.optional()}),ce(f(),we()).optional())),kv=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({sampling:Ce({createMessage:Ie.optional()}).optional(),elicitation:Ce({create:Ie.optional()}).optional()}).optional()}),Tv=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({tools:Ce({call:Ie.optional()}).optional()}).optional()}),Ev=I({experimental:ce(f(),Ie).optional(),sampling:I({context:Ie.optional(),tools:Ie.optional()}).optional(),elicitation:Av.optional(),roots:I({listChanged:ae().optional()}).optional(),tasks:kv.optional(),extensions:ce(f(),Ie).optional()}),Uv=ot.extend({protocolVersion:f(),capabilities:Ev,clientInfo:hn}),La=Ae.extend({method:O("initialize"),params:Uv}),uc=o(e=>La.safeParse(e).success,"isInitializeRequest"),Ov=I({experimental:ce(f(),Ie).optional(),logging:Ie.optional(),completions:Ie.optional(),prompts:I({listChanged:ae().optional()}).optional(),resources:I({subscribe:ae().optional(),listChanged:ae().optional()}).optional(),tools:I({listChanged:ae().optional()}).optional(),tasks:Tv.optional(),extensions:ce(f(),Ie).optional()}),dc=ke.extend({protocolVersion:f(),capabilities:Ov,serverInfo:hn,instructions:f().optional()}),Ba=ct.extend({method:O("notifications/initialized"),params:st.optional()}),tm=o(e=>Ba.safeParse(e).success,"isInitializedNotification"),Ga=Ae.extend({method:O("ping"),params:ot.optional()}),$v=I({progress:ee(),total:ge(ee()),message:ge(f())}),zv=I({...st.shape,...$v.shape,progressToken:Wp}),Va=ct.extend({method:O("notifications/progress"),params:zv}),Mv=ot.extend({cursor:Jp.optional()}),ho=Ae.extend({params:Mv.optional()}),go=ke.extend({nextCursor:Jp.optional()}),qv=nt(["working","input_required","completed","failed","cancelled"]),yo=I({taskId:f(),status:qv,ttl:me([ee(),Lp()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:ge(ee()),statusMessage:ge(f())}),Ht=ke.extend({task:yo}),Nv=st.merge(yo),So=ct.extend({method:O("notifications/tasks/status"),params:Nv}),Fa=Ae.extend({method:O("tasks/get"),params:ot.extend({taskId:f()})}),Za=ke.merge(yo),Ka=Ae.extend({method:O("tasks/result"),params:ot.extend({taskId:f()})}),kq=ke.loose(),Wa=ho.extend({method:O("tasks/list")}),Ja=go.extend({tasks:C(yo)}),Ya=Ae.extend({method:O("tasks/cancel"),params:ot.extend({taskId:f()})}),rm=ke.merge(yo),nm=I({uri:f(),mimeType:ge(f()),_meta:ce(f(),we()).optional()}),om=nm.extend({text:f()}),lc=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),am=nm.extend({blob:lc}),_o=nt(["user","assistant"]),gn=I({audience:C(_o).optional(),priority:ee().min(0).max(1).optional(),lastModified:jp.datetime({offset:!0}).optional()}),im=I({...mn.shape,...fo.shape,uri:f(),description:ge(f()),mimeType:ge(f()),size:ge(ee()),annotations:gn.optional(),_meta:ge(Ce({}))}),Dv=I({...mn.shape,...fo.shape,uriTemplate:f(),description:ge(f()),mimeType:ge(f()),annotations:gn.optional(),_meta:ge(Ce({}))}),pc=ho.extend({method:O("resources/list")}),mc=go.extend({resources:C(im)}),jv=ho.extend({method:O("resources/templates/list")}),fc=go.extend({resourceTemplates:C(Dv)}),hc=ot.extend({uri:f()}),Hv=hc,gc=Ae.extend({method:O("resources/read"),params:Hv}),yc=ke.extend({contents:C(me([om,am]))}),Sc=ct.extend({method:O("notifications/resources/list_changed"),params:st.optional()}),Lv=hc,Bv=Ae.extend({method:O("resources/subscribe"),params:Lv}),Gv=hc,Vv=Ae.extend({method:O("resources/unsubscribe"),params:Gv}),Fv=st.extend({uri:f()}),Zv=ct.extend({method:O("notifications/resources/updated"),params:Fv}),Kv=I({name:f(),description:ge(f()),required:ge(ae())}),Wv=I({...mn.shape,...fo.shape,description:ge(f()),arguments:ge(C(Kv)),_meta:ge(Ce({}))}),_c=ho.extend({method:O("prompts/list")}),wc=go.extend({prompts:C(Wv)}),Jv=ot.extend({name:f(),arguments:ce(f(),f()).optional()}),vc=Ae.extend({method:O("prompts/get"),params:Jv}),bc=I({type:O("text"),text:f(),annotations:gn.optional(),_meta:ce(f(),we()).optional()}),Rc=I({type:O("image"),data:lc,mimeType:f(),annotations:gn.optional(),_meta:ce(f(),we()).optional()}),Cc=I({type:O("audio"),data:lc,mimeType:f(),annotations:gn.optional(),_meta:ce(f(),we()).optional()}),Yv=I({type:O("tool_use"),name:f(),id:f(),input:ce(f(),we()),_meta:ce(f(),we()).optional()}),Qv=I({type:O("resource"),resource:me([om,am]),annotations:gn.optional(),_meta:ce(f(),we()).optional()}),Xv=im.extend({type:O("resource_link")}),Ic=me([bc,Rc,Cc,Xv,Qv]),eb=I({role:_o,content:Ic}),Pc=ke.extend({description:f().optional(),messages:C(eb)}),xc=ct.extend({method:O("notifications/prompts/list_changed"),params:st.optional()}),tb=I({title:f().optional(),readOnlyHint:ae().optional(),destructiveHint:ae().optional(),idempotentHint:ae().optional(),openWorldHint:ae().optional()}),rb=I({taskSupport:nt(["required","optional","forbidden"]).optional()}),sm=I({...mn.shape,...fo.shape,description:f().optional(),inputSchema:I({type:O("object"),properties:ce(f(),Ie).optional(),required:C(f()).optional()}).catchall(we()),outputSchema:I({type:O("object"),properties:ce(f(),Ie).optional(),required:C(f()).optional()}).catchall(we()).optional(),annotations:tb.optional(),execution:rb.optional(),_meta:ce(f(),we()).optional()}),Ac=ho.extend({method:O("tools/list")}),kc=go.extend({tools:C(sm)}),pr=ke.extend({content:C(Ic).default([]),structuredContent:ce(f(),we()).optional(),isError:ae().optional()}),Tq=pr.or(ke.extend({toolResult:we()})),nb=mo.extend({name:f(),arguments:ce(f(),we()).optional()}),wo=Ae.extend({method:O("tools/call"),params:nb}),Tc=ct.extend({method:O("notifications/tools/list_changed"),params:st.optional()}),cm=I({autoRefresh:ae().default(!0),debounceMs:ee().int().nonnegative().default(300)}),vo=nt(["debug","info","notice","warning","error","critical","alert","emergency"]),ob=ot.extend({level:vo}),Ec=Ae.extend({method:O("logging/setLevel"),params:ob}),ab=st.extend({level:vo,logger:f().optional(),data:we()}),ib=ct.extend({method:O("notifications/message"),params:ab}),sb=I({name:f().optional()}),cb=I({hints:C(sb).optional(),costPriority:ee().min(0).max(1).optional(),speedPriority:ee().min(0).max(1).optional(),intelligencePriority:ee().min(0).max(1).optional()}),ub=I({mode:nt(["auto","required","none"]).optional()}),db=I({type:O("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:C(Ic).default([]),structuredContent:I({}).loose().optional(),isError:ae().optional(),_meta:ce(f(),we()).optional()}),lb=nc("type",[bc,Rc,Cc]),Na=nc("type",[bc,Rc,Cc,Yv,db]),pb=I({role:_o,content:me([Na,C(Na)]),_meta:ce(f(),we()).optional()}),mb=mo.extend({messages:C(pb),modelPreferences:cb.optional(),systemPrompt:f().optional(),includeContext:nt(["none","thisServer","allServers"]).optional(),temperature:ee().optional(),maxTokens:ee().int(),stopSequences:C(f()).optional(),metadata:Ie.optional(),tools:C(sm).optional(),toolChoice:ub.optional()}),Uc=Ae.extend({method:O("sampling/createMessage"),params:mb}),zr=ke.extend({model:f(),stopReason:ge(nt(["endTurn","stopSequence","maxTokens"]).or(f())),role:_o,content:lb}),bo=ke.extend({model:f(),stopReason:ge(nt(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:_o,content:me([Na,C(Na)])}),fb=I({type:O("boolean"),title:f().optional(),description:f().optional(),default:ae().optional()}),hb=I({type:O("string"),title:f().optional(),description:f().optional(),minLength:ee().optional(),maxLength:ee().optional(),format:nt(["email","uri","date","date-time"]).optional(),default:f().optional()}),gb=I({type:nt(["number","integer"]),title:f().optional(),description:f().optional(),minimum:ee().optional(),maximum:ee().optional(),default:ee().optional()}),yb=I({type:O("string"),title:f().optional(),description:f().optional(),enum:C(f()),default:f().optional()}),Sb=I({type:O("string"),title:f().optional(),description:f().optional(),oneOf:C(I({const:f(),title:f()})),default:f().optional()}),_b=I({type:O("string"),title:f().optional(),description:f().optional(),enum:C(f()),enumNames:C(f()).optional(),default:f().optional()}),wb=me([yb,Sb]),vb=I({type:O("array"),title:f().optional(),description:f().optional(),minItems:ee().optional(),maxItems:ee().optional(),items:I({type:O("string"),enum:C(f())}),default:C(f()).optional()}),bb=I({type:O("array"),title:f().optional(),description:f().optional(),minItems:ee().optional(),maxItems:ee().optional(),items:I({anyOf:C(I({const:f(),title:f()}))}),default:C(f()).optional()}),Rb=me([vb,bb]),Cb=me([_b,wb,Rb]),Ib=me([Cb,fb,hb,gb]),Pb=mo.extend({mode:O("form").optional(),message:f(),requestedSchema:I({type:O("object"),properties:ce(f(),Ib),required:C(f()).optional()})}),xb=mo.extend({mode:O("url"),message:f(),elicitationId:f(),url:f().url()}),Ab=me([Pb,xb]),Oc=Ae.extend({method:O("elicitation/create"),params:Ab}),kb=st.extend({elicitationId:f()}),Tb=ct.extend({method:O("notifications/elicitation/complete"),params:kb}),mr=ke.extend({action:nt(["accept","decline","cancel"]),content:ac(e=>e===null?void 0:e,ce(f(),me([f(),ee(),ae(),C(f())])).optional())}),Eb=I({type:O("ref/resource"),uri:f()});var Ub=I({type:O("ref/prompt"),name:f()}),Ob=ot.extend({ref:me([Ub,Eb]),argument:I({name:f(),value:f()}),context:I({arguments:ce(f(),f()).optional()}).optional()}),$b=Ae.extend({method:O("completion/complete"),params:Ob});var $c=ke.extend({completion:Ce({values:C(f()).max(100),total:ge(ee().int()),hasMore:ge(ae())})}),zb=I({uri:f().startsWith("file://"),name:f().optional(),_meta:ce(f(),we()).optional()}),Mb=Ae.extend({method:O("roots/list"),params:ot.optional()}),zc=ke.extend({roots:C(zb)}),qb=ct.extend({method:O("notifications/roots/list_changed"),params:st.optional()}),Eq=me([Ga,La,$b,Ec,vc,_c,pc,jv,gc,Bv,Vv,wo,Ac,Fa,Ka,Wa,Ya]),Uq=me([Ha,Va,Ba,qb,So]),Oq=me([jt,zr,bo,mr,zc,Za,Ja,Ht]),$q=me([Ga,Uc,Oc,Mb,Fa,Ka,Wa,Ya]),zq=me([Ha,Va,ib,Zv,Sc,Tc,xc,So,Tb]),Mq=me([jt,dc,$c,Pc,wc,mc,fc,yc,pr,kc,Za,Ja,Ht]),A=class e extends Error{static{o(this,"McpError")}constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===U.UrlElicitationRequired&&n){let a=n;if(a.elicitations)return new cr(a.elicitations,r)}return new e(t,r,n)}},cr=class extends A{static{o(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(U.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function fr(e){return e==="completed"||e==="failed"||e==="cancelled"}o(fr,"isTerminal");var Nb=Symbol("Let zodToJsonSchema decide on which parser to use");var O1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Mc(e){let r=pn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(Mc,"getMethodLiteral");function qc(e,t){let r=Ge(e,t);if(!r.success)throw r.error;return r.data}o(qc,"parseWithCompat");var Gb=6e4,yn=class{static{o(this,"Protocol")}constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ha,r=>{this._oncancel(r)}),this.setNotificationHandler(Va,r=>{this._onprogress(r)}),this.setRequestHandler(Ga,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Fa,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new A(U.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(Ka,async(r,n)=>{let a=o(async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(c.type==="response"||c.type==="error"){let d=c.message,p=d.id,l=this._requestResolvers.get(p);if(l)if(this._requestResolvers.delete(p),c.type==="response")l(d);else{let m=d,h=new A(m.error.code,m.error.message,m.error.data);l(h)}else{let m=c.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${p}`))}continue}await this._transport?.send(c.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new A(U.InvalidParams,`Task not found: ${i}`);if(!fr(s.status))return await this._waitForTaskUpdate(i,n.signal),await a();if(fr(s.status)){let c=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[lr]:{taskId:i}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(Wa,async(r,n)=>{try{let{tasks:a,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:a,nextCursor:i,_meta:{}}}catch(a){throw new A(U.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(Ya,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new A(U.InvalidParams,`Task not found: ${r.params.taskId}`);if(fr(a.status))throw new A(U.InvalidParams,`Cannot cancel task in terminal status: ${a.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new A(U.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(a){throw a instanceof A?a:new A(U.InvalidRequest,`Failed to cancel task: ${a instanceof Error?a.message:String(a)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,a,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:a})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),A.fromError(U.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let a=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{a?.(i,s),St(i)||fn(i)?this._onresponse(i):It(i)?this._onrequest(i,s):em(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=A.fromError(U.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,a=this._transport,i=t.params?._meta?.[lr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:U.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},a?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):a?.send(l).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let c=Yp(t.params)?t.params.task:void 0,d=this._taskStore?this.requestTaskStore(t,a?.sessionId):void 0,p={signal:s.signal,sessionId:a?.sessionId,_meta:t.params?._meta,sendNotification:o(async l=>{if(s.signal.aborted)return;let m={relatedRequestId:t.id};i&&(m.relatedTask={taskId:i}),await this.notification(l,m)},"sendNotification"),sendRequest:o(async(l,m,h)=>{if(s.signal.aborted)throw new A(U.ConnectionClosed,"Request was cancelled");let y={...h,relatedRequestId:t.id};i&&!y.relatedTask&&(y.relatedTask={taskId:i});let _=y.relatedTask?.taskId??i;return _&&d&&await d.updateTaskStatus(_,"input_required"),await this.request(l,m,y)},"sendRequest"),authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,p)).then(async l=>{if(s.signal.aborted)return;let m={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)},async l=>{if(s.signal.aborted)return;let m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:U.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,a=Number(r),i=this._progressHandlers.get(a);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(a),c=this._timeoutInfo.get(a);if(c&&s&&c.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(d){this._responseHandlers.delete(a),this._progressHandlers.delete(a),this._cleanupTimeout(a),s(d);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),St(t))n(t);else{let s=new A(t.error.code,t.error.message,t.error.data);n(s)}return}let a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(St(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let c=s.task;typeof c.taskId=="string"&&(i=!0,this._taskProgressTokens.set(c.taskId,r))}}if(i||this._progressHandlers.delete(r),St(t))a(t);else{let s=A.fromError(t.error.code,t.error.message,t.error.data);a(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:a}=n??{};if(!a){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof A?s:new A(U.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Ht,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new A(U.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},fr(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new A(U.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new A(U.InternalError,`Task ${i} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let d=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(p=>setTimeout(p,d)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof A?s:new A(U.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s,task:c,relatedTask:d}=n??{};return new Promise((p,l)=>{let m=o(b=>{l(b)},"earlyReject");if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),c&&this.assertTaskCapability(t.method)}catch(b){m(b);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,y={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),c&&(y.params={...y.params,task:c}),d&&(y.params={...y.params,_meta:{...y.params?._meta||{},[lr]:d}});let _=o(b=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(b)}},{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(q=>this._onerror(new Error(`Failed to send cancellation: ${q}`)));let R=b instanceof A?b:new A(U.RequestTimeout,String(b));l(R)},"cancel");this._responseHandlers.set(h,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let R=Ge(r,b.result);R.success?p(R.data):l(R.error)}catch(R){l(R)}}}),n?.signal?.addEventListener("abort",()=>{_(n?.signal?.reason)});let S=n?.timeout??Gb,w=o(()=>_(A.fromError(U.RequestTimeout,"Request timed out",{timeout:S})),"timeoutHandler");this._setupTimeout(h,S,n?.maxTotalTimeout,w,n?.resetTimeoutOnProgress??!1);let v=d?.taskId;if(v){let b=o(R=>{let q=this._responseHandlers.get(h);q?q(R):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))},"responseResolver");this._requestResolvers.set(h,b),this._enqueueTaskMessage(v,{type:"request",message:y,timestamp:Date.now()}).catch(R=>{this._cleanupTimeout(h),l(R)})}else this._transport.send(y,{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(h),l(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Za,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Ja,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},rm,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let c={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[lr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:c,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let c={...t,jsonrpc:"2.0"};r?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[lr]:r.relatedTask}}}),this._transport?.send(c,r).catch(d=>this._onerror(d))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[lr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=Mc(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,i)=>{let s=qc(t,a);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=Mc(t);this._notificationHandlers.set(n,a=>{let i=qc(t,a);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let a=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,a)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let a of n)if(a.type==="request"&&It(a.message)){let i=a.message.id,s=this._requestResolvers.get(i);s?(s(new A(U.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let a=await this._taskStore?.getTask(t);a?.pollInterval&&(n=a.pollInterval)}catch{}return new Promise((a,i)=>{if(r.aborted){i(new A(U.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new A(U.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:o(async a=>{if(!t)throw new Error("No request provided");return await n.createTask(a,t.id,{method:t.method,params:t.params},r)},"createTask"),getTask:o(async a=>{let i=await n.getTask(a,r);if(!i)throw new A(U.InvalidParams,"Failed to retrieve task: Task not found");return i},"getTask"),storeTaskResult:o(async(a,i,s)=>{await n.storeTaskResult(a,i,s,r);let c=await n.getTask(a,r);if(c){let d=So.parse({method:"notifications/tasks/status",params:c});await this.notification(d),fr(c.status)&&this._cleanupTaskProgressHandler(a)}},"storeTaskResult"),getTaskResult:o(a=>n.getTaskResult(a,r),"getTaskResult"),updateTaskStatus:o(async(a,i,s)=>{let c=await n.getTask(a,r);if(!c)throw new A(U.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(fr(c.status))throw new A(U.InvalidParams,`Cannot update task "${a}" from terminal status "${c.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(a,i,s,r);let d=await n.getTask(a,r);if(d){let p=So.parse({method:"notifications/tasks/status",params:d});await this.notification(p),fr(d.status)&&this._cleanupTaskProgressHandler(a)}},"updateTaskStatus"),listTasks:o(a=>n.listTasks(a,r),"listTasks")}}};function um(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(um,"isPlainObject");function Qa(e,t){let r={...e};for(let n in t){let a=n,i=t[a];if(i===void 0)continue;let s=r[a];um(s)&&um(i)?r[a]={...s,...i}:r[a]=i}return r}o(Qa,"mergeCapabilities");var Jh=Mp(bd(),1),Yh=Mp(Wh(),1);function $A(){let e=new Jh.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Yh.default)(e),e}o($A,"createDefaultAjvInstance");var $n=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??$A()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var zi=class{static{o(this,"ExperimentalServerTasks")}constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let a=t.messages[t.messages.length-1],i=Array.isArray(a.content)?a.content:[a.content],s=i.some(l=>l.type==="tool_result"),c=t.messages.length>1?t.messages[t.messages.length-2]:void 0,d=c?Array.isArray(c.content)?c.content:[c.content]:[],p=d.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!p)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(p){let l=new Set(d.filter(h=>h.type==="tool_use").map(h=>h.id)),m=new Set(i.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(l.size!==m.size||![...l].every(h=>m.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},zr,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),a=t.mode??"form";switch(a){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=a==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},mr,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function Mi(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}o(Mi,"assertToolsCallTaskCapability");function qi(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}o(qi,"assertClientRequestTaskCapability");var Ni=class extends yn{static{o(this,"Server")}constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(vo.options.map((n,a)=>[n,a])),this.isMessageIgnored=(n,a)=>{let i=this._loggingLevels.get(a);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new $n,this.setRequestHandler(La,n=>this._oninitialize(n)),this.setNotificationHandler(Ba,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ec,async(n,a)=>{let i=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,c=vo.safeParse(s);return c.success&&this._loggingLevels.set(i,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new zi(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qa(this._capabilities,t)}setRequestHandler(t,r){let a=pn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(sr(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let c=o(async(d,p)=>{let l=Ge(wo,d);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new A(U.InvalidParams,`Invalid tools/call request: ${_}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let _=Ge(Ht,h);if(!_.success){let S=_.error instanceof Error?_.error.message:String(_.error);throw new A(U.InvalidParams,`Invalid task creation result: ${S}`)}return _.data}let y=Ge(pr,h);if(!y.success){let _=y.error instanceof Error?y.error.message:String(y.error);throw new A(U.InvalidParams,`Invalid tools/call result: ${_}`)}return y.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){qi(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Mi(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:dr.includes(r)?r:ur,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"},jt)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],a=Array.isArray(n.content)?n.content:[n.content],i=a.some(p=>p.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],d=c.some(p=>p.type==="tool_use");if(i){if(a.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(a.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(p.size!==l.size||![...p].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},bo,r):this.request({method:"sampling/createMessage",params:t},zr,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let a=t;return this.request({method:"elicitation/create",params:a},mr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let a=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:a},mr,r);if(i.action==="accept"&&i.content&&a.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!c.valid)throw new A(U.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(s){throw s instanceof A?s:new A(U.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},zc,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Di=class{static{o(this,"WebStandardStreamableHTTPServerTransport")}constructor(t={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=t.sessionIdGenerator,this._enableJsonResponse=t.enableJsonResponse??!1,this._eventStore=t.eventStore,this._onsessioninitialized=t.onsessioninitialized,this._onsessionclosed=t.onsessionclosed,this._allowedHosts=t.allowedHosts,this._allowedOrigins=t.allowedOrigins,this._enableDnsRebindingProtection=t.enableDnsRebindingProtection??!1,this._retryInterval=t.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(t,r,n,a){let i={code:r,message:n};return a?.data!==void 0&&(i.data=a.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:t,headers:{"Content-Type":"application/json",...a?.headers}})}validateRequestHeaders(t){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=t.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=t.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(t,r){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(t);if(n)return n;switch(t.method){case"POST":return this.handlePostRequest(t,r);case"GET":return this.handleGetRequest(t);case"DELETE":return this.handleDeleteRequest(t);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(t,r,n,a){if(!this._eventStore||a<"2025-11-25")return;let i=await this._eventStore.storeEvent(n,{}),s=`id: ${i}
32
+ deps: ${r}}`,"params")};var SE={keyword:"dependencies",type:"object",schemaType:"object",error:Ut.error,code(e){let[t,r]=_E(e);hS(e,t),gS(e,r)}};function _E({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let a=Array.isArray(e[n])?t:r;a[n]=e[n]}return[t,r]}o(_E,"splitDependencies");function hS(e,t=e.schema){let{gen:r,data:n,it:a}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let c=t[s];if(c.length===0)continue;let d=(0,ka.propertyInData)(r,n,s,a.opts.ownProperties);e.setParams({property:s,depsCount:c.length,deps:c.join(", ")}),a.allErrors?r.if(d,()=>{for(let p of c)(0,ka.checkReportMissingProp)(e,p)}):(r.if((0,kl._)`${d} && (${(0,ka.checkMissingProp)(e,c,i)})`),(0,ka.reportMissingProp)(e,i),r.else())}}o(hS,"validatePropertyDeps");Ut.validatePropertyDeps=hS;function gS(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,s=r.name("valid");for(let c in t)(0,yE.alwaysValidSchema)(i,t[c])||(r.if((0,ka.propertyInData)(r,n,c,i.opts.ownProperties),()=>{let d=e.subschema({keyword:a,schemaProp:c},s);e.mergeValidEvaluated(d,s)},()=>r.var(s,!0)),e.ok(s))}o(gS,"validateSchemaDeps");Ut.validateSchemaDeps=gS;Ut.default=SE});var _S=x(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var SS=V(),wE=te(),vE={message:"property name must be valid",params:o(({params:e})=>(0,SS._)`{propertyName: ${e.propertyName}}`,"params")},bE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:vE,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,wE.alwaysValidSchema)(a,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,SS.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};Tl.default=bE});var Ul=x(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});var gs=mt(),bt=V(),RE=Wt(),ys=te(),CE={message:"must NOT have additional properties",params:o(({params:e})=>(0,bt._)`{additionalProperty: ${e.additionalProperty}}`,"params")},IE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:CE,code(e){let{gen:t,schema:r,parentSchema:n,data:a,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:c,opts:d}=s;if(s.props=!0,d.removeAdditional!=="all"&&(0,ys.alwaysValidSchema)(s,r))return;let p=(0,gs.allSchemaProperties)(n.properties),l=(0,gs.allSchemaProperties)(n.patternProperties);m(),e.ok((0,bt._)`${i} === ${RE.default.errors}`);function m(){t.forIn("key",a,w=>{!p.length&&!l.length?_(w):t.if(h(w),()=>_(w))})}o(m,"checkAdditionalProperties");function h(w){let v;if(p.length>8){let b=(0,ys.schemaRefOrVal)(s,n.properties,"properties");v=(0,gs.isOwnProperty)(t,b,w)}else p.length?v=(0,bt.or)(...p.map(b=>(0,bt._)`${w} === ${b}`)):v=bt.nil;return l.length&&(v=(0,bt.or)(v,...l.map(b=>(0,bt._)`${(0,gs.usePattern)(e,b)}.test(${w})`))),(0,bt.not)(v)}o(h,"isAdditional");function y(w){t.code((0,bt._)`delete ${a}[${w}]`)}o(y,"deleteAdditional");function _(w){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){y(w);return}if(r===!1){e.setParams({additionalProperty:w}),e.error(),c||t.break();return}if(typeof r=="object"&&!(0,ys.alwaysValidSchema)(s,r)){let v=t.name("valid");d.removeAdditional==="failing"?(S(w,v,!1),t.if((0,bt.not)(v),()=>{e.reset(),y(w)})):(S(w,v),c||t.if((0,bt.not)(v),()=>t.break()))}}o(_,"additionalPropertyCode");function S(w,v,b){let R={keyword:"additionalProperties",dataProp:w,dataPropType:ys.Type.Str};b===!1&&Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(R,v)}o(S,"applyAdditionalSchema")}};El.default=IE});var bS=x($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var PE=ha(),wS=mt(),Ol=te(),vS=Ul(),xE={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&vS.default.code(new PE.KeywordCxt(i,vS.default,"additionalProperties"));let s=(0,wS.allSchemaProperties)(r);for(let m of s)i.definedProperties.add(m);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Ol.mergeEvaluated.props(t,(0,Ol.toHash)(s),i.props));let c=s.filter(m=>!(0,Ol.alwaysValidSchema)(i,r[m]));if(c.length===0)return;let d=t.name("valid");for(let m of c)p(m)?l(m):(t.if((0,wS.propertyInData)(t,a,m,i.opts.ownProperties)),l(m),i.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(m),e.ok(d);function p(m){return i.opts.useDefaults&&!i.compositeRule&&r[m].default!==void 0}o(p,"hasDefault");function l(m){e.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}o(l,"applyPropertySchema")}};$l.default=xE});var PS=x(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});var RS=mt(),Ss=V(),CS=te(),IS=te(),AE={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:a,it:i}=e,{opts:s}=i,c=(0,RS.allSchemaProperties)(r),d=c.filter(S=>(0,CS.alwaysValidSchema)(i,r[S]));if(c.length===0||d.length===c.length&&(!i.opts.unevaluated||i.props===!0))return;let p=s.strictSchema&&!s.allowMatchingProperties&&a.properties,l=t.name("valid");i.props!==!0&&!(i.props instanceof Ss.Name)&&(i.props=(0,IS.evaluatedPropsToName)(t,i.props));let{props:m}=i;h();function h(){for(let S of c)p&&y(S),i.allErrors?_(S):(t.var(l,!0),_(S),t.if(l))}o(h,"validatePatternProperties");function y(S){for(let w in p)new RegExp(S).test(w)&&(0,CS.checkStrictMode)(i,`property ${w} matches pattern ${S} (use allowMatchingProperties)`)}o(y,"checkMatchingProperties");function _(S){t.forIn("key",n,w=>{t.if((0,Ss._)`${(0,RS.usePattern)(e,S)}.test(${w})`,()=>{let v=d.includes(S);v||e.subschema({keyword:"patternProperties",schemaProp:S,dataProp:w,dataPropType:IS.Type.Str},l),i.opts.unevaluated&&m!==!0?t.assign((0,Ss._)`${m}[${w}]`,!0):!v&&!i.allErrors&&t.if((0,Ss.not)(l),()=>t.break())})})}o(_,"validateProperties")}};zl.default=AE});var xS=x(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var kE=te(),TE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,kE.alwaysValidSchema)(n,r)){e.fail();return}let a=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ml.default=TE});var AS=x(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var EE=mt(),UE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:EE.validateUnion,error:{message:"must match a schema in anyOf"}};ql.default=UE});var kS=x(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var _s=V(),OE=te(),$E={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,_s._)`{passingSchemas: ${e.passing}}`,"params")},zE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:$E,code(e){let{gen:t,schema:r,parentSchema:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&n.discriminator)return;let i=r,s=t.let("valid",!1),c=t.let("passing",null),d=t.name("_valid");e.setParams({passing:c}),t.block(p),e.result(s,()=>e.reset(),()=>e.error(!0));function p(){i.forEach((l,m)=>{let h;(0,OE.alwaysValidSchema)(a,l)?t.var(d,!0):h=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,_s._)`${d} && ${s}`).assign(s,!1).assign(c,(0,_s._)`[${c}, ${m}]`).else(),t.if(d,()=>{t.assign(s,!0),t.assign(c,m),h&&e.mergeEvaluated(h,_s.Name)})})}o(p,"validateOneOf")}};Nl.default=zE});var TS=x(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var ME=te(),qE={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let a=t.name("valid");r.forEach((i,s)=>{if((0,ME.alwaysValidSchema)(n,i))return;let c=e.subschema({keyword:"allOf",schemaProp:s},a);e.ok(a),e.mergeEvaluated(c)})}};jl.default=qE});var OS=x(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var ws=V(),US=te(),NE={message:o(({params:e})=>(0,ws.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,ws._)`{failingKeyword: ${e.ifClause}}`,"params")},jE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:NE,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,US.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=ES(n,"then"),i=ES(n,"else");if(!a&&!i)return;let s=t.let("valid",!0),c=t.name("_valid");if(d(),e.reset(),a&&i){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(c,p("then",l),p("else",l))}else a?t.if(c,p("then")):t.if((0,ws.not)(c),p("else"));e.pass(s,()=>e.error(!0));function d(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},c);e.mergeEvaluated(l)}o(d,"validateIf");function p(l,m){return()=>{let h=e.subschema({keyword:l},c);t.assign(s,c),e.mergeValidEvaluated(h,s),m?t.assign(m,(0,ws._)`${l}`):e.setParams({ifClause:l})}}o(p,"validateClause")}};function ES(e,t){let r=e.schema[t];return r!==void 0&&!(0,US.alwaysValidSchema)(e,r)}o(ES,"hasSchema");Dl.default=jE});var $S=x(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var DE=te(),HE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,DE.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Hl.default=HE});var zS=x(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var LE=Cl(),BE=lS(),GE=Il(),VE=mS(),FE=fS(),ZE=yS(),KE=_S(),JE=Ul(),WE=bS(),YE=PS(),QE=xS(),XE=AS(),eU=kS(),tU=TS(),rU=OS(),nU=$S();function oU(e=!1){let t=[QE.default,XE.default,eU.default,tU.default,rU.default,nU.default,KE.default,JE.default,ZE.default,WE.default,YE.default];return e?t.push(BE.default,VE.default):t.push(LE.default,GE.default),t.push(FE.default),t}o(oU,"getApplicator");Ll.default=oU});var MS=x(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var Re=V(),aU={message:o(({schemaCode:e})=>(0,Re.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Re._)`{format: ${e}}`,"params")},iU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:aU,code(e,t){let{gen:r,data:n,$data:a,schema:i,schemaCode:s,it:c}=e,{opts:d,errSchemaPath:p,schemaEnv:l,self:m}=c;if(!d.validateFormats)return;a?h():y();function h(){let _=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),S=r.const("fDef",(0,Re._)`${_}[${s}]`),w=r.let("fType"),v=r.let("format");r.if((0,Re._)`typeof ${S} == "object" && !(${S} instanceof RegExp)`,()=>r.assign(w,(0,Re._)`${S}.type || "string"`).assign(v,(0,Re._)`${S}.validate`),()=>r.assign(w,(0,Re._)`"string"`).assign(v,S)),e.fail$data((0,Re.or)(b(),R()));function b(){return d.strictSchema===!1?Re.nil:(0,Re._)`${s} && !${v}`}o(b,"unknownFmt");function R(){let M=l.$async?(0,Re._)`(${S}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Re._)`${v}(${n})`,q=(0,Re._)`(typeof ${v} == "function" ? ${M} : ${v}.test(${n}))`;return(0,Re._)`${v} && ${v} !== true && ${w} === ${t} && !${q}`}o(R,"invalidFmt")}o(h,"validate$DataFormat");function y(){let _=m.formats[i];if(!_){b();return}if(_===!0)return;let[S,w,v]=R(_);S===t&&e.pass(M());function b(){if(d.strictSchema===!1){m.logger.warn(q());return}throw new Error(q());function q(){return`unknown format "${i}" ignored in schema at path "${p}"`}}o(b,"unknownFormat");function R(q){let Me=q instanceof RegExp?(0,Re.regexpCode)(q):d.code.formats?(0,Re._)`${d.code.formats}${(0,Re.getProperty)(i)}`:void 0,it=r.scopeValue("formats",{key:i,ref:q,code:Me});return typeof q=="object"&&!(q instanceof RegExp)?[q.type||"string",q.validate,(0,Re._)`${it}.validate`]:["string",q,it]}o(R,"getFormat");function M(){if(typeof _=="object"&&!(_ instanceof RegExp)&&_.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Re._)`await ${v}(${n})`}return typeof w=="function"?(0,Re._)`${v}(${n})`:(0,Re._)`${v}.test(${n})`}o(M,"validCondition")}o(y,"validateFormat")}};Bl.default=iU});var qS=x(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var sU=MS(),cU=[sU.default];Gl.default=cU});var NS=x(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.contentVocabulary=Xn.metadataVocabulary=void 0;Xn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Xn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var DS=x(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var uU=Zy(),dU=sS(),lU=zS(),pU=qS(),jS=NS(),mU=[uU.default,dU.default,(0,lU.default)(),pU.default,jS.metadataVocabulary,jS.contentVocabulary];Vl.default=mU});var LS=x(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.DiscrError=void 0;var HS;(function(e){e.Tag="tag",e.Mapping="mapping"})(HS||(vs.DiscrError=HS={}))});var GS=x(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var eo=V(),Fl=LS(),BS=rs(),fU=ga(),hU=te(),gU={message:o(({params:{discrError:e,tagName:t}})=>e===Fl.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,"message"),params:o(({params:{discrError:e,tag:t,tagName:r}})=>(0,eo._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},yU={keyword:"discriminator",type:"object",schemaType:"object",error:gU,code(e){let{gen:t,data:r,schema:n,parentSchema:a,it:i}=e,{oneOf:s}=a;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let c=n.propertyName;if(typeof c!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let d=t.let("valid",!1),p=t.const("tag",(0,eo._)`${r}${(0,eo.getProperty)(c)}`);t.if((0,eo._)`typeof ${p} == "string"`,()=>l(),()=>e.error(!1,{discrError:Fl.DiscrError.Tag,tag:p,tagName:c})),e.ok(d);function l(){let y=h();t.if(!1);for(let _ in y)t.elseIf((0,eo._)`${p} === ${_}`),t.assign(d,m(y[_]));t.else(),e.error(!1,{discrError:Fl.DiscrError.Mapping,tag:p,tagName:c}),t.endIf()}o(l,"validateMapping");function m(y){let _=t.name("valid"),S=e.subschema({keyword:"oneOf",schemaProp:y},_);return e.mergeEvaluated(S,eo.Name),_}o(m,"applyTagSchema");function h(){var y;let _={},S=v(a),w=!0;for(let M=0;M<s.length;M++){let q=s[M];if(q?.$ref&&!(0,hU.schemaHasRulesButRef)(q,i.self.RULES)){let it=q.$ref;if(q=BS.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,it),q instanceof BS.SchemaEnv&&(q=q.schema),q===void 0)throw new fU.default(i.opts.uriResolver,i.baseId,it)}let Me=(y=q?.properties)===null||y===void 0?void 0:y[c];if(typeof Me!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);w=w&&(S||v(q)),b(Me,M)}if(!w)throw new Error(`discriminator: "${c}" must be required`);return _;function v({required:M}){return Array.isArray(M)&&M.includes(c)}function b(M,q){if(M.const)R(M.const,q);else if(M.enum)for(let Me of M.enum)R(Me,q);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function R(M,q){if(typeof M!="string"||M in _)throw new Error(`discriminator: "${c}" values must be unique strings`);_[M]=q}}o(h,"getMapping")}};Zl.default=yU});var VS=x((zF,SU)=>{SU.exports={$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 Jl=x((me,Kl)=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.MissingRefError=me.ValidationError=me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=me.Ajv=void 0;var _U=Hy(),wU=DS(),vU=GS(),FS=VS(),bU=["/properties"],bs="http://json-schema.org/draft-07/schema",to=class extends _U.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),wU.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(vU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(FS,bU):FS;this.addMetaSchema(t,bs,!1),this.refs["http://json-schema.org/schema"]=bs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(bs)?bs:void 0)}};me.Ajv=to;Kl.exports=me=to;Kl.exports.Ajv=to;Object.defineProperty(me,"__esModule",{value:!0});me.default=to;var RU=ha();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:o(function(){return RU.KeywordCxt},"get")});var ro=V();Object.defineProperty(me,"_",{enumerable:!0,get:o(function(){return ro._},"get")});Object.defineProperty(me,"str",{enumerable:!0,get:o(function(){return ro.str},"get")});Object.defineProperty(me,"stringify",{enumerable:!0,get:o(function(){return ro.stringify},"get")});Object.defineProperty(me,"nil",{enumerable:!0,get:o(function(){return ro.nil},"get")});Object.defineProperty(me,"Name",{enumerable:!0,get:o(function(){return ro.Name},"get")});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:o(function(){return ro.CodeGen},"get")});var CU=es();Object.defineProperty(me,"ValidationError",{enumerable:!0,get:o(function(){return CU.default},"get")});var IU=ga();Object.defineProperty(me,"MissingRefError",{enumerable:!0,get:o(function(){return IU.default},"get")})});var e_=x($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.formatNames=$t.fastFormats=$t.fullFormats=void 0;function Ot(e,t){return{validate:e,compare:t}}o(Ot,"fmtDef");$t.fullFormats={date:Ot(WS,Xl),time:Ot(Yl(!0),ep),"date-time":Ot(ZS(!0),QS),"iso-time":Ot(Yl(),YS),"iso-date-time":Ot(ZS(),XS),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:EU,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:NU,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:UU,int32:{type:"number",validate:zU},int64:{type:"number",validate:MU},float:{type:"number",validate:JS},double:{type:"number",validate:JS},password:!0,binary:!0};$t.fastFormats={...$t.fullFormats,date:Ot(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Xl),time:Ot(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ep),"date-time":Ot(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,QS),"iso-time":Ot(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,YS),"iso-date-time":Ot(/^\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,XS),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};$t.formatNames=Object.keys($t.fullFormats);function PU(e){return e%4===0&&(e%100!==0||e%400===0)}o(PU,"isLeapYear");var xU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,AU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function WS(e){let t=xU.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n===2&&PU(r)?29:AU[n])}o(WS,"date");function Xl(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(Xl,"compareDate");var Wl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Yl(e){return o(function(r){let n=Wl.exec(r);if(!n)return!1;let a=+n[1],i=+n[2],s=+n[3],c=n[4],d=n[5]==="-"?-1:1,p=+(n[6]||0),l=+(n[7]||0);if(p>23||l>59||e&&!c)return!1;if(a<=23&&i<=59&&s<60)return!0;let m=i-l*d,h=a-p*d-(m<0?1:0);return(h===23||h===-1)&&(m===59||m===-1)&&s<61},"time")}o(Yl,"getTime");function ep(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}o(ep,"compareTime");function YS(e,t){if(!(e&&t))return;let r=Wl.exec(e),n=Wl.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}o(YS,"compareIsoTime");var Ql=/t|\s/i;function ZS(e){let t=Yl(e);return o(function(n){let a=n.split(Ql);return a.length===2&&WS(a[0])&&t(a[1])},"date_time")}o(ZS,"getDateTime");function QS(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(QS,"compareDateTime");function XS(e,t){if(!(e&&t))return;let[r,n]=e.split(Ql),[a,i]=t.split(Ql),s=Xl(r,a);if(s!==void 0)return s||ep(n,i)}o(XS,"compareIsoDateTime");var kU=/\/|:/,TU=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function EU(e){return kU.test(e)&&TU.test(e)}o(EU,"uri");var KS=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function UU(e){return KS.lastIndex=0,KS.test(e)}o(UU,"byte");var OU=-(2**31),$U=2**31-1;function zU(e){return Number.isInteger(e)&&e<=$U&&e>=OU}o(zU,"validateInt32");function MU(e){return Number.isInteger(e)}o(MU,"validateInt64");function JS(){return!0}o(JS,"validateNumber");var qU=/[^\\]\\Z/;function NU(e){if(qU.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(NU,"regex")});var t_=x(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.formatLimitDefinition=void 0;var jU=Jl(),Rt=V(),Pr=Rt.operators,Rs={formatMaximum:{okStr:"<=",ok:Pr.LTE,fail:Pr.GT},formatMinimum:{okStr:">=",ok:Pr.GTE,fail:Pr.LT},formatExclusiveMaximum:{okStr:"<",ok:Pr.LT,fail:Pr.GTE},formatExclusiveMinimum:{okStr:">",ok:Pr.GT,fail:Pr.LTE}},DU={message:o(({keyword:e,schemaCode:t})=>(0,Rt.str)`should be ${Rs[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,Rt._)`{comparison: ${Rs[e].okStr}, limit: ${t}}`,"params")};no.formatLimitDefinition={keyword:Object.keys(Rs),type:"string",schemaType:"string",$data:!0,error:DU,code(e){let{gen:t,data:r,schemaCode:n,keyword:a,it:i}=e,{opts:s,self:c}=i;if(!s.validateFormats)return;let d=new jU.KeywordCxt(i,c.RULES.all.format.definition,"format");d.$data?p():l();function p(){let h=t.scopeValue("formats",{ref:c.formats,code:s.code.formats}),y=t.const("fmt",(0,Rt._)`${h}[${d.schemaCode}]`);e.fail$data((0,Rt.or)((0,Rt._)`typeof ${y} != "object"`,(0,Rt._)`${y} instanceof RegExp`,(0,Rt._)`typeof ${y}.compare != "function"`,m(y)))}o(p,"validate$DataFormat");function l(){let h=d.schema,y=c.formats[h];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${a}": format "${h}" does not define "compare" function`);let _=t.scopeValue("formats",{key:h,ref:y,code:s.code.formats?(0,Rt._)`${s.code.formats}${(0,Rt.getProperty)(h)}`:void 0});e.fail$data(m(_))}o(l,"validateFormat");function m(h){return(0,Rt._)`${h}.compare(${r}, ${n}) ${Rs[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var HU=o(e=>(e.addKeyword(no.formatLimitDefinition),e),"formatLimitPlugin");no.default=HU});var a_=x((Ta,o_)=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});var oo=e_(),LU=t_(),tp=V(),r_=new tp.Name("fullFormats"),BU=new tp.Name("fastFormats"),rp=o((e,t={keywords:!0})=>{if(Array.isArray(t))return n_(e,t,oo.fullFormats,r_),e;let[r,n]=t.mode==="fast"?[oo.fastFormats,BU]:[oo.fullFormats,r_],a=t.formats||oo.formatNames;return n_(e,a,r,n),t.keywords&&(0,LU.default)(e),e},"formatsPlugin");rp.get=(e,t="full")=>{let n=(t==="fast"?oo.fastFormats:oo.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function n_(e,t,r,n){var a,i;(a=(i=e.opts.code).formats)!==null&&a!==void 0||(i.formats=(0,tp._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}o(n_,"addFormats");o_.exports=Ta=rp;Object.defineProperty(Ta,"__esModule",{value:!0});Ta.default=rp});var vn={runtime:{invalid_request:{code:"invalid_request",seam:"runtime",status:400,title:"Bad Request",publicDetail:"The request did not match the route contract.",oauthError:"invalid_request"},forbidden:{code:"forbidden",seam:"runtime",status:403,title:"Forbidden",publicDetail:"The request is not allowed.",oauthError:"invalid_request"},not_found:{code:"not_found",seam:"runtime",status:404,title:"Not Found",publicDetail:"The requested resource was not found.",oauthError:"invalid_request"},internal_server_error:{code:"internal_server_error",seam:"runtime",status:500,title:"Internal Server Error",publicDetail:"The gateway failed to process the request.",oauthError:"server_error"}},config:{virtual_server_not_enabled:{code:"virtual_server_not_enabled",seam:"config",status:404,title:"Not Found",publicDetail:"The requested virtual server is not enabled."},unknown_upstream_server:{code:"unknown_upstream_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream server is not configured.",oauthError:"invalid_request"},unknown_virtual_server:{code:"unknown_virtual_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server is not configured.",oauthError:"invalid_target"},unknown_auth_profile:{code:"unknown_auth_profile",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream auth profile is not configured.",oauthError:"invalid_request"},virtual_server_upstream_mismatch:{code:"virtual_server_upstream_mismatch",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server does not belong to the selected upstream server.",oauthError:"invalid_request"}},downstream_auth:{authentication_required:{code:"authentication_required",seam:"downstream_auth",status:401,title:"Unauthorized",publicDetail:"Authentication is required to access this route.",oauthError:"invalid_client"},identity_context_missing:{code:"identity_context_missing",seam:"downstream_auth",status:403,title:"Forbidden",publicDetail:"Authenticated requests must include a gateway principal subject.",oauthError:"invalid_request"}},downstream_oauth:{browser_login_verification_failed:{code:"browser_login_verification_failed",seam:"downstream_oauth",status:400,title:"Connection failed",publicDetail:"The gateway could not verify the browser login response. Retry the login flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_auth:{provider_access_denied:{code:"provider_access_denied",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream authorization request was denied. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_invalid:{code:"oauth_state_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request could not be verified. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_expired:{code:"oauth_state_expired",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request expired. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_reused:{code:"oauth_state_reused",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"This upstream connection request was already used. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_callback_mismatch:{code:"oauth_callback_mismatch",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream callback did not match the initiating connection request.",callbackFailure:!0,oauthError:"invalid_request"},upstream_token_exchange_failed:{code:"upstream_token_exchange_failed",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The gateway could not complete the upstream token exchange. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"},upstream_client_registration_required:{code:"upstream_client_registration_required",seam:"upstream_auth",status:400,title:"Upstream OAuth client registration required",publicDetail:"The upstream authorization server supports neither gateway-hosted Client ID Metadata Documents nor Dynamic Client Registration. Register an upstream OAuth client manually before retrying.",oauthError:"invalid_request"},upstream_token_response_invalid:{code:"upstream_token_response_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream token response was invalid. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_mcp:{upstream_capability_invocation_failed:{code:"upstream_capability_invocation_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability invocation failed. Retry later or reconnect the upstream if the issue persists."},upstream_import_failed:{code:"upstream_import_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability import failed. Retry later or reconnect the upstream if the issue persists."}}},tm={...vn.runtime,...vn.config,...vn.downstream_auth,...vn.downstream_oauth,...vn.upstream_auth,...vn.upstream_mcp};function wo(e){return typeof e=="string"&&Object.hasOwn(tm,e)}o(wo,"isGatewayProblemCode");function Fa(e){return wo(e)&&Ke(e).callbackFailure===!0}o(Fa,"isGatewayCallbackFailureCode");function Ke(e){return tm[e]}o(Ke,"readGatewayProblemDefinition");function rm(e){switch(e){case 400:return"invalid_request";case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";default:return"internal_server_error"}}o(rm,"readDefaultGatewayProblemCodeForStatus");var nm="gatewayCode";function om(e){let t=Ke(e);return{title:t.title,body:t.publicDetail}}o(om,"readGatewayCallbackFailureContent");function ge(e){if(!(e instanceof _n))return;let t=e.extensionMembers?.[nm];return wo(t)?t:void 0}o(ge,"readGatewayProblemCode");function g(e,t,r){let n=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...r===void 0?{}:{cause:r}}:e,a=Ke(n.code),i=n.privateDetail??(Za(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),s=Pv(n);return new _n({message:i,extensionMembers:{[nm]:n.code}},s===void 0?void 0:{cause:s})}o(g,"createGatewayRuntimeError");async function st(e,t,r){let n=Ke(r.code),a=xv(r.code,r.detail),i=Za(r.code)?r.title??n.title:n.title,c={problem:{..._o.getProblemFromStatus(n.status,{detail:a,instance:r.instance,type:r.type}),...r.extensions??{},status:n.status,title:i,detail:a,code:r.code}};return r.headers!==void 0&&(c.additionalHeaders=r.headers),_o.format(c,e,t)}o(st,"gatewayProblemResponse");function Za(e){return Ke(e).status<500}o(Za,"canExposeGatewayProblemDetail");function Pv(e){return!e.privateDetail||Za(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o(Pv,"readRuntimeErrorCause");function xv(e,t){let r=Ke(e);return Za(e)&&t||r.publicDetail}o(xv,"readSafeGatewayProblemDetail");ae();ae();ae();var Av=new Set(["localhost","::1"]);function jt(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(jt,"normalizeHostname");function qe(e){let t=jt(e.hostname);return e.protocol==="http:"&&(Av.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(qe,"isLoopbackHttpUrl");var am=new It("gateway-route");function im(e,t){am.set(e,t)}o(im,"setGatewayRouteContext");function vo(e){return am.get(e)}o(vo,"readGatewayRouteContext");function bn(e){let t=vo(e);if(!t)throw g("internal_server_error","Gateway route context has not been set");return t}o(bn,"requireGatewayRouteContext");var sm=new It("mcp-oauth-runtime-config");function Rn(e,t){sm.set(e,t)}o(Rn,"setMcpOAuthRuntimeConfig");function cm(e){let t=sm.get(e);if(!t)throw g("internal_server_error","MCP gateway OAuth config has not been set on the request context. An `mcp-oauth-inbound` policy (or `mcp-auth0-oauth-inbound`) must run before this handler, or the internal OAuth route wrapper must have populated the context.");return t}o(cm,"requireMcpOAuthRuntimeConfig");var bo=u.string().trim().min(1),Ro={accessTokenTtlSeconds:900,refreshTokenTtlSeconds:2592e3,cimdEnabled:!0},kv=u.object({issuer:u.url(),jwksUrl:u.url(),audience:bo.optional()}),Tv=u.object({url:u.url(),tokenUrl:u.url().optional(),clientId:bo.optional(),clientSecret:bo.optional(),scope:bo.default("openid profile email"),audience:bo.optional(),remoteTimeoutMs:u.coerce.number().int().positive().default(1e4),stateTtlSeconds:u.coerce.number().int().positive().default(900),sessionTtlSeconds:u.coerce.number().int().positive().default(28800)}).strict(),Ev=u.object({accessTokenTtlSeconds:u.coerce.number().int().positive().default(Ro.accessTokenTtlSeconds),refreshTokenTtlSeconds:u.coerce.number().int().positive().default(Ro.refreshTokenTtlSeconds),cimdEnabled:u.boolean().default(Ro.cimdEnabled)}).strict().default(Ro),fc=u.object({oidc:kv,browserLogin:Tv,gateway:Ev.optional().default(Ro)}).strict();function um(e){return Uv(e.browserLogin.url)?"local_dev":"federated_oidc"}o(um,"readBrowserLoginKind");function Uv(e){let t;try{t=new URL(e)}catch{return!1}return qe(t)&&t.pathname==="/oauth/dev-login"}o(Uv,"isLoopbackDevLoginUrl");function dm(e){return fc.parse(e)}o(dm,"parseMcpOAuthRuntimeConfig");function Pe(){let e;try{e=cc()}catch(t){throw g("internal_server_error","MCP gateway OAuth config can only be read during a request. Wrap tests in `runWithRequestContext` and ensure MCP OAuth routes are registered through `McpGatewayPlugin`.",t)}return cm(e)}o(Pe,"getGatewayOAuthConfig");ae();var Ov=["shared-oauth","user_oauth","static_secret","user-secret","shared-secret"],$v=["none","client_secret_basic","client_secret_post"],Je=u.string().min(1).brand(),xe=u.string().min(1).brand(),We=u.string().min(1).brand(),ar=u.string().min(1).brand(),Ka=u.enum(Ov),hc=u.enum($v),Ja=u.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),gc=u.object({name:Ja,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict();ae();var W=u.string().datetime({offset:!0}).brand();function re(e){return W.parse(e.toISOString())}o(re,"toIsoTimestamp");function Dt(e,t){return new Date(e.getTime()+t*1e3)}o(Dt,"addSeconds");ae();function ie(e){return new URL(e).origin}o(ie,"readGatewayRequestOrigin");function gt(e){return ie(e)}o(gt,"readGatewayOAuthIssuer");function yc(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(yc,"truncate");function lm(e){return"cause"in e?e.cause:void 0}o(lm,"readCause");function Ye(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=yc(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=yc(r.message);let n=lm(r);for(let a=1;a<=4&&n instanceof Error;a+=1){let i=a===1?"cause":`cause${a}`;e[`${i}Name`]=n.name,e[`${i}Message`]=yc(n.message),n=lm(n)}}o(Ye,"addErrorLogFields");function ct(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}o(ct,"safeHost");function pm(e,t){let r=Object.entries(t).filter(n=>n[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}o(pm,"setLogProperties");function Sc(e,t){pm(e,{subjectId:t.subjectId})}o(Sc,"applyGatewayPrincipalLogProperties");function mm(e,t){pm(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(mm,"applyGatewayRouteLogProperties");ae();var zv=43,Mv=128,qv=/^[A-Za-z0-9._~-]+$/,_c="S256",Wa=u.literal(_c),Ya=u.string().min(zv).max(Mv).regex(qv);ae();var Qa=["none","client_secret_post","client_secret_basic"],Nv=[...Qa,"private_key_jwt"],jv=["awaiting_login","awaiting_setup"],Dv=u.string().min(1).brand(),Ne=u.string().min(1).brand(),Co=u.uuid().brand(),ut=u.uuid().brand(),Xa=u.uuid().brand(),wc=u.enum(Qa),Hv=u.enum(Nv),p1=u.enum(jv),fm=u.object({client_id:Ne,client_name:u.string().min(1),redirect_uris:u.array(u.string().min(1)).min(1),token_endpoint_auth_method:Hv.default("none")}),vc=u.object({clientId:Ne,clientName:u.string().min(1),redirectUris:u.array(u.string().min(1)),tokenEndpointAuthMethod:wc,hashedClientSecret:u.string().optional(),clientSecretExpiresAt:W.optional(),clientExpiresAt:W,revokedAt:W.optional(),createdAt:W}),bc=u.object({clientId:Ne,resource:u.string(),virtualServerId:xe,subjectId:Dv,scope:u.string(),roles:u.array(u.string()),createdAt:W,expiresAt:W}),m1=bc.extend({id:ut,redirectUri:u.string(),clientState:u.string().optional(),codeChallenge:u.string(),codeChallengeMethod:Wa}),Rc=bc.extend({id:Co,currentRefreshTokenHash:u.string().optional(),previousRefreshTokenHash:u.string().optional(),revokedAt:W.optional(),revokedReason:u.string().optional()}),ei=bc.extend({tokenHash:u.string(),grantId:Co,revokedAt:W.optional()});function Cc(){return ut.parse(crypto.randomUUID())}o(Cc,"createDownstreamAuthorizationTransactionId");function Ic(){return Xa.parse(crypto.randomUUID())}o(Ic,"createDownstreamBrowserLoginStateId");function hm(){return Co.parse(crypto.randomUUID())}o(hm,"createDownstreamGrantId");var Se="mcp:tools";function gm(e,t){if(e===t)return!0;let r=new URL(e),n=new URL(t);return qe(r)&&qe(n)&&r.pathname===n.pathname&&r.search===n.search}o(gm,"redirectUriMatchesRegistration");function ym(e){return qe(e)&&e.pathname==="/oauth/dev-login"}o(ym,"isLoopbackDevLoginUrl");function ti(e,t){return new URL(e,gt(t)).toString()}o(ti,"buildGatewayOAuthUrl");function Pc(e){return new URL(`/mcp/${encodeURIComponent(e.virtualServerId)}`,ie(e.requestUrl)).toString()}o(Pc,"buildScopedAuthorizationServerIssuer");function Lv(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,ie(e.requestUrl)).toString()}o(Lv,"buildScopedAuthorizationEndpoint");function xc(e){let t=Pe();return{issuer:gt(e),authorization_endpoint:ti("/oauth/authorize",e),token_endpoint:ti("/oauth/token",e),registration_endpoint:ti("/oauth/register",e),revocation_endpoint:ti("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[Se],code_challenge_methods_supported:[_c],token_endpoint_auth_methods_supported:Qa,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","none"],client_id_metadata_document_supported:t.gateway.cimdEnabled,"x-zuplo-browser-login-kind":um(t)}}o(xc,"buildAuthorizationServerMetadata");function Sm(e){let t=Pc(e);return{...xc(e.requestUrl),issuer:t,authorization_endpoint:Lv(e)}}o(Sm,"buildScopedAuthorizationServerMetadata");var zr="2025-06-18";async function _m(e,t){try{let r=xe.parse(e.params.virtualServerId),n=qr(r);return Response.json(Bv(n.virtualServerId,e.url))}catch(r){let n=ge(r);return st(e,t,{code:n==="unknown_virtual_server"?n:"not_found",detail:(r instanceof Error?r.message:void 0)??"The requested protected resource metadata document was not found."})}}o(_m,"protectedResourceMetadataHandler");function Bv(e,t){return{resource:Mr(e,t),resource_name:e,authorization_servers:[Pc({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[Se],mcp_protocol_version:zr}}o(Bv,"buildProtectedResourceMetadataResponseBody");function Mr(e,t){return new URL(`/mcp/${encodeURIComponent(e)}`,ie(t)).toString()}o(Mr,"buildCanonicalMcpResourceForVirtualServer");function wm(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,ie(t)).toString()}o(wm,"buildProtectedResourceMetadataUrlForVirtualServer");var Gv=u.record(u.string(),u.unknown()),vm=u.string().min(1),Vv=u.union([vm.transform(e=>[e]),u.array(vm)]),_e=u.string().min(1).brand(),Fv=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],Zv=["https://zuplo.com/roles","roles","role","permissions","groups"],bm=new It("gateway-principal");function Kv(e){let t=Gv.safeParse(e);return t.success?t.data:{}}o(Kv,"toClaimRecord");function Jv(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(Jv,"readValidationFailureDetail");function Wv(e,t,r){for(let i of Fv){let s=_e.safeParse(t[i]);if(s.success)return s.data}let n=_e.safeParse(e?.sub);if(!n.success)throw g("identity_context_missing",Jv(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===gt(r)?n.data:_e.parse(`${a}|${n.data}`)}o(Wv,"readNormalizedSubjectId");function Yv(e){let t=new Set;for(let r of Zv){let n=Vv.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o(Yv,"readRoles");function Cn(e,t){let r=Kv(e?.data),n={subjectId:Wv(e,r,t)},a=Yv(r);return a&&(n.roles=a),n}o(Cn,"parseGatewayPrincipal");function Rm(e){let t=kc(e);if(!t)throw g("identity_context_missing","Gateway principal has not been hydrated");return t}o(Rm,"requireGatewayPrincipal");function Cm(e,t){bm.set(e,t)}o(Cm,"setGatewayPrincipal");function kc(e){return bm.get(e)}o(kc,"readGatewayPrincipal");function ri(e){let r=['realm="OAuth"',`resource_metadata="${Ac(wm(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${Ac(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${Ac(e.scope)}"`),`Bearer ${r.join(", ")}`}o(ri,"buildGatewayBearerChallenge");function Ac(e){let t="";for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);n<=31||n===127||(t+=e[r])}return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}o(Ac,"sanitizeQuotedHeaderParameter");ae();ae();function ni(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path.");let t=new URL(e,"https://gateway.local");if(t.origin!=="https://gateway.local"||t.username||t.password||t.hash||t.pathname.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}o(ni,"parseSafeRelativeReturnTo");ae();var Qv=["user","shared"],In=u.enum(Qv);function ir(e){return{mode:"user",subjectId:e}}o(ir,"buildUserUpstreamConnectionOwner");function oi(){return{mode:"shared"}}o(oi,"buildSharedUpstreamConnectionOwner");var Im=u.object({ownerMode:In,initiatedBySubjectId:_e,ownerSubjectId:_e.optional(),upstreamServerId:Je,authProfileId:We,virtualServerId:xe,returnTo:u.string().min(1).transform(e=>ni(e)).optional()});function Pm(e,t){e.ownerMode==="user"&&!e.ownerSubjectId&&t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned state requires ownerSubjectId",path:["ownerSubjectId"]}),e.ownerMode==="shared"&&e.ownerSubjectId&&t.addIssue({code:u.ZodIssueCode.custom,message:"Shared state must not include ownerSubjectId",path:["ownerSubjectId"]})}o(Pm,"validateUpstreamOwnerState");var Pn=Im.superRefine(Pm),xm=Im.omit({returnTo:!0}).superRefine(Pm);function Io(e){return Pn.parse({ownerMode:e.owner.mode,initiatedBySubjectId:e.initiatedBySubjectId,ownerSubjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,returnTo:e.returnTo})}o(Io,"buildUpstreamOwnerState");function xn(e){if(e.ownerMode==="shared")return oi();if(!e.ownerSubjectId)throw g("oauth_state_invalid","User-owned upstream state is missing the owner subject.");return ir(e.ownerSubjectId)}o(xn,"resolveUpstreamConnectionOwnerFromState");var Xv=["active","not_connected","reconsent_required"],eb=["basic_auth_app_password","bearer_token"],Am=u.string().trim().min(1).brand(),An=u.uuid().brand(),Po=u.uuid().brand(),Tc=u.enum(Xv),tb=u.enum(eb),km=u.object({encryptedClientInformation:u.string().optional(),encryptedDiscoveryState:u.string().optional(),connectedBySubjectId:_e.optional()}),rb=km.extend({encryptedStaticSecret:u.string().optional(),staticSecretKind:tb.optional(),staticSecretLabel:u.string().min(1).optional(),staticSecretUsername:u.string().min(1).optional()}).strict(),nb=u.object({id:Am,subjectId:_e.optional(),ownerMode:In,upstreamServerId:Je,authProfileId:We,status:Tc,encryptedAccessToken:u.string().min(1).optional(),encryptedRefreshToken:u.string().min(1).optional(),scopes:u.array(u.string()),expiresAt:W.optional(),metadata:rb.optional(),createdAt:W,updatedAt:W});function Ec(e,t){e.ownerMode==="user"&&(e.subjectId||t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="shared"&&e.subjectId!==void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:"Shared upstream connections must not include subjectId",path:["subjectId"]})}o(Ec,"validateUpstreamConnectionOwnerShape");var kn=nb.superRefine(Ec);function Nr(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}o(Nr,"readUpstreamConnectionLookupKey");var Uc=Pn.extend({id:An,callbackPath:u.string().min(1),expiresAt:W,codeVerifier:u.string().optional(),redirectUri:u.url(),returnOrigin:u.url().optional()}).extend(km.shape);function Tm(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o(Tm,"readUpstreamConnectionStatus");function ai(){return Am.parse(`mcpgw2uc_${crypto.randomUUID()}`)}o(ai,"createUpstreamConnectionId");function Em(){return An.parse(crypto.randomUUID())}o(Em,"createOAuthStateId");function Um(){return Po.parse(crypto.randomUUID())}o(Um,"createBrowserConnectTicketId");ae();var $c=u.discriminatedUnion("mode",[u.object({mode:u.literal("user"),subjectId:_e}).strict(),u.object({mode:u.literal("shared")}).strict()]),$m=u.object({owner:$c,upstreamServerId:Je,authProfileId:We}).strict(),zm=u.object({items:u.array($m).min(1).max(100)}).strict(),zc=u.object({items:u.array(u.object({key:u.object({ownerMode:In,subjectId:_e.optional(),upstreamServerId:Je,authProfileId:We}).strict(),connection:kn.strict().optional()}).strict())}).strict(),Mm=kn.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(Ec),qm=kn.strict(),Nm=u.object({owner:$c,upstreamServerId:Je,authProfileId:We}).strict(),jm=u.object({owner:$c,upstreamServerId:Je,authProfileId:We,connection:kn.strict().optional(),connectionStatus:u.object({connected:u.boolean(),status:Tc,updatedAt:kn.shape.updatedAt.optional()}).strict()}).strict(),ob=u.enum(["none","client_secret_basic","client_secret_post"]),jr=u.object({clientId:Ne,clientName:u.string().min(1),tokenEndpointAuthMethod:ob}).strict(),Mc=u.discriminatedUnion("method",[u.object({method:u.literal("none"),clientId:Ne}).strict(),u.object({method:u.enum(["client_secret_basic","client_secret_post"]),clientId:Ne,clientSecretHashInput:u.string().min(1)}).strict()]),qc=u.object({id:ut,currentStateHash:u.string().min(1),clientId:Ne,redirectUri:u.string().min(1),resource:u.string().min(1),virtualServerId:xe,clientState:u.string().optional(),scope:u.string(),codeChallenge:u.string().min(1),codeChallengeMethod:u.literal("S256"),createdAt:W,expiresAt:W,consumedAt:W.optional()}).strict(),Om=qc.omit({id:!0,consumedAt:!0}).extend({transactionId:ut,client:jr.optional()}).strict(),Nc=u.object({subjectId:_e,roles:u.array(u.string()).optional()}).strict(),ab=qc.extend({phase:u.literal("awaiting_login")}).strict(),Oc=qc.extend({phase:u.literal("awaiting_setup"),principal:Nc}).strict(),ib=u.discriminatedUnion("phase",[ab,Oc]),jc=u.object({transaction:ib,client:jr}).strict(),Dm=vc.omit({revokedAt:!0}).strict(),Hm=u.discriminatedUnion("kind",[u.object({kind:u.literal("registered"),client:jr}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),Lm=u.object({clientId:Ne}).strict(),Bm=u.discriminatedUnion("kind",[u.object({kind:u.literal("found"),client:vc.strict()}).strict(),u.object({kind:u.literal("missing")}).strict()]),Gm=u.discriminatedUnion("phase",[Om.extend({phase:u.literal("awaiting_login")}).strict(),Om.extend({phase:u.literal("awaiting_setup"),principal:Nc}).strict()]),Vm=u.discriminatedUnion("kind",[jc.extend({kind:u.literal("started")}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("redirect_uri_mismatch")}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),Fm=u.object({transactionId:ut,currentStateHash:u.string().min(1),now:W}).strict(),Zm=u.discriminatedUnion("kind",[jc.extend({kind:u.literal("available")}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),Km=u.object({transactionId:ut,expectedPhase:u.literal("awaiting_login"),currentStateHash:u.string().min(1),nextStateHash:u.string().min(1),nextPhase:u.literal("awaiting_setup"),principal:Nc,now:W}).strict(),Jm=u.discriminatedUnion("kind",[jc.extend({kind:u.literal("advanced")}).strict(),u.object({kind:u.literal("wrong_phase"),current:u.enum(["awaiting_login","awaiting_setup"])}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),Wm=u.discriminatedUnion("decision",[u.object({decision:u.literal("approve"),transactionId:ut,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:_e}).strict(),authorizationCodeHash:u.string().min(1),authorizationCodeExpiresAt:W,grantId:Co,now:W}).strict(),u.object({decision:u.literal("cancel"),transactionId:ut,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:_e}).strict(),now:W}).strict()]),Ym=u.discriminatedUnion("kind",[u.object({kind:u.literal("approved"),transaction:Oc,client:jr}).strict(),u.object({kind:u.literal("cancelled"),transaction:Oc,client:jr}).strict(),u.object({kind:u.literal("principal_mismatch")}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed_already")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),Qm=u.object({clientAuth:Mc,codeHash:u.string().min(1),redirectUri:u.string().min(1),resource:u.string().min(1).optional(),codeChallenge:u.string().min(1),currentRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),grantExpiresAt:W,accessTokenExpiresAt:W,now:W}).strict(),Xm=u.discriminatedUnion("kind",[u.object({kind:u.literal("exchanged"),client:jr,grant:Rc.strict()}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("binding_mismatch")}).strict()]),ef=u.object({clientAuth:Mc,currentRefreshTokenHash:u.string().min(1),nextRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),resource:u.string().min(1).optional(),accessTokenExpiresAt:W,now:W}).strict(),tf=u.discriminatedUnion("kind",[u.object({kind:u.literal("rotated"),client:jr,grant:Rc.strict(),accessToken:ei.strict(),matched:u.literal("current")}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),rf=u.object({clientAuth:Mc,tokenHash:u.string().min(1),now:W}).strict(),nf=u.discriminatedUnion("kind",[u.object({kind:u.literal("revoked_access_token")}).strict(),u.object({kind:u.literal("revoked_grant")}).strict(),u.object({kind:u.literal("client_mismatch")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("invalid_client")}).strict()]),of=u.object({tokenHash:u.string().min(1),now:W}).strict(),af=u.discriminatedUnion("kind",[u.object({kind:u.literal("valid"),record:ei.strict()}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),sf=u.object({accessTokenHash:u.string().min(1),resource:u.string().min(1),virtualServerId:xe,upstreamConnectionKeys:u.array($m).max(100),now:W}).strict(),cf=u.discriminatedUnion("kind",[u.object({kind:u.literal("authorized"),principal:u.object({subjectId:_e,roles:u.array(u.string())}).strict(),accessToken:ei.strict(),upstreamConnections:zc.shape.items}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("principal_mismatch")}).strict()]),uf=u.object({record:Uc}).strict(),df=u.object({kind:u.literal("saved")}).strict(),lf=u.object({id:An,now:W}).strict(),pf=u.discriminatedUnion("kind",[u.object({kind:u.literal("available"),record:Uc}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict()]),mf=u.object({id:Po,expiresAt:W,now:W}).strict(),ff=u.discriminatedUnion("kind",[u.object({kind:u.literal("available")}).strict(),u.object({kind:u.literal("consumed")}).strict()]);var hf=100,sb=new Set(["undefined","null","nan"]);function gf(e){return e!==null&&typeof e=="object"}o(gf,"isProblemDetailsShape");var cb="/zups/v2/mcp/storage";function Ae(e){return`${cb}/${e}`}o(Ae,"buildStoragePath");function ub(){return Ae("upstream-connections/batch-get")}o(ub,"buildBatchGetUpstreamConnectionsPath");function db(){return Ae("upstream-connections/upsert")}o(db,"buildUpsertUpstreamConnectionPath");function lb(){return Ae("authorization/read-setup")}o(lb,"buildReadAuthorizationSetupPath");function pb(){return Ae("oauth/register-client")}o(pb,"buildRegisterClientPath");function mb(){return Ae("oauth/read-client")}o(mb,"buildReadClientPath");function fb(){return Ae("authorization/start")}o(fb,"buildStartAuthorizationPath");function hb(){return Ae("authorization/read-pending")}o(hb,"buildReadPendingAuthorizationPath");function gb(){return Ae("authorization/advance-pending")}o(gb,"buildAdvancePendingAuthorizationPath");function yb(){return Ae("authorization/decide-setup")}o(yb,"buildDecideAuthorizationSetupPath");function Sb(){return Ae("token/exchange-authorization-code")}o(Sb,"buildExchangeAuthorizationCodePath");function _b(){return Ae("token/refresh")}o(_b,"buildRefreshTokenPath");function wb(){return Ae("token/revoke")}o(wb,"buildRevokeOAuthTokenPath");function vb(){return Ae("token/validate-access-token")}o(vb,"buildValidateAccessTokenPath");function bb(){return Ae("mcp/authorize-and-load-connections")}o(bb,"buildAuthorizeAndLoadConnectionsPath");function Rb(){return Ae("upstream-oauth-state/save")}o(Rb,"buildSaveUpstreamOAuthStatePath");function Cb(){return Ae("upstream-oauth-state/consume")}o(Cb,"buildConsumeUpstreamOAuthStatePath");function Ib(){return Ae("browser-connect-ticket/consume")}o(Ib,"buildConsumeBrowserConnectTicketPath");function Pb(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(Pb,"responseKeyMatchesLookup");function xb(e,t){return e.owner.mode===t.owner.mode&&(e.owner.mode==="user"?e.owner.subjectId:"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(xb,"authorizationSetupMatchesLookup");function _f(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(_f,"connectionMatchesLookup");function Ab(e,t){return e.ownerMode===t.ownerMode&&(e.subjectId??"")===(t.subjectId??"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId&&e.status===t.status&&(e.encryptedAccessToken??"")===(t.encryptedAccessToken??"")&&(e.encryptedRefreshToken??"")===(t.encryptedRefreshToken??"")&&Hc(e.scopes,t.scopes)&&Dc(e.expiresAt,t.expiresAt)&&Tb(e.metadata,t.metadata)}o(Ab,"connectionMatchesUpsertRecord");function Dc(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}o(Dc,"optionalTimestampInstantsMatch");function kb(e,t){return Date.parse(e)<=Date.parse(t)}o(kb,"timestampInstantIsAtOrBefore");function Hc(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}o(Hc,"stringArraysMatch");function Tb(e,t){let r=yf(e),n=yf(t),a=Object.fromEntries(n);return r.length===n.length&&r.every(([i,s])=>a[i]===s)}o(Tb,"metadataMatches");function yf(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}o(yf,"definedMetadataEntries");function ve(e,t){throw g({code:"internal_server_error",privateDetail:e,cause:t})}o(ve,"throwInvalidStorageResponse");async function Eb(e,t){try{let r=await e.json();return r&&typeof r=="object"&&!Array.isArray(r)&&delete r.$schema,t.parse(r)}catch(r){ve("Gateway Service storage response did not match the runtime storage contract.",r)}}o(Eb,"parseRuntimeHttpStorageResponse");function wf(e,t){e.length!==t.length&&ve("Gateway Service storage response item count did not match the request.");for(let[r,n]of e.entries()){let a=t[r];Pb(n.key,a)||ve("Gateway Service storage response key did not match the request."),n.connection!==void 0&&!_f(n.connection,a)&&ve("Gateway Service storage response connection did not match the response key.")}}o(wf,"validateUpstreamConnectionItemsMatchLookups");function Ub(e,t){xb(e,t)||ve("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!_f(e.connection,t)&&ve("Gateway Service storage response authorization setup connection did not match the request.");let r=e.connection?.status==="active",n=e.connection?.status??"not_connected",a=e.connection?.updatedAt;(e.connectionStatus.connected!==r||e.connectionStatus.status!==n||!Dc(e.connectionStatus.updatedAt,a))&&ve("Gateway Service storage response authorization setup status did not match the connection.")}o(Ub,"validateAuthorizationSetupResponseMatchesLookup");function Ob(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&ve("Gateway Service storage response registered client did not match the request.")}o(Ob,"validateRegisterClientResponseMatchesRequest");function $b(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&ve("Gateway Service storage response client did not match the request.")}o($b,"validateReadClientResponseMatchesRequest");function zb(e,t){e.kind==="started"&&((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.phase!==t.phase||e.transaction.clientId!==t.clientId||e.transaction.redirectUri!==t.redirectUri||e.transaction.resource!==t.resource||e.transaction.virtualServerId!==t.virtualServerId||(e.transaction.clientState??"")!==(t.clientState??"")||e.transaction.scope!==t.scope||e.transaction.codeChallenge!==t.codeChallenge||e.transaction.codeChallengeMethod!==t.codeChallengeMethod)&&ve("Gateway Service storage response started authorization did not match the request."),t.phase==="awaiting_setup"&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&ve("Gateway Service storage response started authorization principal did not match the request."))}o(zb,"validateStartAuthorizationResponseMatchesRequest");function Sf(e,t){e.kind!=="available"&&e.kind!=="advanced"||((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==("nextStateHash"in t?t.nextStateHash:t.currentStateHash))&&ve("Gateway Service storage response pending authorization did not match the request."),"nextPhase"in t&&(e.transaction.phase!==t.nextPhase||e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&ve("Gateway Service storage response advanced authorization did not match the request."))}o(Sf,"validatePendingAuthorizationResponseMatchesRequest");function Mb(e,t){e.kind!=="approved"&&e.kind!=="cancelled"||(e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&ve("Gateway Service storage response authorization setup transaction did not match the request.")}o(Mb,"validateAuthorizationSetupDecisionResponseMatchesRequest");function qb(e,t){e.kind==="exchanged"&&(e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.currentRefreshTokenHash||!Dc(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&ve("Gateway Service storage response authorization-code exchange did not match the request.")}o(qb,"validateExchangeAuthorizationCodeResponseMatchesRequest");function Nb(e,t){e.kind==="rotated"&&((e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.nextRefreshTokenHash||e.grant.previousRefreshTokenHash!==t.currentRefreshTokenHash||t.resource!==void 0&&e.grant.resource!==t.resource)&&ve("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!kb(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!Hb(e.accessToken,e.grant))&&ve("Gateway Service storage response token refresh access token did not match the request."))}o(Nb,"validateRefreshTokenResponseMatchesRequest");function jb(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&ve("Gateway Service storage response access token did not match the request.")}o(jb,"validateAccessTokenValidationResponseMatchesRequest");function Db(e,t){e.kind==="authorized"&&((e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.resource!==t.resource||e.accessToken.virtualServerId!==t.virtualServerId||e.principal.subjectId!==e.accessToken.subjectId||!Hc(e.principal.roles,e.accessToken.roles))&&ve("Gateway Service storage response MCP authorization did not match the request."),wf(e.upstreamConnections,t.upstreamConnectionKeys))}o(Db,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function Hb(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.virtualServerId===t.virtualServerId&&e.subjectId===t.subjectId&&e.scope===t.scope&&Hc(e.roles,t.roles)}o(Hb,"accessTokenMatchesGrant");async function Lb(e){try{return await e.clone().json()}catch{return}}o(Lb,"readProblemDetails");async function Bb(e){let t=await Lb(e),r=gf(t)&&typeof t.status=="number"?t.status:e.status,n=gf(t)&&wo(t.code)?t.code:rm(r);throw g({code:n,privateDetail:`Gateway Service storage request failed with HTTP ${r}.`})}o(Bb,"throwRuntimeHttpStorageError");var ii=class{static{o(this,"RuntimeHttpStorageClient")}#t;#r;constructor(t){this.#t=t.baseUrl??So.instance.zuploEdgeApiUrl,this.#r=t.fetch??fetch}#n(t){let r;try{r=new URL(t,this.#t)}catch(n){throw g("internal_server_error",`Gateway Service storage base URL is not a valid URL. Got ${JSON.stringify(this.#t)}. Verify the gateway runtime configuration.`,n)}if(r.protocol!=="https:"&&r.protocol!=="http:")throw g("internal_server_error",`Gateway Service storage base URL must use http(s); got protocol "${r.protocol}" from ${JSON.stringify(this.#t)}.`);if(!r.hostname||sb.has(r.hostname))throw g("internal_server_error",`Gateway Service storage base URL has an invalid hostname "${r.hostname}" (parsed from ${JSON.stringify(this.#t)}). The configured value is likely coerced from an unset environment variable.`);return r}async#e(t){let r=t.requestSchema.parse(t.input),n=this.#n(t.path),a=new Headers({"Content-Type":"application/json"});Vp(a);let i=await this.#r(n,{method:"POST",headers:a,body:JSON.stringify(r)});return i.ok||await Bb(i),{request:r,response:await Eb(i,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],n=new Map,a=t.map(s=>{let c=Nr(s),d=n.get(c);if(d!==void 0)return d;let p=r.length;return r.push(s),n.set(c,p),p}),i=[];for(let s=0;s<r.length;s+=hf){let c=r.slice(s,s+hf);i.push(...await this.#o(c))}return a.map(s=>i[s])}async upsertUpstreamConnection(t){let{request:r,response:n}=await this.#e({input:t,path:db(),requestSchema:Mm,responseSchema:qm});return Ab(n,r)||ve("Gateway Service storage response connection did not match the request."),n}async readAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:lb(),requestSchema:Nm,responseSchema:jm});return Ub(n,r),n}async registerClient(t){let{request:r,response:n}=await this.#e({input:t,path:pb(),requestSchema:Dm,responseSchema:Hm});return Ob(n,r),n}async readClient(t){let{request:r,response:n}=await this.#e({input:t,path:mb(),requestSchema:Lm,responseSchema:Bm});return $b(n,r),n}async startAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:fb(),requestSchema:Gm,responseSchema:Vm});return zb(n,r),n}async readPendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:hb(),requestSchema:Fm,responseSchema:Zm});return Sf(n,r),n}async advancePendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:gb(),requestSchema:Km,responseSchema:Jm});return Sf(n,r),n}async decideAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:yb(),requestSchema:Wm,responseSchema:Ym});return Mb(n,r),n}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:Rb(),requestSchema:uf,responseSchema:df});return r}async consumeUpstreamOAuthState(t){let{request:r,response:n}=await this.#e({input:t,path:Cb(),requestSchema:lf,responseSchema:pf});return n.kind==="available"&&n.record.id!==r.id&&ve("Gateway Service storage response upstream OAuth state did not match the request."),n}async consumeBrowserConnectTicket(t){let{response:r}=await this.#e({input:t,path:Ib(),requestSchema:mf,responseSchema:ff});return r}async exchangeAuthorizationCode(t){let{request:r,response:n}=await this.#e({input:t,path:Sb(),requestSchema:Qm,responseSchema:Xm});return qb(n,r),n}async refreshToken(t){let{request:r,response:n}=await this.#e({input:t,path:_b(),requestSchema:ef,responseSchema:tf});return Nb(n,r),n}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:wb(),requestSchema:rf,responseSchema:nf});return r}async validateAccessToken(t){let{request:r,response:n}=await this.#e({input:t,path:vb(),requestSchema:of,responseSchema:af});return jb(n,r),n}async authorizeAndLoadConnections(t){let{request:r,response:n}=await this.#e({input:t,path:bb(),requestSchema:sf,responseSchema:cf});return Db(n,r),n}async#o(t){let r={items:[...t]},{response:n}=await this.#e({input:r,path:ub(),requestSchema:zm,responseSchema:zc});return wf(n.items,t),n.items.map(a=>a.connection)}};var Gb="__zuploMcpGatewayStorageBackend",Lc;function Vb(){return new ii({})}o(Vb,"buildProductionStorageBackend");function K(){let e=globalThis[Gb];return e||(Lc||(Lc=Vb()),Lc)}o(K,"getStorage");import{base64url as Bc}from"jose";var Fb="sha256:",Zb=32;function vf(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(vf,"copyToArrayBuffer");function Ht(){let e=crypto.getRandomValues(new Uint8Array(Zb));return Bc.encode(e)}o(Ht,"createOpaqueToken");async function le(e){let t=await crypto.subtle.digest("SHA-256",vf(new TextEncoder().encode(e)));return`${Fb}${Bc.encode(new Uint8Array(t))}`}o(le,"hashOpaqueValue");async function bf(e){let t=await crypto.subtle.digest("SHA-256",vf(new TextEncoder().encode(e)));return Bc.encode(new Uint8Array(t))}o(bf,"calculatePkceS256Challenge");function Gc(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(Gc,"readBearerToken");function Kb(e,t,r){return st(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(Kb,"gatewayAuthenticationRequiredResponse");async function Jb(e,t,r){let n=await K().validateAccessToken({tokenHash:await le(e),now:re(new Date)});if(n.kind!=="valid")throw t.log.warn({event:"gateway_access_token_validate_failed",code:"authentication_required",validationKind:n.kind,virtualServerId:r},"Gateway access token validation failed"),g("authentication_required","Gateway access token is expired, revoked, or invalid.");return n.record}o(Jb,"validateGatewayAccessToken");function Wb(e,t){if(e.accessToken.resource!==e.resource||e.accessToken.virtualServerId!==e.virtualServerId)throw t.log.warn({event:"gateway_access_token_resource_mismatch",code:"authentication_required",expectedResource:e.resource,tokenResource:e.accessToken.resource,expectedVirtualServerId:e.virtualServerId,tokenVirtualServerId:e.accessToken.virtualServerId,clientId:e.accessToken.clientId},"Gateway access token resource does not match the requested MCP resource"),g("authentication_required","Gateway access token was not issued for this MCP resource.")}o(Wb,"assertAccessTokenResource");function Yb(e,t,r){return st(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":ri({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${Se} scope required by this MCP resource.`,scope:Se})}})}o(Yb,"insufficientScopeResponse");function Qb(e){return{subjectId:e.subjectId,roles:e.roles}}o(Qb,"principalFromAccessToken");function Xb(e){let t=ge(e.error),r={event:"gateway_access_token_rejected",code:t??"authentication_required",virtualServerId:e.virtualServerId};return e.error instanceof Error?(r.errorName=e.error.name,r.errorMessage=e.error.message):e.error!==void 0&&e.error!==null&&(r.errorMessage=String(e.error)),e.context.log.warn(r,"Gateway access token rejected; MCP request denied"),st(e.request,e.context,{code:t??"authentication_required",detail:e.error instanceof Error?e.error.message:"Gateway access token could not be verified.",headers:{"WWW-Authenticate":ri({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(Xb,"gatewayTokenRejectedResponse");async function Vc(e,t){let r=bn(t),n=Mr(r.virtualServerId,e.url),a=Gc(e),i=ri({virtualServerId:r.virtualServerId,requestUrl:e.url});if(!a)return t.log.debug({event:"gateway_access_token_missing",code:"authentication_required",virtualServerId:r.virtualServerId,hasAuthorizationHeader:e.headers.get("authorization")!==null},"MCP request did not include a gateway access token"),Kb(e,t,i);try{let s=await Jb(a,t,r.virtualServerId);if(Wb({accessToken:s,resource:n,virtualServerId:r.virtualServerId},t),s.scope!==Se)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:s.scope,requiredScope:Se,virtualServerId:r.virtualServerId,clientId:s.clientId},"Gateway access token does not have the required MCP scope"),Yb(e,t,r.virtualServerId);let c=Qb(s);return Cm(t,c),Sc(t,c),e}catch(s){return Xb({request:e,context:t,error:s,virtualServerId:r.virtualServerId})}}o(Vc,"gatewayTokenInbound");var eR=2,Rf=4,tR=24,rR=16,Cf=512,nR=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,oR=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,aR=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,iR=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,sR=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,cR=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function If(e){let t=e.route;return t&&typeof t=="object"?t:void 0}o(If,"readRoute");function uR(e){let t=If(e)?.path;return typeof t=="string"&&t.length>0?t:void 0}o(uR,"readRoutePath");function dR(e){let t=If(e)?.raw;if(typeof t!="function")return;let r=t();if(!r||typeof r!="object")return;let n=r.operationId;return typeof n=="string"&&n.length>0?n:void 0}o(dR,"readRouteOperationId");function lR(e){if(!(e===void 0||!Number.isFinite(e)||e<100))return`${Math.trunc(e/100)}xx`}o(lR,"deriveStatusClass");function pR(e,t){if(!(!e&&!t))return e==="user"?t==="user_oauth"?"upstream_user_attributed":"gateway_user_attributed_only":e==="shared"?"shared_upstream_identity":e==="none"?"machine_identity":"unknown"}o(pR,"deriveOriginAttributionMode");function mR(e){if(!e)return;let t=e.toLowerCase();return t.includes("desktop")||t.includes("claude")||t.includes("chatgpt")?"desktop":t.includes("vscode")||t.includes("cursor")||t.includes("zed")||t.includes("jetbrains")||t.includes("ide")?"ide":t.includes("extension")?"extension":t.includes("agent")||t.includes("bot")||t.includes("worker")||t.includes("service")?"service":"unknown"}o(mR,"deriveClientKind");function fR(e,t){return t==="success"?"none":e===Z.MCP_GATEWAY_REQUEST_RECEIVED||e===Z.MCP_GATEWAY_REQUEST_REJECTED||e===Z.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===Z.MCP_GATEWAY_INITIALIZE_NEGOTIATED?"routing":e===Z.MCP_GATEWAY_POLICY_DECISION?"policy":e===Z.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===Z.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e.startsWith("mcp_gateway_capability_")||e.startsWith("mcp_gateway_catalog_")?"upstream":e===Z.MCP_GATEWAY_REQUEST_COMPLETED?"egress":"none"}o(fR,"deriveFailureStage");function hR(e,t){return t==="success"?"none":t==="application_error"?"mcp_application":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===Z.MCP_GATEWAY_POLICY_DECISION||e===Z.MCP_GATEWAY_GUARDRAIL_DECISION||e===Z.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e===Z.MCP_GATEWAY_CAPABILITY_FAILED||e===Z.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED?"upstream":e===Z.MCP_GATEWAY_REQUEST_REJECTED||e===Z.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}o(hR,"deriveFailureOrigin");function gR(e,t){return t==="success"?"none":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===Z.MCP_GATEWAY_POLICY_DECISION?"policy":e===Z.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===Z.MCP_GATEWAY_RATE_LIMIT_DECISION?"rate_limit":e.startsWith("mcp_gateway_upstream_")?"upstream":e===Z.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR||e===Z.MCP_GATEWAY_REQUEST_REJECTED?"protocol":"none"}o(gR,"deriveReasonClass");function yR(e){return e.length<=Cf?e:`${e.slice(0,Cf)}...`}o(yR,"truncateAnalyticsString");function SR(e){return yR(e.replace(oR,"$1[REDACTED]$3").replace(iR,"$1$2[REDACTED]").replace(aR,"$1$2[REDACTED]").replace(sR,"Bearer [REDACTED]").replace(cR,"Basic [REDACTED]"))}o(SR,"redactAnalyticsString");function Pf(e,t){if(e!==void 0){if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return SR(e);if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(Array.isArray(e))return t>=Rf?"[DEPTH_LIMIT]":e.slice(0,rR).map(r=>Pf(r,t+1)).filter(r=>r!==void 0);if(typeof e=="object")return e instanceof Date?e.toISOString():t>=Rf?"[DEPTH_LIMIT]":xf(e,t+1)}}o(Pf,"sanitizeAnalyticsValue");function xf(e,t=0){if(!e)return;let r={};for(let[n,a]of Object.entries(e).slice(0,tR)){if(nR.test(n)){r[n]="[REDACTED]";continue}let i=Pf(a,t);i!==void 0&&(r[n]=i)}return Object.keys(r).length===0?void 0:r}o(xf,"sanitizeMcpGatewayAnalyticsAttributes");function z(e){return e===void 0?null:e}o(z,"nullable");function _R(e){let t=e.environment;return t&&typeof t=="object"&&typeof t.name=="string"?t.name:null}o(_R,"readEnvironment");function wR(e){let t=e.requestId;return typeof t=="string"&&t.length>0?t:null}o(wR,"readRequestId");function vR(e){if(e===void 0)return null;try{return JSON.stringify(e)}catch{return null}}o(vR,"attributesToJsonString");function bR(e,t){let r=kc(e),n=vo(e),a=xf(t.attributes),i=wR(e),s=t.ownerMode??t.routeBinding?.ownerMode??null,c=t.upstreamAuthMode??t.routeBinding?.authMode??null,d=t.virtualServerName??t.routeBinding?.virtualServerId??n?.virtualServerId??null,p=t.upstreamServerName??t.routeBinding?.upstreamServerId??n?.upstreamServerId??null,l=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName??null,m=t.authProfileId??t.routeBinding?.authProfileId??n?.authProfileId??null,h=t.clientKind??mR(t.clientName)??null,y=pR(s??void 0,c??void 0)??null,_=lR(t.httpStatusCode)??null,S=t.reasonClass??gR(t.eventType,t.outcome),w=t.failureOrigin??hR(t.eventType,t.outcome),v=t.failureStage??fR(t.eventType,t.outcome);return{schemaVersion:eR,outcome:t.outcome,subjectId:z(r?.subjectId),environment:_R(e),traceId:t.traceId??i,spanId:z(t.spanId),parentEventId:z(t.parentEventId),mcpSessionId:z(t.mcpSessionId),routeSurface:z(t.routeSurface),routePath:uR(e)??null,operationId:dR(e)??null,virtualServerName:d,virtualServerTitle:z(t.virtualServerTitle),upstreamServerName:p,upstreamServerTitle:l,upstreamBindingId:z(t.upstreamBindingId),clientName:z(t.clientName),clientTitle:z(t.clientTitle),clientVersion:z(t.clientVersion),clientKind:h,authProfileId:m,upstreamAuthMode:c,ownerMode:s,authMethod:z(t.authMethod),originAttributionMode:y,httpMethod:z(t.httpMethod),httpStatusCode:z(t.httpStatusCode),statusClass:_,mcpMethod:z(t.mcpMethod),mcpProtocolVersion:z(t.mcpProtocolVersion),mcpStatus:z(t.mcpStatus),mcpErrorType:z(t.mcpErrorType),applicationError:z(t.applicationError),applicationErrorCode:z(t.applicationErrorCode),toolResultIsError:z(t.toolResultIsError),capabilityType:z(t.capabilityType),capabilityName:z(t.capabilityName),capabilityTitle:z(t.capabilityTitle),upstreamCapabilityName:z(t.upstreamCapabilityName),upstreamCapabilityTitle:z(t.upstreamCapabilityTitle),capabilitySchemaHash:z(t.capabilitySchemaHash),policyId:z(t.policyId),policyAction:z(t.policyAction),guardrailType:z(t.guardrailType),guardrailDirection:z(t.guardrailDirection),guardrailFindingCount:z(t.guardrailFindingCount),redactionCount:z(t.redactionCount),requestMutated:z(t.requestMutated),responseMutated:z(t.responseMutated),latencyMs:z(t.latencyMs),gatewayLatencyMs:z(t.gatewayLatencyMs),upstreamLatencyMs:z(t.upstreamLatencyMs),authLatencyMs:z(t.authLatencyMs),policyLatencyMs:z(t.policyLatencyMs),requestBytes:z(t.requestBytes),responseBytes:z(t.responseBytes),estimatedInputTokens:z(t.estimatedInputTokens),estimatedOutputTokens:z(t.estimatedOutputTokens),estimatedContextTokens:z(t.estimatedContextTokens),contextPressureBucket:z(t.contextPressureBucket),responseMimeTypes:z(t.responseMimeTypes),base64Suspected:z(t.base64Suspected),truncated:z(t.truncated),isLargePayloadRequest:z(t.isLargePayloadRequest),isLargePayloadResponse:z(t.isLargePayloadResponse),payloadCaptureMode:z(t.payloadCaptureMode),reasonCode:z(t.reasonCode),reasonClass:S,errorType:t.errorType??t.reasonCode??null,failureOrigin:w,failureStage:v,customMetadataJson:z(t.customMetadataJson),attributesJson:vR(a)}}o(bR,"buildMcpGatewayAnalyticsMetadata");function Qe(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,bR(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_gateway_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(Qe,"emitMcpGatewayAnalyticsEvent");var Tn={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},RR="oauth-protected-resource-metadata",CR="/.well-known/oauth-protected-resource/";function IR(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}o(IR,"readRouteOperationId");function PR(e){return e.hasGatewayRouteContext?Tn.VIRTUAL_MCP_SERVER:e.routeOperationId===RR||e.routeOperationId===void 0&&e.routePath.startsWith(CR)?Tn.OAUTH_PROTECTED_RESOURCE_METADATA:Tn.OTHER}o(PR,"classifyAnalyticsRouteSurface");function xR(e){let t=e.route.path;return{routePath:t,routeSurface:PR({routePath:t,routeOperationId:IR(e),hasGatewayRouteContext:vo(e)!==void 0})}}o(xR,"readAnalyticsRequestContext");function AR(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Tn.VIRTUAL_MCP_SERVER}o(AR,"isIntentionalMethodRejection");function kR(e){return AR(e)||e.response.status===401&&e.routeSurface===Tn.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(kR,"classifyRequestCompletedOutcome");async function Fc(e,t){let r=Date.now(),n=xR(t);return t.addResponseSendingFinalHook(a=>{let i=kR({response:a,routeSurface:n.routeSurface});Qe(t,{eventType:Z.MCP_GATEWAY_REQUEST_COMPLETED,outcome:i,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(Fc,"analyticsContextInbound");function TR(e){return e instanceof Response}o(TR,"isResponse");var Af="/mcp/";function ER(e){let t=e.route.path;if(!t.startsWith(Af))throw new ue(`Route ${t} is bound to mcp-oauth-inbound but does not match the /mcp/{virtualServerId} convention.`);let r=t.slice(Af.length);if(!r||r.includes("/"))throw new ue(`Route ${t} is bound to mcp-oauth-inbound but must use exactly one /mcp/{virtualServerId} segment.`);return r}o(ER,"readVirtualServerIdFromRoute");async function xo(e,t){let n={virtualServerId:xe.parse(ER(t))};im(t,n),mm(t,n);let a=await Fc(e,t);return TR(a)?a:Vc(a,t)}o(xo,"mcpOAuthInboundPolicy");function si(e,t,r){let n=e.safeParse(t);if(n.success)return n.data;throw new ue(`${r} is misconfigured. Validation failed:
33
+ ${UR(n.error)}`,{cause:n.error})}o(si,"parseConfigOrThrow");function UR(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
34
+ `)}o(UR,"formatZodIssues");var OR=u.string({error:"auth0Domain is required and must be a string"}).trim().min(1,"auth0Domain is required (commonly set via $env(AUTH0_DOMAIN))").refine(e=>!/[:/]/.test(e),{message:'auth0Domain must be a bare hostname (e.g. "tenant.us.auth0.com"); drop the "https://" prefix and any trailing path'}).refine(e=>e.includes("."),{message:'auth0Domain must be a fully-qualified domain name with at least one dot (e.g. "tenant.us.auth0.com"). If the value looks like "undefined" or is empty, the configured environment variable is likely unset.'}),$R=u.object({auth0Domain:OR,audience:u.string().trim().min(1).optional(),clientId:u.string({error:"clientId is required and must be a string"}).trim().min(1,"clientId is required (commonly set via $env(AUTH0_CLIENT_ID))"),clientSecret:u.string().trim().min(1).optional(),scope:u.string().trim().min(1).optional(),gateway:u.object({accessTokenTtlSeconds:u.number().int().positive().optional(),refreshTokenTtlSeconds:u.number().int().positive().optional(),cimdEnabled:u.boolean().optional()}).strict().optional(),browserLoginOverrides:u.object({remoteTimeoutMs:u.number().int().positive().optional(),stateTtlSeconds:u.number().int().positive().optional(),sessionTtlSeconds:u.number().int().positive().optional()}).strict().optional()}).strict(),Zc=class extends wn{static{o(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,r){let n=kf(t,r);super(n,r),this.#t=Ef(n,r)}async handler(t,r){return Ct("policy.inbound.mcp-auth0-oauth"),Rn(r,this.#t),xo(t,r)}};function kf(e,t){return si($R,e,`MCP Auth0 OAuth policy "${t}"`)}o(kf,"parseAuth0OAuthOptions");function Tf(e,t="mcp-auth0-oauth-inbound"){let r=kf(e,t);return Ef(r,t)}o(Tf,"auth0OptionsToMcpOAuthRuntimeConfig");function Ef(e,t){let r=`https://${e.auth0Domain}/`,n=`https://${e.auth0Domain}/.well-known/jwks.json`,a=`https://${e.auth0Domain}/authorize`,i=`https://${e.auth0Domain}/oauth/token`;try{return dm({oidc:{issuer:r,jwksUrl:n,...e.audience===void 0?{}:{audience:e.audience}},browserLogin:{url:a,tokenUrl:i,clientId:e.clientId,clientSecret:e.clientSecret,scope:e.scope??"openid profile email",...e.audience===void 0?{}:{audience:e.audience},...e.browserLoginOverrides??{}},gateway:e.gateway})}catch(s){let c=s instanceof Error?` Validation failed: ${s.message}`:"";throw new ue(`MCP Auth0 OAuth policy "${t}" is misconfigured. Check the policy options in policies.json.${c}`,s instanceof Error?{cause:s}:void 0)}}o(Ef,"buildAuth0McpOAuthRuntimeConfig");var Kc=class extends wn{static{o(this,"McpOAuthInboundPolicy")}#t;constructor(t,r){let n=Jc(t,r);super(n,r),this.#t=n}async handler(t,r){return Ct("policy.inbound.mcp-oauth"),Rn(r,this.#t),xo(t,r)}};function Jc(e,t="mcp-oauth-inbound"){return si(fc,e,`MCP OAuth policy "${t}"`)}o(Jc,"mcpOAuthOptionsToRuntimeConfig");var Wc=["mcp-oauth-inbound","mcp-auth0-oauth-inbound"];function zR(e,t){switch(e){case"mcp-oauth-inbound":return Jc(t);case"mcp-auth0-oauth-inbound":return Tf(t);default:return}}o(zR,"parseMcpOAuthPolicyConfig");function Ao(e){return e!==void 0&&Wc.some(t=>t===e)}o(Ao,"isMcpOAuthInboundPolicyType");function Uf(e){if(e){for(let t of e)if(Ao(t.policyType))try{let r=zR(t.policyType,t.handler.options);if(!r)throw new ue(`MCP gateway: policy '${t.name}' has unsupported MCP OAuth policy type '${t.policyType}'.`);return{policyName:t.name,config:r}}catch(r){throw r instanceof u.ZodError?new ue(MR(t.name,r),{cause:r}):r}}}o(Uf,"resolveMcpOAuthRuntimeConfigFromPolicies");function MR(e,t){let r=t.issues.map(n=>` - ${n.path.length>0?n.path.join("."):"<root>"}: ${n.message}`).join(`
35
+ `);return`MCP OAuth policy "${e}" is misconfigured. Missing/invalid options:
36
+ ${r}`}o(MR,"formatPolicyConfigError");ae();var cr="2025-11-25",Of="2025-03-26",ur=[cr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],dr="io.modelcontextprotocol/related-task",ui="2.0",Ie=Qp(e=>e!==null&&(typeof e=="object"||typeof e=="function")),$f=fe([f(),X().int()]),zf=f(),Oj=Ce({ttl:X().optional(),pollInterval:X().optional()}),NR=I({ttl:X().optional()}),jR=I({taskId:f()}),Yc=Ce({progressToken:$f.optional(),[dr]:jR.optional()}),ot=I({_meta:Yc.optional()}),ko=ot.extend({task:NR.optional()}),Mf=o(e=>ko.safeParse(e).success,"isTaskAugmentedRequestParams"),ke=I({method:f(),params:ot.loose().optional()}),dt=I({_meta:Yc.optional()}),lt=I({method:f(),params:dt.loose().optional()}),Te=Ce({_meta:Yc.optional()}),di=fe([f(),X().int()]),qf=I({jsonrpc:U(ui),id:di,...ke.shape}).strict(),Pt=o(e=>qf.safeParse(e).success,"isJSONRPCRequest"),Nf=I({jsonrpc:U(ui),...lt.shape}).strict(),jf=o(e=>Nf.safeParse(e).success,"isJSONRPCNotification"),Qc=I({jsonrpc:U(ui),id:di,result:Te}).strict(),yt=o(e=>Qc.safeParse(e).success,"isJSONRPCResultResponse");var E;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(E||(E={}));var Xc=I({jsonrpc:U(ui),id:di.optional(),error:I({code:X().int(),message:f(),data:we().optional()})}).strict();var Un=o(e=>Xc.safeParse(e).success,"isJSONRPCErrorResponse");var Dr=fe([qf,Nf,Qc,Xc]),$j=fe([Qc,Xc]),Lt=Te.strict(),DR=dt.extend({requestId:di.optional(),reason:f().optional()}),li=lt.extend({method:U("notifications/cancelled"),params:DR}),HR=I({src:f(),mimeType:f().optional(),sizes:C(f()).optional(),theme:nt(["light","dark"]).optional()}),To=I({icons:C(HR).optional()}),En=I({name:f(),title:f().optional()}),On=En.extend({...En.shape,...To.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),LR=pc(I({applyDefaults:oe().optional()}),de(f(),we())),BR=mc(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,pc(I({form:LR.optional(),url:Ie.optional()}),de(f(),we()).optional())),GR=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({sampling:Ce({createMessage:Ie.optional()}).optional(),elicitation:Ce({create:Ie.optional()}).optional()}).optional()}),VR=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({tools:Ce({call:Ie.optional()}).optional()}).optional()}),FR=I({experimental:de(f(),Ie).optional(),sampling:I({context:Ie.optional(),tools:Ie.optional()}).optional(),elicitation:BR.optional(),roots:I({listChanged:oe().optional()}).optional(),tasks:GR.optional(),extensions:de(f(),Ie).optional()}),ZR=ot.extend({protocolVersion:f(),capabilities:FR,clientInfo:On}),pi=ke.extend({method:U("initialize"),params:ZR}),eu=o(e=>pi.safeParse(e).success,"isInitializeRequest"),KR=I({experimental:de(f(),Ie).optional(),logging:Ie.optional(),completions:Ie.optional(),prompts:I({listChanged:oe().optional()}).optional(),resources:I({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:I({listChanged:oe().optional()}).optional(),tasks:VR.optional(),extensions:de(f(),Ie).optional()}),tu=Te.extend({protocolVersion:f(),capabilities:KR,serverInfo:On,instructions:f().optional()}),mi=lt.extend({method:U("notifications/initialized"),params:dt.optional()}),Df=o(e=>mi.safeParse(e).success,"isInitializedNotification"),fi=ke.extend({method:U("ping"),params:ot.optional()}),JR=I({progress:X(),total:ye(X()),message:ye(f())}),WR=I({...dt.shape,...JR.shape,progressToken:$f}),hi=lt.extend({method:U("notifications/progress"),params:WR}),YR=ot.extend({cursor:zf.optional()}),Eo=ke.extend({params:YR.optional()}),Uo=Te.extend({nextCursor:zf.optional()}),QR=nt(["working","input_required","completed","failed","cancelled"]),Oo=I({taskId:f(),status:QR,ttl:fe([X(),Wp()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:ye(X()),statusMessage:ye(f())}),Bt=Te.extend({task:Oo}),XR=dt.merge(Oo),$o=lt.extend({method:U("notifications/tasks/status"),params:XR}),gi=ke.extend({method:U("tasks/get"),params:ot.extend({taskId:f()})}),yi=Te.merge(Oo),Si=ke.extend({method:U("tasks/result"),params:ot.extend({taskId:f()})}),zj=Te.loose(),_i=Eo.extend({method:U("tasks/list")}),wi=Uo.extend({tasks:C(Oo)}),vi=ke.extend({method:U("tasks/cancel"),params:ot.extend({taskId:f()})}),Hf=Te.merge(Oo),Lf=I({uri:f(),mimeType:ye(f()),_meta:de(f(),we()).optional()}),Bf=Lf.extend({text:f()}),ru=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Gf=Lf.extend({blob:ru}),zo=nt(["user","assistant"]),$n=I({audience:C(zo).optional(),priority:X().min(0).max(1).optional(),lastModified:Kp.datetime({offset:!0}).optional()}),Vf=I({...En.shape,...To.shape,uri:f(),description:ye(f()),mimeType:ye(f()),size:ye(X()),annotations:$n.optional(),_meta:ye(Ce({}))}),eC=I({...En.shape,...To.shape,uriTemplate:f(),description:ye(f()),mimeType:ye(f()),annotations:$n.optional(),_meta:ye(Ce({}))}),nu=Eo.extend({method:U("resources/list")}),ou=Uo.extend({resources:C(Vf)}),au=Eo.extend({method:U("resources/templates/list")}),iu=Uo.extend({resourceTemplates:C(eC)}),su=ot.extend({uri:f()}),tC=su,cu=ke.extend({method:U("resources/read"),params:tC}),uu=Te.extend({contents:C(fe([Bf,Gf]))}),du=lt.extend({method:U("notifications/resources/list_changed"),params:dt.optional()}),rC=su,nC=ke.extend({method:U("resources/subscribe"),params:rC}),oC=su,aC=ke.extend({method:U("resources/unsubscribe"),params:oC}),iC=dt.extend({uri:f()}),sC=lt.extend({method:U("notifications/resources/updated"),params:iC}),cC=I({name:f(),description:ye(f()),required:ye(oe())}),uC=I({...En.shape,...To.shape,description:ye(f()),arguments:ye(C(cC)),_meta:ye(Ce({}))}),lu=Eo.extend({method:U("prompts/list")}),pu=Uo.extend({prompts:C(uC)}),dC=ot.extend({name:f(),arguments:de(f(),f()).optional()}),mu=ke.extend({method:U("prompts/get"),params:dC}),fu=I({type:U("text"),text:f(),annotations:$n.optional(),_meta:de(f(),we()).optional()}),hu=I({type:U("image"),data:ru,mimeType:f(),annotations:$n.optional(),_meta:de(f(),we()).optional()}),gu=I({type:U("audio"),data:ru,mimeType:f(),annotations:$n.optional(),_meta:de(f(),we()).optional()}),lC=I({type:U("tool_use"),name:f(),id:f(),input:de(f(),we()),_meta:de(f(),we()).optional()}),pC=I({type:U("resource"),resource:fe([Bf,Gf]),annotations:$n.optional(),_meta:de(f(),we()).optional()}),mC=Vf.extend({type:U("resource_link")}),yu=fe([fu,hu,gu,mC,pC]),fC=I({role:zo,content:yu}),Su=Te.extend({description:f().optional(),messages:C(fC)}),_u=lt.extend({method:U("notifications/prompts/list_changed"),params:dt.optional()}),hC=I({title:f().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),gC=I({taskSupport:nt(["required","optional","forbidden"]).optional()}),Ff=I({...En.shape,...To.shape,description:f().optional(),inputSchema:I({type:U("object"),properties:de(f(),Ie).optional(),required:C(f()).optional()}).catchall(we()),outputSchema:I({type:U("object"),properties:de(f(),Ie).optional(),required:C(f()).optional()}).catchall(we()).optional(),annotations:hC.optional(),execution:gC.optional(),_meta:de(f(),we()).optional()}),wu=Eo.extend({method:U("tools/list")}),vu=Uo.extend({tools:C(Ff)}),lr=Te.extend({content:C(yu).default([]),structuredContent:de(f(),we()).optional(),isError:oe().optional()}),Mj=lr.or(Te.extend({toolResult:we()})),yC=ko.extend({name:f(),arguments:de(f(),we()).optional()}),Mo=ke.extend({method:U("tools/call"),params:yC}),bu=lt.extend({method:U("notifications/tools/list_changed"),params:dt.optional()}),Zf=I({autoRefresh:oe().default(!0),debounceMs:X().int().nonnegative().default(300)}),qo=nt(["debug","info","notice","warning","error","critical","alert","emergency"]),SC=ot.extend({level:qo}),Ru=ke.extend({method:U("logging/setLevel"),params:SC}),_C=dt.extend({level:qo,logger:f().optional(),data:we()}),wC=lt.extend({method:U("notifications/message"),params:_C}),vC=I({name:f().optional()}),bC=I({hints:C(vC).optional(),costPriority:X().min(0).max(1).optional(),speedPriority:X().min(0).max(1).optional(),intelligencePriority:X().min(0).max(1).optional()}),RC=I({mode:nt(["auto","required","none"]).optional()}),CC=I({type:U("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:C(yu).default([]),structuredContent:I({}).loose().optional(),isError:oe().optional(),_meta:de(f(),we()).optional()}),IC=lc("type",[fu,hu,gu]),ci=lc("type",[fu,hu,gu,lC,CC]),PC=I({role:zo,content:fe([ci,C(ci)]),_meta:de(f(),we()).optional()}),xC=ko.extend({messages:C(PC),modelPreferences:bC.optional(),systemPrompt:f().optional(),includeContext:nt(["none","thisServer","allServers"]).optional(),temperature:X().optional(),maxTokens:X().int(),stopSequences:C(f()).optional(),metadata:Ie.optional(),tools:C(Ff).optional(),toolChoice:RC.optional()}),Cu=ke.extend({method:U("sampling/createMessage"),params:xC}),Hr=Te.extend({model:f(),stopReason:ye(nt(["endTurn","stopSequence","maxTokens"]).or(f())),role:zo,content:IC}),No=Te.extend({model:f(),stopReason:ye(nt(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:zo,content:fe([ci,C(ci)])}),AC=I({type:U("boolean"),title:f().optional(),description:f().optional(),default:oe().optional()}),kC=I({type:U("string"),title:f().optional(),description:f().optional(),minLength:X().optional(),maxLength:X().optional(),format:nt(["email","uri","date","date-time"]).optional(),default:f().optional()}),TC=I({type:nt(["number","integer"]),title:f().optional(),description:f().optional(),minimum:X().optional(),maximum:X().optional(),default:X().optional()}),EC=I({type:U("string"),title:f().optional(),description:f().optional(),enum:C(f()),default:f().optional()}),UC=I({type:U("string"),title:f().optional(),description:f().optional(),oneOf:C(I({const:f(),title:f()})),default:f().optional()}),OC=I({type:U("string"),title:f().optional(),description:f().optional(),enum:C(f()),enumNames:C(f()).optional(),default:f().optional()}),$C=fe([EC,UC]),zC=I({type:U("array"),title:f().optional(),description:f().optional(),minItems:X().optional(),maxItems:X().optional(),items:I({type:U("string"),enum:C(f())}),default:C(f()).optional()}),MC=I({type:U("array"),title:f().optional(),description:f().optional(),minItems:X().optional(),maxItems:X().optional(),items:I({anyOf:C(I({const:f(),title:f()}))}),default:C(f()).optional()}),qC=fe([zC,MC]),NC=fe([OC,$C,qC]),jC=fe([NC,AC,kC,TC]),DC=ko.extend({mode:U("form").optional(),message:f(),requestedSchema:I({type:U("object"),properties:de(f(),jC),required:C(f()).optional()})}),HC=ko.extend({mode:U("url"),message:f(),elicitationId:f(),url:f().url()}),LC=fe([DC,HC]),Iu=ke.extend({method:U("elicitation/create"),params:LC}),BC=dt.extend({elicitationId:f()}),GC=lt.extend({method:U("notifications/elicitation/complete"),params:BC}),pr=Te.extend({action:nt(["accept","decline","cancel"]),content:mc(e=>e===null?void 0:e,de(f(),fe([f(),X(),oe(),C(f())])).optional())}),VC=I({type:U("ref/resource"),uri:f()});var FC=I({type:U("ref/prompt"),name:f()}),ZC=ot.extend({ref:fe([FC,VC]),argument:I({name:f(),value:f()}),context:I({arguments:de(f(),f()).optional()}).optional()}),KC=ke.extend({method:U("completion/complete"),params:ZC});var Pu=Te.extend({completion:Ce({values:C(f()).max(100),total:ye(X().int()),hasMore:ye(oe())})}),JC=I({uri:f().startsWith("file://"),name:f().optional(),_meta:de(f(),we()).optional()}),WC=ke.extend({method:U("roots/list"),params:ot.optional()}),xu=Te.extend({roots:C(JC)}),YC=lt.extend({method:U("notifications/roots/list_changed"),params:dt.optional()}),qj=fe([fi,pi,KC,Ru,mu,lu,nu,au,cu,nC,aC,Mo,wu,gi,Si,_i,vi]),Nj=fe([li,hi,mi,YC,$o]),jj=fe([Lt,Hr,No,pr,xu,yi,wi,Bt]),Dj=fe([fi,Cu,Iu,WC,gi,Si,_i,vi]),Hj=fe([li,hi,wC,sC,du,bu,_u,$o,GC]),Lj=fe([Lt,tu,Pu,Su,pu,ou,iu,uu,lr,vu,yi,wi,Bt]),A=class e extends Error{static{o(this,"McpError")}constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===E.UrlElicitationRequired&&n){let a=n;if(a.elicitations)return new sr(a.elicitations,r)}return new e(t,r,n)}},sr=class extends A{static{o(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(E.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};ae();var Wf=Je,QC=u.object({mode:u.literal("auto")}).strict(),XC=u.object({mode:u.literal("manual"),clientId:u.string().trim().min(1),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:hc.default("client_secret_basic")}).strict().superRefine((e,t)=>{e.tokenEndpointAuthMethod!=="none"&&!e.clientSecret&&t.addIssue({code:u.ZodIssueCode.custom,message:`${e.tokenEndpointAuthMethod} requires clientSecret`,path:["clientSecret"]})}),Yf=u.discriminatedUnion("mode",[QC,XC]),eI=Yf.default({mode:"auto"}),Au=u.object({scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:eI}).strict(),Kf=Au.extend({redirectPath:u.string().startsWith("/auth/connections/")}).strict(),Qf=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),tI=new Set([...Qf,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),rI=u.object({kind:u.literal("bearer_token"),token:u.string().min(1)}).strict(),nI=u.object({kind:u.literal("headers"),headers:u.array(u.object({name:Ja,value:u.string().min(1)}).strict()).min(1)}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.headers.entries()){let i=a.name.toLowerCase();Qf.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Header ${a.name} is not allowed for static secret injection`,path:["headers",n,"name"]}),r.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Duplicate static secret header ${a.name}`,path:["headers",n,"name"]}),r.add(i)}}),ku=u.discriminatedUnion("kind",[rI,nI]),oI=u.object({kind:u.literal("basic_auth_app_password"),usernameLabel:u.string().min(1).default("Username"),passwordLabel:u.string().min(1).default("App password")}).strict(),aI=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key"),capture:u.enum(["browser_login"]).optional()}).strict(),Tu=u.discriminatedUnion("kind",[oI,aI]),Eu=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key")}).strict(),iI=u.discriminatedUnion("mode",[u.object({mode:u.literal("shared-oauth"),oauth:Kf}).strict(),u.object({mode:u.literal("user_oauth"),oauth:Kf}).strict(),u.object({mode:u.literal("static_secret"),secret:ku}).strict(),u.object({mode:u.literal("user-secret"),secret:Tu}).strict(),u.object({mode:u.literal("shared-secret"),secret:Eu}).strict()]),sI=u.object({baseUrl:u.url(),resourceMetadataUrl:u.url(),requestHeaders:u.array(gc).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let i=a.name.toLowerCase();tI.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Header ${a.name} is not allowed for native MCP transport request headers`,path:["requestHeaders",n,"name"]}),r.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Duplicate native MCP transport request header ${a.name}`,path:["requestHeaders",n,"name"]}),r.add(i)}}),Jj=u.object({displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:On.optional(),authProfiles:u.record(We,iI),transport:sI}).strict().superRefine((e,t)=>{Object.keys(e.authProfiles).length===0&&t.addIssue({code:u.ZodIssueCode.custom,message:"authProfiles must contain at least one profile",path:["authProfiles"]})}),cI=u.object({"shared-oauth":Au.optional(),user_oauth:Au.optional(),static_secret:u.object({secret:ku}).strict().optional(),"user-secret":u.object({secret:Tu}).strict().optional(),"shared-secret":u.object({secret:Eu}).strict().optional()}).strict().superRefine((e,t)=>{Object.values(e).every(r=>r===void 0)&&t.addIssue({code:u.ZodIssueCode.custom,message:"authProfiles must contain at least one upstream auth profile"})}),Jf=u.object({id:Wf,displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:On.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url(),requestHeaders:u.array(gc).default([]),authProfiles:cI}).strict(),uI=u.object({name:Ja,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict(),bi={id:Wf.optional(),displayName:u.string().min(1),summary:u.string().min(1).optional(),serverInfo:On.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url().optional(),requestHeaders:u.array(uI).default([])},dI=u.discriminatedUnion("authMode",[u.object({...bi,authMode:u.enum(["shared-oauth","user_oauth"]),scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:Yf.optional(),clientId:u.string().trim().min(1).optional(),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:hc.optional()}).strict(),u.object({...bi,authMode:u.literal("static_secret"),secret:ku}).strict(),u.object({...bi,authMode:u.literal("user-secret"),secret:Tu}).strict(),u.object({...bi,authMode:u.literal("shared-secret"),secret:Eu}).strict()]);function lI(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
37
+ `)}o(lI,"formatZodIssues");function Xf(e){throw new ue(e)}o(Xf,"throwGatewayConfigError");function pI(e){let t="mcp-upstream-";return e.startsWith(t)||Xf(`Upstream policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`),Je.parse(e.slice(t.length))}o(pI,"inferUpstreamConnectionIdFromPolicyName");function mI(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}o(mI,"buildDefaultProtectedResourceMetadataUrl");function zn(e,t){return We.parse(`${e}:${t}`)}o(zn,"buildUpstreamAuthProfileId");function Ri(e,t){try{let r=Jf.safeParse(e);if(r.success)return r.data;let n=dI.parse(e),a=n.id??(t===void 0?void 0:pI(t));a===void 0&&Xf("Upstream policy options must include id when policy name is unavailable.");let i=n.requestHeaders.map(c=>({name:c.name,value:c.value,required:c.required})),s=(()=>{switch(n.authMode){case"shared-oauth":case"user_oauth":{let c=n.clientRegistration??(n.clientId===void 0?{mode:"auto"}:{mode:"manual",clientId:n.clientId,...n.clientSecret===void 0?{}:{clientSecret:n.clientSecret},...n.tokenEndpointAuthMethod===void 0?{}:{tokenEndpointAuthMethod:n.tokenEndpointAuthMethod}});return{[n.authMode]:{scopes:n.scopes,scopeDelimiter:n.scopeDelimiter,clientRegistration:c}}}case"static_secret":case"user-secret":case"shared-secret":return{[n.authMode]:{secret:n.secret}}}})();return Jf.parse({id:a,displayName:n.displayName,...n.summary===void 0?{}:{description:n.summary},...n.serverInfo===void 0?{}:{serverInfo:n.serverInfo},mcpUrl:n.mcpUrl,protectedResourceMetadataUrl:n.protectedResourceMetadataUrl??mI(n.mcpUrl),requestHeaders:i,authProfiles:s})}catch(r){if(r instanceof ue)throw r;if(r instanceof u.ZodError){let n=t===void 0?"MCP upstream policy":`Policy "${t}"`;throw new ue(`${n} is misconfigured. Missing/invalid options in policies.json:
38
+ ${lI(r)}`,{cause:r})}throw r}}o(Ri,"parseUpstreamConnectionPolicyOptions");function eh(e){return e.mode==="shared-oauth"||e.mode==="user_oauth"}o(eh,"isUpstreamOAuthAuthConfig");ae();var fI=u.looseObject({name:u.string().min(1),version:u.string().min(1).optional()}),hI=u.looseObject({}),gI=u.looseObject({name:ar,namespace:ar.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional(),inputSchema:hI}),yI=u.looseObject({name:ar,namespace:ar.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional()}),SI=u.looseObject({name:ar,uri:u.string().min(1),upstreamPolicy:u.string().min(1).optional(),upstreamUri:u.string().min(1).optional(),enabled:u.boolean().optional()}),_I=u.enum(["openapi","upstream_mcp"]),wI=u.object({catalogSource:_I.default("openapi"),serverInfo:fI.optional(),tools:u.array(gI).default([]),prompts:u.array(yI).default([]),resources:u.array(SI).default([])}).strict();function vI(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
39
+ `)}o(vI,"formatZodIssues");function th(e,t){try{return wI.parse(e??{})}catch(r){if(r instanceof u.ZodError){let n=t===void 0?"MCP virtual server route":`MCP virtual server route ${t}`;throw new ue(`${n} is misconfigured. Missing/invalid handler options in routes.oas.json:
40
+ ${vI(r)}`,{cause:r})}throw r}}o(th,"parseVirtualServerRouteOptions");function Ci(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Ci,"toMcpTool");function Ii(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Ii,"toMcpPrompt");function Pi(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o(Pi,"toMcpResource");var bI="mcp-upstream-connection-inbound",rh="/mcp/";function Be(e){throw new ue(e)}o(Be,"throwRegistryError");function RI(e){return e.policyType===bI}o(RI,"isUpstreamConnectionPolicy");function CI(e){return Ao(e.policyType)}o(CI,"isMcpOAuthInboundPolicy");function II(e){return e instanceof ue?e:new ue(e instanceof Error?e.message:"MCP virtual server route is misconfigured.",e instanceof Error?{cause:e}:void 0)}o(II,"toRouteConfigurationError");function PI(e){e.startsWith(rh)||Be(`MCP virtual server route ${e} must use a /mcp/{virtualServerId} path.`);let t=e.slice(rh.length);return(!t||t.includes("/"))&&Be(`MCP virtual server route ${e} must use exactly one /mcp/{virtualServerId} path segment.`),xe.parse(t)}o(PI,"readVirtualServerIdFromPath");function xI(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&Be(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&Be(`Upstream policy ${e.policyName} does not declare an auth mode.`),Ka.parse(r)}o(xI,"readSingleAuthMode");function AI(e){let t=e.connection.authProfiles[e.authMode];t||Be(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=`/auth/connections/${encodeURIComponent(e.connection.id)}/callback`;switch(e.authMode){case"shared-oauth":case"user_oauth":{let n=t;return{mode:e.authMode,oauth:{scopes:n.scopes,scopeDelimiter:n.scopeDelimiter,redirectPath:r,clientRegistration:n.clientRegistration}}}case"static_secret":return{mode:"static_secret",secret:t.secret};case"user-secret":return{mode:"user-secret",secret:t.secret};case"shared-secret":return{mode:"shared-secret",secret:t.secret}}}o(AI,"buildResolvedAuthConfig");function kI(e){let t=xI({policyName:e.policyName,connection:e.connection}),r=zn(e.connection.id,t),n=AI({connection:e.connection,authMode:t,authProfileId:r}),a={displayName:e.connection.displayName,...e.connection.description===void 0?{}:{description:e.connection.description},...e.connection.serverInfo===void 0?{}:{serverInfo:e.connection.serverInfo},authProfiles:{[r]:n},transport:{baseUrl:e.connection.mcpUrl,resourceMetadataUrl:e.connection.protectedResourceMetadataUrl,requestHeaders:e.connection.requestHeaders}};return{policyName:e.policyName,upstreamServerId:e.connection.id,config:a,authMode:t,authProfileId:r,authConfig:n}}o(kI,"buildRegisteredConnection");function TI(e){let t=new Map;for(let r of e)t.has(r.name)&&Be(`Duplicate policy name ${r.name} in policies.json.`),t.set(r.name,{name:r.name,policyType:r.policyType,handler:{options:r.handler.options}});return t}o(TI,"buildPolicyMap");function EI(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(EI,"readOperationId");function nh(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`;try{return ar.parse(t)}catch{Be(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`)}}o(nh,"buildPublishedCapabilityName");function $u(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||Be(`MCP virtual server route ${e.routePath} declares capability ${e.capabilityName} for upstream policy ${e.authoredPolicyName}, but that policy is not bound to the route.`),e.authoredPolicyName;if(e.connections.length===1)return e.connections[0]?.policyName;Be(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o($u,"readCapabilityUpstreamPolicy");function Uu(e){e.seen.has(e.key)&&Be(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(Uu,"assertUniqueCatalogKey");function UI(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=nh({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:$u({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(UI,"normalizeCatalogTool");function OI(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=nh({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:$u({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(OI,"normalizeCatalogPrompt");function $I(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:$u({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o($I,"normalizeCatalogResource");function zI(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>UI({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>OI({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>$I({resource:d,connections:e.connections,routePath:e.routePath})),i=new Set;for(let d of r)Uu({kind:"tool",key:d.name,routePath:e.routePath,seen:i});let s=new Set;for(let d of n)Uu({kind:"prompt",key:d.name,routePath:e.routePath,seen:s});let c=new Set;for(let d of a)Uu({kind:"resource",key:String(d.uri),routePath:e.routePath,seen:c});return{catalogSource:t,...e.catalog.serverInfo===void 0?{}:{serverInfo:e.catalog.serverInfo},tools:r,prompts:n,resources:a}}o(zI,"normalizeVirtualServerCatalog");function MI(e){let t=new Map,r=new Map,n=new Map,a=new Set,i=new Set;function s(c){let d=n.get(c.name);if(d)return d;let p=Ri(c.handler.options,c.name);a.has(p.id)&&Be(`Duplicate upstream MCP connection id ${p.id} in policies.json.`),a.add(p.id);let l=kI({policyName:c.name,connection:p});return n.set(c.name,l),l}o(s,"readConnectionForPolicy");for(let c of e.routes){let d=c.policies?.inbound??[];if(d.length===0)continue;let p=d[0],l=p===void 0?void 0:e.policyByName.get(p);if(!l||!CI(l))continue;let m=EI(c),h;try{h=PI(c.path),m||Be(`MCP virtual server route ${c.path} must declare an operationId in routes.oas.json.`),i.has(m)&&Be(`Duplicate MCP virtual server operationId ${m} across routes.`),t.has(h)&&Be(`Duplicate MCP virtual server id ${h} across routes.`);let y=[];for(let w of d.slice(1)){let v=e.policyByName.get(w);!v||!RI(v)||y.push(s(v))}let _=th(c.handler.options,c.path),S=zI({catalog:_,connections:y,routePath:c.path});S.catalogSource==="upstream_mcp"&&y.length!==1&&Be(`MCP virtual server route ${c.path} uses upstream MCP catalog mode but declares ${y.length} upstream bindings; upstream MCP catalog mode requires exactly one upstream binding.`),t.set(h,{virtualServerId:h,operationId:m,routePath:c.path,handlerExport:c.handler.export,serverInfo:S.serverInfo,catalog:S,connections:y}),i.add(m)}catch(y){h!==void 0&&r.set(h,II(y))}}return{byVirtualServerId:t,virtualServerErrorsById:r,connectionsByPolicyName:n}}o(MI,"buildVirtualServers");function zu(e){let t=TI(e.policies),{byVirtualServerId:r,virtualServerErrorsById:n,connectionsByPolicyName:a}=MI({routes:e.routes,policyByName:t}),i=new Map;for(let s of a.values())i.set(s.upstreamServerId,s);return{byVirtualServerId:r,connectionsById:i,virtualServerErrorsById:n}}o(zu,"buildGatewayConnectionRegistry");var Lr,Ou;function oh(e){Ou=e,Lr=void 0}o(oh,"configureGatewayConnectionRegistrySource");function ah(e){Lr=e}o(ah,"setGatewayConnectionRegistry");function St(){if(!Lr&&Ou&&(Lr=zu(Ou)),!Lr)throw g("internal_server_error","MCP gateway connection registry has not been initialized. Ensure routes.oas.json declares at least one MCP virtual server route and policies.json registers an `mcp-oauth-inbound` (or wrapper) policy.");return Lr}o(St,"getGatewayConnectionRegistry");function qr(e){let t=St(),r=t.virtualServerErrorsById?.get(e);if(r)throw r;let n=t.byVirtualServerId.get(e);if(!n)throw g("unknown_virtual_server",`Unknown MCP virtual server: ${e}`);return n}o(qr,"getRegisteredVirtualServer");function ih(){return Lr}o(ih,"tryGetGatewayConnectionRegistry");function je(e){let t=St().connectionsById.get(e);if(!t)throw g("unknown_upstream_server",`Unknown upstream server: ${e}`);return t.config}o(je,"getUpstreamServerConfig");function qI(e){let t=St().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw g("unknown_auth_profile",`Unknown auth profile ${String(e.authProfileId)} for upstream server ${e.upstreamServerId}.`);return t.authProfileId}o(qI,"resolveUpstreamAuthProfileId");function mr(e){qI(e);let t=St().connectionsById.get(e.upstreamServerId);if(!t)throw g("unknown_auth_profile",`Auth profile could not be resolved for upstream server ${e.upstreamServerId}.`);return t.authConfig}o(mr,"getUpstreamAuthConfig");function Br(e,t){let r=mr({upstreamServerId:e,authProfileId:t});if(!eh(r))throw g("invalid_request",`Upstream server ${e} does not use upstream OAuth.`);return r.oauth}o(Br,"requireUpstreamOAuthConfig");function NI(){let e=uc.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP;return typeof e=="string"&&e==="1"}o(NI,"isTestOnlyAllowHttpLoopbackIdpEnabled");var jI=new Set(["undefined","null","nan"]);function qu(e,t){if(!e.hostname)throw g("invalid_request",`Outbound URL has an empty hostname (got ${JSON.stringify(t)}). This typically indicates an unset $env(...) reference or a JS template literal coercing \`undefined\` into a URL. Check the policy options or runtime config that produced this URL.`);if(jI.has(e.hostname.toLowerCase()))throw g("invalid_request",`Outbound URL hostname is ${JSON.stringify(e.hostname)} (from ${JSON.stringify(t)}). This almost always means an environment variable referenced by $env(...) is unset and a JS value was string-coerced into a URL. Set the missing env var or fix the policy option that produced this URL.`)}o(qu,"assertSafeOutboundHostname");var DI=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),HI=[{first:0},{first:10},{first:127},{first:169,secondMin:254,secondMax:254},{first:172,secondMin:16,secondMax:31},{first:192,secondMin:168,secondMax:168},{first:100,secondMin:64,secondMax:127},{first:224,firstMax:239},{first:240,firstMax:255}];function sh(e){if(!/^\d+\.\d+\.\d+\.\d+$/.test(e))return;let t=e.split(".").map(r=>Number(r));if(!(t.length!==4||t.some(r=>Number.isNaN(r)||r<0||r>255)))return t}o(sh,"parseIpv4Octets");function LI([e,t],r){let n=r.firstMax??r.first;return e<r.first||e>n?!1:r.secondMin===void 0||r.secondMax===void 0?!0:t>=r.secondMin&&t<=r.secondMax}o(LI,"ipv4RangeMatches");function ch(e){let t=sh(e);return t!==void 0&&HI.some(r=>LI(t,r))}o(ch,"isPrivateIpv4");function Mu(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}o(Mu,"parseIpv6Word");function BI(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(BI,"formatIpv4FromWords");function GI(e){let t=e.slice(7),r=sh(t);if(r!==void 0)return r.join(".");let[n,a,i]=t.split(":"),s=Mu(n),c=Mu(a);return i===void 0&&s!==void 0&&c!==void 0?BI(s,c):void 0}o(GI,"parseIpv6MappedIpv4");function VI(e){return Mu(e.split(":").find(Boolean))}o(VI,"readFirstIpv6Hextet");function FI(e){let t=jt(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=GI(t);return n===void 0||ch(n)}let r=VI(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(FI,"isPrivateIpv6");function Nu(e){let t=jt(e);return DI.has(t)||t.endsWith(".internal")||ch(t)||FI(t)}o(Nu,"isBlockedOutboundHostname");function uh(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw g("invalid_request",`Unsupported outbound protocol: ${t.protocol}`);qu(t,e);let r=qe(t);if(t.protocol==="http:"&&!r)throw g("invalid_request","Configured outbound HTTP URLs must target loopback hosts.");let n=jt(t.hostname);if(!r&&Nu(n))throw g("invalid_request",`Blocked outbound host: ${n}`);return t}o(uh,"validateConfiguredOutboundUrl");function dh(e){let t=new URL(e),r=qe(t),n=r&&NI();if(t.protocol!=="https:"&&!n)throw g("invalid_request","Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw g("invalid_request","Identity provider URLs must not include credentials, query params, or fragments.");qu(t,e);let a=jt(t.hostname);if(!r&&Nu(a))throw g("invalid_request",`Blocked identity provider host: ${a}`);return t}o(dh,"validateIdentityProviderUrl");function xi(e){let t=new URL(e);if(t.protocol!=="https:"||t.pathname==="/"||t.username||t.password||t.search||t.hash)throw g("invalid_request","CIMD client_id must be an HTTPS URL with a path and no credentials, query, or fragment.");if(qu(t,e),Nu(t.hostname))throw g("invalid_request","CIMD client_id points at a blocked host.");return t}o(xi,"validateCimdClientMetadataUrl");function lh(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=o(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}o(lh,"mergeAbortSignals");async function ZI(e){try{await e.cancel()}catch{}}o(ZI,"cancelReader");async function Ai(e,t){if(!e)return new Uint8Array;let r=e.getReader(),n=[],a=0,i=await r.read();for(;!i.done;){let d=i.value;if(a+=d.byteLength,a>t.maxBytes)throw await ZI(r),t.createLimitError();n.push(d),i=await r.read()}let s=new Uint8Array(a),c=0;for(let d of n)s.set(d,c),c+=d.byteLength;return s}o(Ai,"readBoundedByteStream");var KI=2,JI=1024*1024,WI=1e4,YI=new Set([301,302,303,307,308]),QI=["authorization","proxy-authorization","cookie","cookie2"];function ju(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(ju,"readRequestUrl");function Mn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Mn,"readRequestMethod");function XI(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g(r,"Outbound response exceeded the maximum allowed size.")}o(XI,"assertContentLengthWithinLimit");async function eP(e,t,r){return XI(e,t,r),Ai(e.body,{maxBytes:t,createLimitError:o(()=>g(r,"Outbound response exceeded the maximum allowed size."),"createLimitError")})}o(eP,"readBoundedResponseBody");function tP(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}o(tP,"responseFromBufferedBody");function rP(e,t){if(!YI.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(rP,"resolveRedirectUrl");function ph(e,t){try{return t.validateUrl(e)}catch(r){throw g(t.problemCode,"Outbound URL was not allowed.",r)}}o(ph,"validateOutboundUrl");function nP(e,t){throw ge(e)!==void 0?e:g(t,"Outbound fetch failed.",e)}o(nP,"normalizeFetchError");function jo(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,a]of Object.entries(t.extra))a!==void 0&&(r[n]=a);t.error!==void 0&&Ye(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(jo,"logOutboundFailure");async function oP(e,t,r,n,a,i,s){let c=Mn(r,n);try{return await t(r,n)}catch(d){let p=d instanceof DOMException&&d.name==="AbortError";jo(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:c,host:ct(i),error:d,extra:{abortReason:s()}}),nP(d,a)}}o(oP,"fetchWithNormalizedError");function aP(e){if(e.redirects>=e.maxRedirects)throw g(e.problemCode,"Outbound redirects exceeded the maximum allowed depth.");if(e.method!=="GET"&&e.method!=="HEAD")throw g(e.problemCode,"Outbound redirect after a non-idempotent request was blocked.")}o(aP,"assertRedirectAllowed");function iP(e,t){let r=new Headers(e);for(let n of QI)r.delete(n);for(let n of t)r.delete(n);return r}o(iP,"stripCrossOriginHeaders");function sP(e,t,r,n,a){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=iP(e.headers,a)),i}o(sP,"buildRedirectInit");function cP(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(cP,"buildInitialRequestInit");function uP(e){let t=Mn(e.currentInput,e.currentInit);aP({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ph(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),n=new URL(e.currentUrl),a=r.origin!==n.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:sP(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(uP,"followRedirect");async function Du(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??KI,i=r.maxResponseBytes??JI,s=r.timeoutMs??WI,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],p=r.context,l=new AbortController,m=lh(l,t.signal),h=!1,y=setTimeout(()=>{h=!0,l.abort()},s),_=e,S=cP(e,t,l.signal),w;try{w=ph(ju(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(b){throw jo(p,{event:"outbound_url_blocked",problemCode:n,method:Mn(e,t),host:ct(ju(e)),error:b}),clearTimeout(y),m?.(),b}let v=0;try{for(;;){let b=await oP(p,c,_,S,n,w,()=>h?`timeout_after_${s}ms`:void 0),R=rP(b,w);if(R!==void 0)try{let M=uP({currentInput:_,currentInit:S,currentUrl:w,redirectUrl:R,redirects:v,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:l.signal,additionalCrossOriginStrippedHeaders:d});_=M.currentInput,S=M.currentInit,w=M.currentUrl,v=M.redirects;continue}catch(M){throw jo(p,{event:"outbound_redirect_blocked",problemCode:n,method:Mn(_,S),host:ct(w),error:M,extra:{redirects:v,maxRedirects:a,redirectTargetHost:ct(R)}}),M}try{return tP(b,await eP(b,i,n))}catch(M){throw jo(p,{event:"outbound_response_size_exceeded",problemCode:n,method:Mn(_,S),host:ct(w),error:M,extra:{maxResponseBytes:i,status:b.status}}),M}}}finally{clearTimeout(y),m?.()}}o(Du,"runSafeOutboundExchange");async function Hu(e,t,r){let n=await Du(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw jo(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Mn(e,t),host:ct(ju(e)),error:a,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),g(r.problemCode??"invalid_request","Outbound JSON response could not be parsed.",a)}}o(Hu,"runSafeOutboundJsonExchange");function qn(e,t={},r={}){return Du(e,t,{...r,validateUrl:uh})}o(qn,"fetchConfiguredOutbound");function mh(e,t={},r={}){return Hu(e,t,{...r,validateUrl:dh})}o(mh,"fetchIdentityProviderJson");function fh(e,t={},r={}){return Hu(e,t,{...r,validateUrl:xi})}o(fh,"fetchCimdClientMetadataJson");var dP={"shared-oauth":{authMode:"shared-oauth",ownerMode:"shared",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},user_oauth:{authMode:"user_oauth",ownerMode:"user",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},static_secret:{authMode:"static_secret",ownerMode:"none",connectSupport:"none",connectUnsupportedDetail:"Static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"configured_static_secret"},"shared-secret":{authMode:"shared-secret",ownerMode:"shared",connectSupport:"none",connectUnsupportedDetail:"Shared static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"shared_secret_connection"},"user-secret":{authMode:"user-secret",ownerMode:"user",connectSupport:"user_secret_capture",connectUnsupportedDetail:void 0,callbackSupport:"none",credentialAcquisition:"user_secret_connection"}};function xt(e){return dP[e]}o(xt,"describeUpstreamAuthMode");function ki(e){return xt(e).ownerMode}o(ki,"resolveOwnerModeForUpstreamAuthMode");ae();import{errors as bh,jwtVerify as Rh,SignJWT as Ch}from"jose";import{base64url as lP}from"jose";var pP=new TextEncoder,mP="MCP gateway could not initialize secure key material.",fP=32,hh=new Map,gh=new Map,hP;function gP(){return hP??So.instance.authPrivateKey}o(gP,"readAuthPrivateKey");function yh(e){return new _n(mP,e===void 0?void 0:{cause:e})}o(yh,"createGeneratedKeyMaterialError");function Sh(e,t){let r=lP.decode(t);if(r.byteLength!==fP)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(Sh,"decodeJwkKeyField");function yP(e){let t=gP();if(!t)throw yh();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let n=Sh("d",r.d);Sh("x",r.x);let a=pP.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(a.byteLength+n.byteLength);return i.set(a),i.set(n,a.byteLength),i}catch(r){throw yh(r)}}o(yP,"decodeGeneratedKeyMaterial");function SP(e){let t=hh.get(e);return t||(t=yP(e),hh.set(e,t)),t}o(SP,"getMasterKeyMaterial");async function At(e){let t=gh.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(SP(e.keyMaterialPurpose));return gh.set(e.purpose,r),r}o(At,"readCachedDerivedKey");var _P="SHA-256";var wP="zuplo-mcp-gateway:",vP=new TextEncoder,_h=new WeakMap;async function fr(e,t){let r=_h.get(e);r||(r=new Map,_h.set(e,r));let n=r.get(t);if(n)return n;let a=await bP(e,t);return r.set(t,a),a}o(fr,"deriveGatewaySigningKey");async function bP(e,t){let r=wh(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=vP.encode(`${wP}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:_P,salt:new Uint8Array,info:wh(a)},n,32*8);return new Uint8Array(i)}o(bP,"hkdfExpand");function wh(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(wh,"copyToArrayBuffer");var Ti="HS256",Ih=15*60,RP=15*60,Ei="zuplo-mcp-gateway",Ui="zuplo-mcp-gateway",CP=xm.extend({id:An}),IP=CP.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),Ph=Pn.extend({id:Po,purpose:u.literal("browser_connect")}),PP=Pn.extend({purpose:u.literal("browser_connect")}),xP=Ph.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),xh=Ih*1e3;async function Ah(){return At({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>fr(e,"oauth-state"),"derive")})}o(Ah,"getOAuthStateKey");async function kh(){return At({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>fr(e,"browser-connect"),"derive")})}o(kh,"getBrowserConnectKey");async function Th(e){let t=Math.floor(Date.now()/1e3)+Ih;return new Ch(e).setProtectedHeader({alg:Ti,typ:"JWT"}).setIssuer(Ei).setAudience(Ui).setIssuedAt().setExpirationTime(t).sign(await Ah())}o(Th,"signOAuthState");async function Oi(e){try{let{payload:t}=await Rh(e,await Ah(),{algorithms:[Ti],issuer:Ei,audience:Ui});return IP.parse(t)}catch(t){throw t instanceof bh.JWTExpired?g("oauth_state_expired","OAuth state has expired",t):g("oauth_state_invalid","OAuth state could not be verified",t)}}o(Oi,"verifyOAuthState");async function Eh(e){let t=Math.floor(Date.now()/1e3)+RP,r=PP.parse(e),n=Ph.parse({...r,id:Um()});return new Ch(n).setProtectedHeader({alg:Ti,typ:"JWT"}).setIssuer(Ei).setAudience(Ui).setIssuedAt().setExpirationTime(t).sign(await kh())}o(Eh,"signBrowserConnectTicket");async function $i(e){try{let{payload:t}=await Rh(e,await kh(),{algorithms:[Ti],issuer:Ei,audience:Ui});return xP.parse(t)}catch(t){throw t instanceof bh.JWTExpired?g("oauth_state_expired","Browser connect ticket has expired",t):g("oauth_state_invalid","Browser connect ticket could not be verified",t)}}o($i,"verifyBrowserConnectTicket");async function zi(e){if((await K().consumeBrowserConnectTicket({id:e.id,expiresAt:re(new Date(e.exp*1e3)),now:re(new Date)})).kind==="consumed")throw g("oauth_state_reused","Browser connect ticket has already been used")}o(zi,"consumeBrowserConnectTicket");function AP(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}o(AP,"buildConnectRequiredMessage");async function Uh(e){let t=ie(e.requestUrl),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("virtualServerId",e.virtualServerId),r.searchParams.set("browserTicket",await Eh({...Io(e),purpose:"browser_connect"})),r.toString()}o(Uh,"buildGatewayBrowserTicketUrl");function kP(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(kP,"buildGatewayConnectPath");async function Lu(e){return Uh({...e,path:kP(e.upstreamServerId),redirect:!0})}o(Lu,"buildGatewayConnectUrl");async function Oh(e){return Uh({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(Oh,"buildGatewayAppPasswordCaptureUrl");async function Nn(e){let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Lu(t),message:AP(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Nn,"buildRedirectConnectRequiredResponse");function $h(e){return zh({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}o($h,"buildAdminConnectRequiredResponse");function zh(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}o(zh,"buildAdminSetupRequiredResponse");function Mh(e){return zh({...e,message:e.requiresReconsent?`An administrator must replace the ${e.upstreamDisplayName} static credential before this tool can be used.`:`An administrator must configure the ${e.upstreamDisplayName} static credential before this tool can be used.`})}o(Mh,"buildAdminStaticSecretRequiredResponse");ae();import{base64url as hr}from"jose";var TP="SHA-256",Dn="AES-GCM",EP=12,Gu="zuplo-secret",Vu=1,qh="generated:auth_private_key:token-encryption",UP=u.object({version:u.literal(Vu),keyId:u.literal(qh),algorithm:u.literal(Dn),iv:u.string().min(1),ciphertext:u.string().min(1)}).strict();function jn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(jn,"copyToArrayBuffer");async function Bu(){return At({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(TP,jn(e));return crypto.subtle.importKey("raw",t,{name:Dn},!1,["encrypt","decrypt"])},"derive")})}o(Bu,"getEncryptionKey");function Nh(e){return jn(new TextEncoder().encode(`${Gu}:v${e.version}:${e.keyId}`))}o(Nh,"getAssociatedData");function OP(e){return`${Gu}:v${e.version}:${hr.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(OP,"encodeEnvelope");function $P(e){let t=`${Gu}:v${Vu}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(hr.decode(r));return UP.parse(JSON.parse(n))}o($P,"decodeEnvelope");async function Gr(e){let t=await Bu(),r=crypto.getRandomValues(new Uint8Array(EP)),n={version:Vu,keyId:qh},a=await crypto.subtle.encrypt({name:Dn,iv:r,additionalData:Nh(n)},t,new TextEncoder().encode(e));return OP({...n,algorithm:Dn,iv:hr.encode(r),ciphertext:hr.encode(new Uint8Array(a))})}o(Gr,"encryptSecret");async function Gt(e){let t=$P(e);if(t){let s=await Bu(),c=await crypto.subtle.decrypt({name:Dn,iv:jn(hr.decode(t.iv)),additionalData:Nh(t)},s,jn(hr.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw g("internal_server_error","Encrypted payload is malformed");let a=await Bu(),i=await crypto.subtle.decrypt({name:Dn,iv:jn(hr.decode(r))},a,jn(hr.decode(n)));return new TextDecoder().decode(i)}o(Gt,"decryptSecret");function zP(e,t){let r=mr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-secret")throw g("invalid_request",`Upstream server ${e} does not use tenant static credentials.`);return r.secret}o(zP,"requireTenantStaticSecretConfig");function jh(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(jh,"hasUsableTenantStaticSecret");async function MP(e){if(!jh(e.connection))throw g("internal_server_error","Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await Gt(e.connection.metadata.encryptedStaticSecret)}}o(MP,"resolveTenantStaticSecretCredential");async function Dh(e){let t=je(e.upstreamServerId);zP(e.upstreamServerId,e.authProfileId);let r="preloadedConnection"in e?e.preloadedConnection:(await K().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(jh(r))return{kind:"authorized",credential:await MP({connection:r})};let n={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:t.displayName,virtualServerId:e.virtualServerId,requiresReconsent:!!r};return r!==void 0&&(n.connectionId=r.id),{kind:"connect_required",payload:Mh(n)}}o(Dh,"resolveTenantStaticSecretCredentialForRequest");ae();async function Fu(e){return K().upsertUpstreamConnection({id:ai(),ownerMode:e.owner.mode,subjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,status:"active",encryptedAccessToken:void 0,encryptedRefreshToken:void 0,scopes:[],expiresAt:void 0,metadata:e.metadata})}o(Fu,"upsertStaticSecretConnection");var qP=u.string().trim().min(1).max(320),NP=u.string().min(1).max(4096),jP=u.string().trim().min(1).max(4096);function Zu(e,t){let r=mr({upstreamServerId:e,authProfileId:t});if(r.mode!=="user-secret")throw g("invalid_request",`Upstream server ${e} does not use user static credentials.`);return r.secret}o(Zu,"requireUserStaticSecretConfig");function DP(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o(DP,"encodeBase64Utf8");function HP(e){return`Basic ${DP(`${e.username}:${e.appPassword}`)}`}o(HP,"buildBasicAuthHeader");function Hh(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(Hh,"hasEncryptedUserStaticSecret");async function LP(e){if(!Hh(e.connection))throw g("internal_server_error","Stored user static credential is incomplete.");if(e.connection.metadata.staticSecretKind==="bearer_token")return{type:"bearer_token",token:await Gt(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:HP({username:e.connection.metadata.staticSecretUsername,appPassword:await Gt(e.connection.metadata.encryptedStaticSecret)})}};throw g("internal_server_error","Stored user static credential kind is unsupported.")}o(LP,"resolveUserStaticSecretCredential");async function Lh(e){if(Zu(e.upstreamServerId,e.authProfileId).kind!=="basic_auth_app_password")throw g("invalid_request","This upstream does not use username and app-password credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=qP.parse(e.username),n=NP.parse(e.appPassword);return Fu({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Gr(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(Lh,"saveUserStaticSecretCredential");async function Mi(e){let t=Zu(e.upstreamServerId,e.authProfileId);if(t.kind!=="bearer_token")throw g("invalid_request","This upstream does not use bearer token credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=jP.parse(e.token);return Fu({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Gr(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(Mi,"saveUserStaticBearerTokenCredential");function Ku(e,t){return Zu(e,t)}o(Ku,"readUserStaticSecretCaptureConfig");async function Bh(e){let t=je(e.upstreamServerId);if(e.owner.mode!=="user")throw g("internal_server_error","User static credential flow resolved a non-user owner.");let r="preloadedConnection"in e?e.preloadedConnection:(await K().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(Hh(r))return{kind:"authorized",credential:await LP({connection:r})};let n={requestUrl:e.request.url,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:t.displayName,virtualServerId:e.virtualServerId,subject:"tool",requiresReconsent:!!r};return r!==void 0&&(n.connectionId=r.id),{kind:"connect_required",payload:await Nn(n)}}o(Bh,"resolveUserStaticSecretCredentialForRequest");function Gh(e){if(e.owner.mode!=="user")throw g("invalid_request","User static credential capture requires a user-owned connection.");return Oh({requestUrl:e.request.url,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}})}o(Gh,"buildUserStaticSecretConnectUrl");var Ju;Ju=globalThis.crypto;async function BP(e){return(await Ju).getRandomValues(new Uint8Array(e))}o(BP,"getRandomValues");async function GP(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await BP(e-n.length);for(let i of a)i<r&&(n+=t[i%t.length])}return n}o(GP,"random");async function VP(e){return await GP(e)}o(VP,"generateVerifier");async function FP(e){let t=await(await Ju).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(FP,"generateChallenge");async function Wu(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await VP(e),r=await FP(t);return{code_verifier:t,code_challenge:r}}o(Wu,"pkceChallenge");ae();var Ee=Jp().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Xp.custom,message:"URL must be parseable",fatal:!0}),Zp}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),qi=Ce({resource:f().url(),authorization_servers:C(Ee).optional(),jwks_uri:f().url().optional(),scopes_supported:C(f()).optional(),bearer_methods_supported:C(f()).optional(),resource_signing_alg_values_supported:C(f()).optional(),resource_name:f().optional(),resource_documentation:f().optional(),resource_policy_uri:f().url().optional(),resource_tos_uri:f().url().optional(),tls_client_certificate_bound_access_tokens:oe().optional(),authorization_details_types_supported:C(f()).optional(),dpop_signing_alg_values_supported:C(f()).optional(),dpop_bound_access_tokens_required:oe().optional()}),Do=Ce({issuer:f(),authorization_endpoint:Ee,token_endpoint:Ee,registration_endpoint:Ee.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),service_documentation:Ee.optional(),revocation_endpoint:Ee.optional(),revocation_endpoint_auth_methods_supported:C(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:C(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(f()).optional(),code_challenge_methods_supported:C(f()).optional(),client_id_metadata_document_supported:oe().optional()}),ZP=Ce({issuer:f(),authorization_endpoint:Ee,token_endpoint:Ee,userinfo_endpoint:Ee.optional(),jwks_uri:Ee,registration_endpoint:Ee.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),acr_values_supported:C(f()).optional(),subject_types_supported:C(f()),id_token_signing_alg_values_supported:C(f()),id_token_encryption_alg_values_supported:C(f()).optional(),id_token_encryption_enc_values_supported:C(f()).optional(),userinfo_signing_alg_values_supported:C(f()).optional(),userinfo_encryption_alg_values_supported:C(f()).optional(),userinfo_encryption_enc_values_supported:C(f()).optional(),request_object_signing_alg_values_supported:C(f()).optional(),request_object_encryption_alg_values_supported:C(f()).optional(),request_object_encryption_enc_values_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),display_values_supported:C(f()).optional(),claim_types_supported:C(f()).optional(),claims_supported:C(f()).optional(),service_documentation:f().optional(),claims_locales_supported:C(f()).optional(),ui_locales_supported:C(f()).optional(),claims_parameter_supported:oe().optional(),request_parameter_supported:oe().optional(),request_uri_parameter_supported:oe().optional(),require_request_uri_registration:oe().optional(),op_policy_uri:Ee.optional(),op_tos_uri:Ee.optional(),client_id_metadata_document_supported:oe().optional()}),Ni=I({...ZP.shape,...Do.pick({code_challenge_methods_supported:!0}).shape}),Ho=I({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:em.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),Fh=I({error:f(),error_description:f().optional(),error_uri:f().optional()}),Vh=Ee.optional().or(U("").transform(()=>{})),KP=I({redirect_uris:C(Ee),token_endpoint_auth_method:f().optional(),grant_types:C(f()).optional(),response_types:C(f()).optional(),client_name:f().optional(),client_uri:Ee.optional(),logo_uri:Vh,scope:f().optional(),contacts:C(f()).optional(),tos_uri:Vh,policy_uri:f().optional(),jwks_uri:Ee.optional(),jwks:Yp().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),Yu=I({client_id:f(),client_secret:f().optional(),client_id_issued_at:X().optional(),client_secret_expires_at:X().optional()}).strip(),Lo=KP.merge(Yu),OH=I({error:f(),error_description:f().optional()}).strip(),$H=I({token:f(),token_type_hint:f().optional()}).strip();function Zh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(Zh,"resourceUrlFromServerUrl");function Kh({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return a.startsWith(i)}o(Kh,"checkResourceAllowed");var be=class extends Error{static{o(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},Bo=class extends be{static{o(this,"InvalidRequestError")}};Bo.errorCode="invalid_request";var Vr=class extends be{static{o(this,"InvalidClientError")}};Vr.errorCode="invalid_client";var Fr=class extends be{static{o(this,"InvalidGrantError")}};Fr.errorCode="invalid_grant";var Zr=class extends be{static{o(this,"UnauthorizedClientError")}};Zr.errorCode="unauthorized_client";var Go=class extends be{static{o(this,"UnsupportedGrantTypeError")}};Go.errorCode="unsupported_grant_type";var Vo=class extends be{static{o(this,"InvalidScopeError")}};Vo.errorCode="invalid_scope";var Fo=class extends be{static{o(this,"AccessDeniedError")}};Fo.errorCode="access_denied";var Vt=class extends be{static{o(this,"ServerError")}};Vt.errorCode="server_error";var Zo=class extends be{static{o(this,"TemporarilyUnavailableError")}};Zo.errorCode="temporarily_unavailable";var Ko=class extends be{static{o(this,"UnsupportedResponseTypeError")}};Ko.errorCode="unsupported_response_type";var Jo=class extends be{static{o(this,"UnsupportedTokenTypeError")}};Jo.errorCode="unsupported_token_type";var Wo=class extends be{static{o(this,"InvalidTokenError")}};Wo.errorCode="invalid_token";var Yo=class extends be{static{o(this,"MethodNotAllowedError")}};Yo.errorCode="method_not_allowed";var Qo=class extends be{static{o(this,"TooManyRequestsError")}};Qo.errorCode="too_many_requests";var Kr=class extends be{static{o(this,"InvalidClientMetadataError")}};Kr.errorCode="invalid_client_metadata";var Xo=class extends be{static{o(this,"InsufficientScopeError")}};Xo.errorCode="insufficient_scope";var ea=class extends be{static{o(this,"InvalidTargetError")}};ea.errorCode="invalid_target";var Jh={[Bo.errorCode]:Bo,[Vr.errorCode]:Vr,[Fr.errorCode]:Fr,[Zr.errorCode]:Zr,[Go.errorCode]:Go,[Vo.errorCode]:Vo,[Fo.errorCode]:Fo,[Vt.errorCode]:Vt,[Zo.errorCode]:Zo,[Ko.errorCode]:Ko,[Jo.errorCode]:Jo,[Wo.errorCode]:Wo,[Yo.errorCode]:Yo,[Qo.errorCode]:Qo,[Kr.errorCode]:Kr,[Xo.errorCode]:Xo,[ea.errorCode]:ea};var Ft=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function JP(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(JP,"isClientAuthMethod");var Qu="code",Xu="S256";function WP(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&JP(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}o(WP,"selectClientAuthMethod");function YP(e,t,r,n){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":QP(a,i,r);return;case"client_secret_post":XP(a,i,n);return;case"none":ex(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(YP,"applyClientAuthentication");function QP(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}o(QP,"applyBasicAuth");function XP(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(XP,"applyPostAuth");function ex(e,t){t.set("client_id",e)}o(ex,"applyPublicAuth");async function Yh(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Fh.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:s}=n,c=Jh[a]||Vt;return new c(i||"",s)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Vt(a)}}o(Yh,"parseErrorResponse");async function gr(e,t){try{return await ed(e,t)}catch(r){if(r instanceof Vr||r instanceof Zr)return await e.invalidateCredentials?.("all"),await ed(e,t);if(r instanceof Fr)return await e.invalidateCredentials?.("tokens"),await ed(e,t);throw r}}o(gr,"auth");async function ed(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:a,fetchFn:i}){let s=await e.discoveryState?.(),c,d,p,l=a;if(!l&&s?.resourceMetadataUrl&&(l=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(d=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await Xh(d,{fetchFn:i}),!c)try{c=await Qh(t,{resourceMetadataUrl:l},i)}catch{}(p!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let R=await ix(t,{resourceMetadataUrl:l,fetchFn:i});d=R.authorizationServerUrl,p=R.authorizationServerMetadata,c=R.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let m=await tx(t,e,c),h=n||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,y=await Promise.resolve(e.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let R=p?.client_id_metadata_document_supported===!0,M=e.clientMetadataUrl;if(M&&!rd(M))throw new Kr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${M}`);if(R&&M)y={client_id:M},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Me=await lx(d,{metadata:p,clientMetadata:e.clientMetadata,scope:h,fetchFn:i});await e.saveClientInformation(Me),y=Me}}let _=!e.redirectUrl;if(r!==void 0||_){let R=await dx(e,d,{metadata:p,resource:m,authorizationCode:r,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}let S=await e.tokens();if(S?.refresh_token)try{let R=await ux(d,{metadata:p,clientInformation:y,refreshToken:S.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}catch(R){if(!(!(R instanceof be)||R instanceof Vt))throw R}let w=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:b}=await sx(d,{metadata:p,clientInformation:y,state:w,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(v),"REDIRECT"}o(ed,"authInternal");function rd(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(rd,"isHttpsUrl");async function tx(e,t,r){let n=Zh(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Kh({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}o(tx,"selectResourceURL");function nd(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=td(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let s=td(e,"scope")||void 0,c=td(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}o(nd,"extractWWWAuthenticateParams");function td(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(n);return a?a[1]||a[2]:null}o(td,"extractFieldFromWwwAuth");async function Qh(e,t,r=fetch){let n=await ox(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return qi.parse(await n.json())}o(Qh,"discoverOAuthProtectedResourceMetadata");async function od(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?od(e,void 0,r):void 0;throw n}}o(od,"fetchWithCorsRetry");function rx(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(rx,"buildWellKnownPath");async function Wh(e,t,r=fetch){return await od(e,{"MCP-Protocol-Version":t},r)}o(Wh,"tryMetadataDiscovery");function nx(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(nx,"shouldAttemptFallback");async function ox(e,t,r,n){let a=new URL(e),i=n?.protocolVersion??cr,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let d=rx(t,a.pathname);s=new URL(d,n?.metadataServerUrl??a),s.search=a.search}let c=await Wh(s,i,r);if(!n?.metadataUrl&&nx(c,a.pathname)){let d=new URL(`/.well-known/${t}`,a);c=await Wh(d,i,r)}return c}o(ox,"discoverMetadataWithFallback");function ax(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),n.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}o(ax,"buildDiscoveryUrls");async function Xh(e,{fetchFn:t=fetch,protocolVersion:r=cr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=ax(e);for(let{url:i,type:s}of a){let c=await od(i,n,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?Do.parse(await c.json()):Ni.parse(await c.json())}}}o(Xh,"discoverAuthorizationServerMetadata");async function ix(e,t){let r,n;try{r=await Qh(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));let a=await Xh(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o(ix,"discoverOAuthServerInfo");async function sx(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:a,state:i,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Qu))throw new Error(`Incompatible auth server: does not support response type ${Qu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Xu))throw new Error(`Incompatible auth server: does not support code challenge method ${Xu}`)}else c=new URL("/authorize",e);let d=await Wu(),p=d.code_verifier,l=d.code_challenge;return c.searchParams.set("response_type",Qu),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",l),c.searchParams.set("code_challenge_method",Xu),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),a&&c.searchParams.set("scope",a),a?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:p}}o(sx,"startAuthorization");function cx(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(cx,"prepareAuthorizationCodeRequest");async function eg(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),a)await a(d,r,c,t);else if(n){let l=t?.token_endpoint_auth_methods_supported??[],m=WP(n,l);YP(m,n,d,r)}let p=await(s??fetch)(c,{method:"POST",headers:d,body:r});if(!p.ok)throw await Yh(p);return Ho.parse(await p.json())}o(eg,"executeTokenRequest");async function ux(e,{metadata:t,clientInformation:r,refreshToken:n,resource:a,addClientAuthentication:i,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),d=await eg(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:s});return{refresh_token:n,...d}}o(ux,"refreshAuthorization");async function dx(e,t,{metadata:r,resource:n,authorizationCode:a,fetchFn:i}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!a)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await e.codeVerifier();c=cx(a,p,e.redirectUrl)}let d=await e.clientInformation();return eg(t,{metadata:r,tokenRequestParams:c,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}o(dx,"fetchToken");async function lx(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:a}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s=await(a??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!s.ok)throw await Yh(s);return Lo.parse(await s.json())}o(lx,"registerClient");ae();function ad(e){return`Zuplo MCP Gateway - ${e}`}o(ad,"buildGatewayOAuthClientName");function tg(e,t){let r=new URL(e,ie(t));return qe(r)&&jt(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(tg,"buildGatewayOAuthRedirectUri");function id(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(id,"buildOAuthClientMetadataDocumentUrl");function rg(e){return ie(e)}o(rg,"requireOAuthClientMetadataOrigin");function ng(e,t,r){let n=je(t),a=Br(t,r);return{client_id:id({origin:e,upstreamServerId:t,authProfileId:r}),client_name:ad(n.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(a.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}o(ng,"buildOAuthClientMetadataDocument");var px=u.union([Lo,Yu]),mx=u.object({authorizationServerUrl:u.url(),resourceMetadataUrl:u.url().optional(),resourceMetadata:qi.optional(),authorizationServerMetadata:u.union([Do,Ni]).optional()}).passthrough(),fx="Bearer";function hx(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(hx,"splitScopes");function gx(e){return Ya.parse(e)}o(gx,"parsePkceCodeVerifier");function yx(e){if(typeof e.expires_in=="number")return re(new Date(Date.now()+e.expires_in*1e3))}o(yx,"readTokenExpiry");async function og(e){if(e!==void 0)return Gr(JSON.stringify(e))}o(og,"encryptJson");async function ag(e,t){if(!e)return;let r=await Gt(e);try{return t.parse(JSON.parse(r))}catch(n){throw g("oauth_state_invalid","Stored upstream OAuth JSON state is invalid.",n)}}o(ag,"decryptJson");function Sx(e){if(e===void 0)return;let t={authorizationServerUrl:e.authorizationServerUrl};return e.resourceMetadataUrl!==void 0&&(t.resourceMetadataUrl=e.resourceMetadataUrl),e.resourceMetadata!==void 0&&(t.resourceMetadata=e.resourceMetadata),e.authorizationServerMetadata!==void 0&&(t.authorizationServerMetadata=e.authorizationServerMetadata),t}o(Sx,"toOAuthDiscoveryState");function _x(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(_x,"clientInformationAllowsRedirectUri");function wx(e,t,r){let n=je(e),a=Br(e,t),i;return a.scopes.length>0&&(i=a.scopes.join(a.scopeDelimiter)),{client_name:ad(n.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:i,token_endpoint_auth_method:"none"}}o(wx,"buildOAuthClientMetadata");function vx(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw g("internal_server_error",`Manual OAuth registration for ${e.upstreamServerId} requires clientSecret.`);return Lo.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(vx,"buildManualOAuthClientInformation");function bx(e,t,r){let n=id({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return rd(n)?n:void 0}o(bx,"buildClientMetadataUrl");function ig(e){for(let t of e)if(t!==void 0)return t}o(ig,"firstDefined");function Rx(e){let t=Br(e.target.upstreamServerId,e.target.authProfileId),r=wx(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:vx({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=bx(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(Rx,"buildInitialOAuthClientSetup");function Cx(e,t){if(t===void 0)return ig([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(Cx,"readEncryptedClientInformation");function Ix(e){return ig([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(Ix,"readEncryptedDiscoveryState");var Jr=class{static{o(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredClientInformation;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=Rx({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.connection=t.connection,this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=Cx(t,this.configuredClientInformation),this.encryptedDiscoveryState=Ix(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return Th({id:t.id,...Io({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.encryptedClientInformation=await og(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await og(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Ho.parse(t),n=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0;this.cachedTokens=r,this.tokensLoaded=!0;let a={id:this.connection?.id??ai(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Gr(r.access_token),encryptedRefreshToken:r.refresh_token?await Gr(r.refresh_token):void 0,scopes:hx(r.scope??this.clientMetadataValue.scope),expiresAt:yx(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await K().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:gx(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw g("oauth_state_invalid","OAuth code verifier is missing");return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Em(),...Io({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,virtualServerId:this.target.virtualServerId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:re(new Date(Date.now()+xh)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await K().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await ag(this.encryptedClientInformation,px)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!_x(t,this.redirectUriValue)){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1);return}return this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=Sx(await ag(this.encryptedDiscoveryState,mx))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.cachedDiscoveryState}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection?.encryptedAccessToken||this.connection.status!=="active")return;let t=Ho.parse({access_token:await Gt(this.connection.encryptedAccessToken),token_type:fx,refresh_token:this.connection.encryptedRefreshToken?await Gt(this.connection.encryptedRefreshToken):void 0,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=t,t}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await K().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var Px=1e4,xx=256*1024,Ax=2;function kx(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(kx,"hasUsableAccessToken");var Tx="does not support dynamic client registration";function Ex(e){return e instanceof Error&&e.message.includes(Tx)}o(Ex,"isDynamicClientRegistrationUnsupported");function Ux(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(Ux,"readOAuthFetchRequest");function Ox(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(Ox,"responseLooksJson");function sg(e){return async(t,r)=>{let n=Ux(t),a=await qn(t,r,{maxRedirects:Ax,maxResponseBytes:xx,problemCode:"upstream_token_exchange_failed",timeoutMs:Px}),i=await a.clone().text();if(!Ox(a,i))return a;try{JSON.parse(i)}catch(s){throw g("upstream_token_exchange_failed",`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,s)}return a}}o(sg,"createUpstreamOAuthFetch");async function cg(e,t){try{return await gr(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:sg(t.upstreamServerId)})}catch(r){throw Ex(r)?g("upstream_client_registration_required",`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,r):r}}o(cg,"runUpstreamOAuth");async function $x(e,t){return gr(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:sg(t.upstreamServerId)})}o($x,"exchangeUpstreamAuthorizationCode");async function ug(e,t){let r=await cg(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?g("upstream_token_exchange_failed",`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`):g("upstream_token_exchange_failed",`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`)}o(ug,"requireUpstreamAuthorizationRedirect");async function dg(e){if(kx(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await cg(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`);if(!e.provider.authorizationUrl)throw g("upstream_token_exchange_failed",`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`);return{kind:"connect_required",payload:await jx({requestUrl:e.target.request.url,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.target.virtualServerId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}o(dg,"authorizeUpstreamOAuthSession");async function zx(e){let t=await Oi(e.stateToken),r=await K().consumeUpstreamOAuthState({id:t.id,now:re(new Date)}),n=Mx(r);return qx({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Nx(n),n}o(zx,"consumeStoredCallbackState");function Mx(e){switch(e.kind){case"consumed":throw g("oauth_state_reused","OAuth state has already been used");case"missing":throw g("oauth_state_expired","OAuth state is missing or expired");case"available":return e.record}}o(Mx,"readConsumedCallbackState");function qx(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.virtualServerId===e.signedState.virtualServerId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw g("oauth_callback_mismatch","OAuth callback did not match the initiating request")}o(qx,"assertStoredCallbackStateMatches");function Nx(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw g("oauth_state_expired","OAuth state has expired")}o(Nx,"assertStoredCallbackStateFresh");async function jx(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.virtualServerId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),$h(r)}let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.virtualServerId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Nn(t)}o(jx,"buildOAuthConnectRequiredResponse");async function lg(e){let t=await zx({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=xn(t),[n]=await K().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(a.connection=n);let i=new Jr(a),s=await $x(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`):g("upstream_token_exchange_failed",`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`)}o(lg,"finishUpstreamOAuthCallback");async function pg(e){let t=je(e.upstreamServerId),r=Br(e.upstreamServerId,e.authProfileId),n=tg(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await K().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:n,returnOrigin:ie(e.request.url)}}}o(pg,"prepareUpstreamOAuthRequest");async function mg(e){let t=await pg(e),r=new Jr({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return ug(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(mg,"startUpstreamConnect");async function fg(e){let t=await pg(e),r=new Jr({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return dg({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(fg,"authorizeUpstreamRequest");function Dx(e,t){switch(e.kind){case"bearer_token":{if(!e.token)throw g("internal_server_error",`Static bearer token is not configured for upstream ${t}.`);return{type:"bearer_token",token:e.token}}case"headers":{let r={};for(let n of e.headers){if(!n.value)throw g("internal_server_error",`Static header ${n.name} is not configured for upstream ${t}.`);r[n.name]=n.value}return{type:"headers",headers:r}}}}o(Dx,"resolveStaticSecretCredential");async function ji(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user_oauth":return fg({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}});case"shared-secret":return Dh({owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}});case"static_secret":{let n=mr({upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId});if(n.mode!=="static_secret")throw g("internal_server_error",`Resolved static-secret credential context loaded ${n.mode} config.`);return{kind:"authorized",credential:Dx(n.secret,t.upstreamServerId)}}case"user-secret":return Bh({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}})}throw g("internal_server_error",`Unsupported upstream auth route context ${JSON.stringify(t)}.`)}o(ji,"resolveUpstreamCredentialForRoute");async function hg(e){let t=ir(e.principal.subjectId),r=St().byVirtualServerId.get(e.virtualServerId);if(r)for(let n of r.connections)n.authConfig.mode!=="user-secret"||n.authConfig.secret.kind!=="bearer_token"||n.authConfig.secret.capture!=="browser_login"||await Mi({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o(hg,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function gg(e){let t,r={request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,virtualServerId:e.connectRequest.virtualServerId,...e.connectRequest.returnTo===void 0?{}:{returnTo:e.connectRequest.returnTo}},n=xt(e.connectRequest.authMode);switch(n.connectSupport){case"oauth_authorization":t=await mg(r);break;case"user_secret_capture":t=await Gh(r);break;case"none":throw g("invalid_request",n.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,virtualServerId:e.connectRequest.virtualServerId}}o(gg,"startUpstreamConnectForRequest");async function yg(e){let r=(await Oi(e.callbackRequest.state)).authProfileId,n=mr({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(xt(n.mode).callbackSupport!=="authorization_code")throw g("invalid_request",`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return lg({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:je(e.callbackRequest.upstreamServerId)})}o(yg,"finishUpstreamCallbackForRequest");var sd=new It("route-upstream-bindings");function Sg(e){return`${e.upstreamServerId}:${e.authProfileId}`}o(Sg,"buildRouteBindingDuplicateKey");function cd(e,t){let r=sd.get(e)??[],n=Sg(t);if(r.find(i=>Sg(i)===n)!==void 0)throw g("internal_server_error",`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.push(t),sd.set(e,r)}o(cd,"appendResolvedUpstreamBindingContext");function Di(e){return sd.get(e)??[]}o(Di,"readResolvedUpstreamBindingContexts");var Hx=new Set(["authorization","connection","content-length","cookie","cookie2","host","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),Lx=3e4,Bx=2*1024*1024,Gx=2;function Vx(e){return e.kind!=="authorized"||e.credential.type!=="headers"?[]:Object.keys(e.credential.headers)}o(Vx,"readCredentialHeaderNames");async function Fx(e,t){Ct("handler.mcp-upstream");let r=Di(t);if(r.length!==1)throw new ue(`mcpUpstreamHandler requires exactly one upstream binding on the route (found ${r.length}). Attach a single \`mcp-upstream-connection-inbound\` policy or use \`McpVirtualServerHandler\` for multi-upstream routes.`);let[n]=r,a=await ji({request:e,routeAuth:n});if(a.kind==="connect_required")return t.log.info({event:"mcp_upstream_connect_required",upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId},"MCP upstream proxy: upstream connection required"),Response.json({error:"connect_required",payload:a.payload},{status:401,headers:{"www-authenticate":'Bearer realm="upstream", error="invalid_token"'}});let i=je(n.upstreamServerId),s=i.transport.baseUrl,c=new Headers;for(let[h,y]of e.headers.entries())Hx.has(h.toLowerCase())||c.set(h,y);let d=[];for(let h of i.transport.requestHeaders??[]){if(h.value===void 0){if(h.required)throw new ue(`mcpUpstreamHandler: configured request header '${h.name}' is required but its value is unset. Set the env var that backs the header or mark the header optional.`);continue}c.set(h.name,h.value),d.push(h.name)}let p=a.credential;switch(p.type){case"bearer_token":c.set("authorization",`Bearer ${p.token}`);break;case"headers":for(let[h,y]of Object.entries(p.headers))c.set(h,y);break;case"mcp_oauth_provider":{let h=await p.provider.tokens();if(!h)return t.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:n.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401});c.set("authorization",`${h.token_type??"Bearer"} ${h.access_token}`);break}}let l=[...d,...Vx(a)],m={method:e.method,headers:c,body:e.method==="GET"||e.method==="HEAD"?void 0:e.body,duplex:"half"};return t.log.info({event:"mcp_upstream_handler_proxy",upstreamServerId:n.upstreamServerId,upstreamUrl:s,method:e.method},"MCP upstream proxy: forwarding request"),qn(s,m,{additionalCrossOriginStrippedHeaders:l,context:t,maxRedirects:Gx,maxResponseBytes:Bx,problemCode:"upstream_capability_invocation_failed",timeoutMs:Lx})}o(Fx,"mcpUpstreamHandler");Cv();function yr(e){return!!e._zod}o(yr,"isZ4Schema");function Ge(e,t){return yr(e)?dc(e,t):e.safeParse(t)}o(Ge,"safeParse");function Hn(e){if(!e)return;let t;if(yr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}o(Hn,"getObjectShape");function _g(e){if(yr(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}o(_g,"getLiteralValue");function Sr(e){return e==="completed"||e==="failed"||e==="cancelled"}o(Sr,"isTerminal");var Kx=Symbol("Let zodToJsonSchema decide on which parser to use");var aG=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ud(e){let r=Hn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=_g(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(ud,"getMethodLiteral");function dd(e,t){let r=Ge(e,t);if(!r.success)throw r.error;return r.data}o(dd,"parseWithCompat");var eA=6e4,Ln=class{static{o(this,"Protocol")}constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(li,r=>{this._oncancel(r)}),this.setNotificationHandler(hi,r=>{this._onprogress(r)}),this.setRequestHandler(fi,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gi,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new A(E.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(Si,async(r,n)=>{let a=o(async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(c.type==="response"||c.type==="error"){let d=c.message,p=d.id,l=this._requestResolvers.get(p);if(l)if(this._requestResolvers.delete(p),c.type==="response")l(d);else{let m=d,h=new A(m.error.code,m.error.message,m.error.data);l(h)}else{let m=c.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${p}`))}continue}await this._transport?.send(c.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new A(E.InvalidParams,`Task not found: ${i}`);if(!Sr(s.status))return await this._waitForTaskUpdate(i,n.signal),await a();if(Sr(s.status)){let c=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[dr]:{taskId:i}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(_i,async(r,n)=>{try{let{tasks:a,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:a,nextCursor:i,_meta:{}}}catch(a){throw new A(E.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(vi,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new A(E.InvalidParams,`Task not found: ${r.params.taskId}`);if(Sr(a.status))throw new A(E.InvalidParams,`Cannot cancel task in terminal status: ${a.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new A(E.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(a){throw a instanceof A?a:new A(E.InvalidRequest,`Failed to cancel task: ${a instanceof Error?a.message:String(a)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,a,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:a})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),A.fromError(E.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let a=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{a?.(i,s),yt(i)||Un(i)?this._onresponse(i):Pt(i)?this._onrequest(i,s):jf(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=A.fromError(E.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,a=this._transport,i=t.params?._meta?.[dr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:E.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},a?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):a?.send(l).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let c=Mf(t.params)?t.params.task:void 0,d=this._taskStore?this.requestTaskStore(t,a?.sessionId):void 0,p={signal:s.signal,sessionId:a?.sessionId,_meta:t.params?._meta,sendNotification:o(async l=>{if(s.signal.aborted)return;let m={relatedRequestId:t.id};i&&(m.relatedTask={taskId:i}),await this.notification(l,m)},"sendNotification"),sendRequest:o(async(l,m,h)=>{if(s.signal.aborted)throw new A(E.ConnectionClosed,"Request was cancelled");let y={...h,relatedRequestId:t.id};i&&!y.relatedTask&&(y.relatedTask={taskId:i});let _=y.relatedTask?.taskId??i;return _&&d&&await d.updateTaskStatus(_,"input_required"),await this.request(l,m,y)},"sendRequest"),authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,p)).then(async l=>{if(s.signal.aborted)return;let m={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)},async l=>{if(s.signal.aborted)return;let m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:E.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,a=Number(r),i=this._progressHandlers.get(a);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(a),c=this._timeoutInfo.get(a);if(c&&s&&c.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(d){this._responseHandlers.delete(a),this._progressHandlers.delete(a),this._cleanupTimeout(a),s(d);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),yt(t))n(t);else{let s=new A(t.error.code,t.error.message,t.error.data);n(s)}return}let a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(yt(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let c=s.task;typeof c.taskId=="string"&&(i=!0,this._taskProgressTokens.set(c.taskId,r))}}if(i||this._progressHandlers.delete(r),yt(t))a(t);else{let s=A.fromError(t.error.code,t.error.message,t.error.data);a(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:a}=n??{};if(!a){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof A?s:new A(E.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Bt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new A(E.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},Sr(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new A(E.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new A(E.InternalError,`Task ${i} was cancelled`)});return}if(c.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let d=c.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(p=>setTimeout(p,d)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof A?s:new A(E.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s,task:c,relatedTask:d}=n??{};return new Promise((p,l)=>{let m=o(b=>{l(b)},"earlyReject");if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),c&&this.assertTaskCapability(t.method)}catch(b){m(b);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,y={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),c&&(y.params={...y.params,task:c}),d&&(y.params={...y.params,_meta:{...y.params?._meta||{},[dr]:d}});let _=o(b=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(b)}},{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(M=>this._onerror(new Error(`Failed to send cancellation: ${M}`)));let R=b instanceof A?b:new A(E.RequestTimeout,String(b));l(R)},"cancel");this._responseHandlers.set(h,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let R=Ge(r,b.result);R.success?p(R.data):l(R.error)}catch(R){l(R)}}}),n?.signal?.addEventListener("abort",()=>{_(n?.signal?.reason)});let S=n?.timeout??eA,w=o(()=>_(A.fromError(E.RequestTimeout,"Request timed out",{timeout:S})),"timeoutHandler");this._setupTimeout(h,S,n?.maxTotalTimeout,w,n?.resetTimeoutOnProgress??!1);let v=d?.taskId;if(v){let b=o(R=>{let M=this._responseHandlers.get(h);M?M(R):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))},"responseResolver");this._requestResolvers.set(h,b),this._enqueueTaskMessage(v,{type:"request",message:y,timestamp:Date.now()}).catch(R=>{this._cleanupTimeout(h),l(R)})}else this._transport.send(y,{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(h),l(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},yi,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},wi,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Hf,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let c={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[dr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:c,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let c={...t,jsonrpc:"2.0"};r?.relatedTask&&(c={...c,params:{...c.params,_meta:{...c.params?._meta||{},[dr]:r.relatedTask}}}),this._transport?.send(c,r).catch(d=>this._onerror(d))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[dr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=ud(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,i)=>{let s=dd(t,a);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=ud(t);this._notificationHandlers.set(n,a=>{let i=dd(t,a);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let a=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,a)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let a of n)if(a.type==="request"&&Pt(a.message)){let i=a.message.id,s=this._requestResolvers.get(i);s?(s(new A(E.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let a=await this._taskStore?.getTask(t);a?.pollInterval&&(n=a.pollInterval)}catch{}return new Promise((a,i)=>{if(r.aborted){i(new A(E.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new A(E.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:o(async a=>{if(!t)throw new Error("No request provided");return await n.createTask(a,t.id,{method:t.method,params:t.params},r)},"createTask"),getTask:o(async a=>{let i=await n.getTask(a,r);if(!i)throw new A(E.InvalidParams,"Failed to retrieve task: Task not found");return i},"getTask"),storeTaskResult:o(async(a,i,s)=>{await n.storeTaskResult(a,i,s,r);let c=await n.getTask(a,r);if(c){let d=$o.parse({method:"notifications/tasks/status",params:c});await this.notification(d),Sr(c.status)&&this._cleanupTaskProgressHandler(a)}},"storeTaskResult"),getTaskResult:o(a=>n.getTaskResult(a,r),"getTaskResult"),updateTaskStatus:o(async(a,i,s)=>{let c=await n.getTask(a,r);if(!c)throw new A(E.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(Sr(c.status))throw new A(E.InvalidParams,`Cannot update task "${a}" from terminal status "${c.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(a,i,s,r);let d=await n.getTask(a,r);if(d){let p=$o.parse({method:"notifications/tasks/status",params:d});await this.notification(p),Sr(d.status)&&this._cleanupTaskProgressHandler(a)}},"updateTaskStatus"),listTasks:o(a=>n.listTasks(a,r),"listTasks")}}};function wg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(wg,"isPlainObject");function Hi(e,t){let r={...e};for(let n in t){let a=n,i=t[a];if(i===void 0)continue;let s=r[a];wg(s)&&wg(i)?r[a]={...s,...i}:r[a]=i}return r}o(Hi,"mergeCapabilities");var i_=Gp(Jl(),1),s_=Gp(a_(),1);function GU(){let e=new i_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,s_.default)(e),e}o(GU,"createDefaultAjvInstance");var ao=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??GU()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Cs=class{static{o(this,"ExperimentalServerTasks")}constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let a=t.messages[t.messages.length-1],i=Array.isArray(a.content)?a.content:[a.content],s=i.some(l=>l.type==="tool_result"),c=t.messages.length>1?t.messages[t.messages.length-2]:void 0,d=c?Array.isArray(c.content)?c.content:[c.content]:[],p=d.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!p)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(p){let l=new Set(d.filter(h=>h.type==="tool_use").map(h=>h.id)),m=new Set(i.filter(h=>h.type==="tool_result").map(h=>h.toolUseId));if(l.size!==m.size||![...l].every(h=>m.has(h)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Hr,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),a=t.mode??"form";switch(a){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=a==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},pr,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function Is(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}o(Is,"assertToolsCallTaskCapability");function Ps(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}o(Ps,"assertClientRequestTaskCapability");var xs=class extends Ln{static{o(this,"Server")}constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(qo.options.map((n,a)=>[n,a])),this.isMessageIgnored=(n,a)=>{let i=this._loggingLevels.get(a);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new ao,this.setRequestHandler(pi,n=>this._oninitialize(n)),this.setNotificationHandler(mi,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ru,async(n,a)=>{let i=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,c=qo.safeParse(s);return c.success&&this._loggingLevels.set(i,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Cs(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Hi(this._capabilities,t)}setRequestHandler(t,r){let a=Hn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(yr(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let c=o(async(d,p)=>{let l=Ge(Mo,d);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new A(E.InvalidParams,`Invalid tools/call request: ${_}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let _=Ge(Bt,h);if(!_.success){let S=_.error instanceof Error?_.error.message:String(_.error);throw new A(E.InvalidParams,`Invalid task creation result: ${S}`)}return _.data}let y=Ge(lr,h);if(!y.success){let _=y.error instanceof Error?y.error.message:String(y.error);throw new A(E.InvalidParams,`Invalid tools/call result: ${_}`)}return y.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Ps(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Is(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:ur.includes(r)?r:cr,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"},Lt)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],a=Array.isArray(n.content)?n.content:[n.content],i=a.some(p=>p.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],d=c.some(p=>p.type==="tool_use");if(i){if(a.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(a.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(p.size!==l.size||![...p].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},No,r):this.request({method:"sampling/createMessage",params:t},Hr,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let a=t;return this.request({method:"elicitation/create",params:a},pr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let a=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:a},pr,r);if(i.action==="accept"&&i.content&&a.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!c.valid)throw new A(E.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(s){throw s instanceof A?s:new A(E.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},xu,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var As=class{static{o(this,"WebStandardStreamableHTTPServerTransport")}constructor(t={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=t.sessionIdGenerator,this._enableJsonResponse=t.enableJsonResponse??!1,this._eventStore=t.eventStore,this._onsessioninitialized=t.onsessioninitialized,this._onsessionclosed=t.onsessionclosed,this._allowedHosts=t.allowedHosts,this._allowedOrigins=t.allowedOrigins,this._enableDnsRebindingProtection=t.enableDnsRebindingProtection??!1,this._retryInterval=t.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(t,r,n,a){let i={code:r,message:n};return a?.data!==void 0&&(i.data=a.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:t,headers:{"Content-Type":"application/json",...a?.headers}})}validateRequestHeaders(t){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=t.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=t.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(t,r){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(t);if(n)return n;switch(t.method){case"POST":return this.handlePostRequest(t,r);case"GET":return this.handleGetRequest(t);case"DELETE":return this.handleDeleteRequest(t);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(t,r,n,a){if(!this._eventStore||a<"2025-11-25")return;let i=await this._eventStore.storeEvent(n,{}),s=`id: ${i}
33
41
  data:
34
42
 
35
43
  `;this._retryInterval!==void 0&&(s=`id: ${i}
@@ -40,19 +48,17 @@ data:
40
48
  `;return a&&(i+=`id: ${a}
41
49
  `),i+=`data: ${JSON.stringify(n)}
42
50
 
43
- `,t.enqueue(r.encode(i)),!0}catch(i){return this.onerror?.(i),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,r){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let a=t.headers.get("content-type");if(!a||!a.includes("application/json"))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let i={headers:Object.fromEntries(t.headers.entries()),url:new URL(t.url)},s;if(r?.parsedBody!==void 0)s=r.parsedBody;else try{s=await t.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let c;try{Array.isArray(s)?c=s.map(v=>$r.parse(v)):c=[$r.parse(s)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let d=c.some(uc);if(d){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(c.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!d){let v=this.validateSession(t);if(v)return v;let b=this.validateProtocolVersion(t);if(b)return b}if(!c.some(It)){for(let v of c)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i});return new Response(null,{status:202})}let l=crypto.randomUUID(),m=c.find(v=>uc(v)),h=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??Kp;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:o(()=>{this._streamMapping.delete(l)},"cleanup")});for(let b of c)It(b)&&this._requestToStreamMapping.set(b.id,l);for(let b of c)this.onmessage?.(b,{authInfo:r?.authInfo,requestInfo:i})});let y=new TextEncoder,_,S=new ReadableStream({start:o(v=>{_=v},"start"),cancel:o(()=>{this._streamMapping.delete(l)},"cancel")}),w={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(w["mcp-session-id"]=this.sessionId);for(let v of c)It(v)&&(this._streamMapping.set(l,{controller:_,encoder:y,cleanup:o(()=>{this._streamMapping.delete(l);try{_.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(v.id,l));await this.writePrimingEvent(_,y,l,h);for(let v of c){let b,R;It(v)&&this._eventStore&&h>="2025-11-25"&&(b=o(()=>{this.closeSSEStream(v.id)},"closeSSEStream"),R=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i,closeSSEStream:b,closeStandaloneSSEStream:R})}return new Response(S,{status:200,headers:w})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let n=this.validateProtocolVersion(t);return n||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(t){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=t.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let r=t.headers.get("mcp-protocol-version");if(r!==null&&!dr.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${dr.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${dr.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:t})=>{t()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let n=r?.relatedRequestId;if((St(t)||fn(t))&&(n=t.id),n===void 0){if(St(t)||fn(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let s;this._eventStore&&(s=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let c=this._streamMapping.get(this._standaloneSseStreamId);if(c===void 0)return;c.controller&&c.encoder&&this.writeSSEEvent(c.controller,c.encoder,t,s);return}let a=this._requestToStreamMapping.get(n);if(!a)throw new Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(a);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let s;this._eventStore&&(s=await this._eventStore.storeEvent(a,t)),this.writeSSEEvent(i.controller,i.encoder,t,s)}if(St(t)||fn(t)){this._requestResponseMap.set(n,t);let s=Array.from(this._requestToStreamMapping.entries()).filter(([d,p])=>p===a).map(([d])=>d);if(s.every(d=>this._requestResponseMap.has(d))){if(!i)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let d={"Content-Type":"application/json"};this.sessionId!==void 0&&(d["mcp-session-id"]=this.sessionId);let p=s.map(l=>this._requestResponseMap.get(l));p.length===1?i.resolveJson(new Response(JSON.stringify(p[0]),{status:200,headers:d})):i.resolveJson(new Response(JSON.stringify(p),{status:200,headers:d}))}else i.cleanup();for(let d of s)this._requestResponseMap.delete(d),this._requestToStreamMapping.delete(d)}}}};function zn(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let a=0;a<n;a++)if(!zn(e[a],t[a]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;for(let s of n)if(!zn(e[s],t[s]))return!1;return!0}return e===t}o(zn,"deepCompareStrict");function at(e){return encodeURI(zA(e))}o(at,"encodePointer");function zA(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(zA,"escapePointer");var MA={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},qA={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},NA={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},DA=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Kt(e,t=Object.create(null),r=DA,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);s.hash.length>1?t[s.href]=e:(s.hash="",n===""?r=s:Kt(e,t,r))}}else if(e!==!0&&e!==!1)return t;let a=r.href+(n?"#"+n:"");if(t[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(t[a]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:a}),e.$ref&&e.__absolute_ref__===void 0){let i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(NA[i])continue;let s=`${n}/${at(i)}`,c=e[i];if(Array.isArray(c)){if(MA[i]){let d=c.length;for(let p=0;p<d;p++)Kt(c[p],t,r,`${s}/${p}`)}}else if(qA[i])for(let d in c)Kt(c[d],t,r,`${s}/${at(d)}`);else Kt(c,t,r,s)}return t}o(Kt,"dereference");var jA=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,HA=[0,31,28,31,30,31,30,31,31,30,31,30,31],LA=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,BA=/^(?=.{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,GA=/^(?:[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,VA=/^(?:(?:[^\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,FA=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,ZA=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,KA=/^(?:\/(?:[^~/]|~0|~1)*)*$/,WA=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,JA=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,YA=o(e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},"EMAIL"),QA=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,XA=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,ek=o(e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),"DURATION");function Ut(e){return e.test.bind(e)}o(Ut,"bind");var Td={date:Qh,time:Xh.bind(void 0,!1),"date-time":nk,duration:ek,uri:ik,"uri-reference":Ut(GA),"uri-template":Ut(VA),url:Ut(FA),email:YA,hostname:Ut(BA),ipv4:Ut(QA),ipv6:Ut(XA),regex:ck,uuid:Ut(ZA),"json-pointer":Ut(KA),"json-pointer-uri-fragment":Ut(WA),"relative-json-pointer":Ut(JA)};function tk(e){return e%4===0&&(e%100!==0||e%400===0)}o(tk,"isLeapYear");function Qh(e){let t=e.match(jA);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&tk(r)?29:HA[n])}o(Qh,"date");function Xh(e,t){let r=t.match(LA);if(!r)return!1;let n=+r[1],a=+r[2],i=+r[3],s=!!r[5];return(n<=23&&a<=59&&i<=59||n==23&&a==59&&i==60)&&(!e||s)}o(Xh,"time");var rk=/t|\s/i;function nk(e){let t=e.split(rk);return t.length==2&&Qh(t[0])&&Xh(!0,t[1])}o(nk,"date_time");var ok=/\/|:/,ak=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function ik(e){return ok.test(e)&&ak.test(e)}o(ik,"uri");var sk=/[^\\]\\Z/;function ck(e){if(sk.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(ck,"regex");var eg;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(eg||(eg={}));function tg(e){let t=0,r=e.length,n=0,a;for(;n<r;)t++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=e.charCodeAt(n),(a&64512)==56320&&n++);return t}o(tg,"ucs2length");function fe(e,t,r="2019-09",n=Kt(t),a=!0,i=null,s="#",c="#",d=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let p=typeof e,l;switch(p){case"boolean":case"number":case"string":l=p;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${p}" type are not supported.`)}let{$ref:m,$recursiveRef:h,$recursiveAnchor:y,type:_,const:S,enum:w,required:v,not:b,anyOf:R,allOf:q,oneOf:N,if:qe,then:it,else:dn,format:ar,properties:qt,patternProperties:Tr,additionalProperties:oo,unevaluatedProperties:ao,minProperties:io,maxProperties:Zs,propertyNames:kp,dependentRequired:Ks,dependentSchemas:Ws,dependencies:Js,prefixItems:Ys,items:so,additionalItems:Tp,unevaluatedItems:Ep,contains:Up,minContains:Nt,maxContains:Ua,minItems:Qs,maxItems:Xs,uniqueItems:Sv,minimum:Er,maximum:Ur,exclusiveMinimum:co,exclusiveMaximum:uo,multipleOf:Oa,minLength:$a,maxLength:za,pattern:Op,__absolute_ref__:Ma,__absolute_recursive_ref__:_v}=t,k=[];if(y===!0&&i===null&&(i=t),h==="#"){let D=i===null?n[_v]:i,z=`${c}/$recursiveRef`,B=fe(e,i===null?t:i,r,n,a,D,s,z,d);B.valid||k.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:z,error:"A subschema had errors."},...B.errors)}if(m!==void 0){let z=n[Ma||m];if(z===void 0){let P=`Unresolved $ref "${m}".`;throw Ma&&Ma!==m&&(P+=` Absolute URI "${Ma}".`),P+=`
51
+ `,t.enqueue(r.encode(i)),!0}catch(i){return this.onerror?.(i),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,r){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let a=t.headers.get("content-type");if(!a||!a.includes("application/json"))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let i={headers:Object.fromEntries(t.headers.entries()),url:new URL(t.url)},s;if(r?.parsedBody!==void 0)s=r.parsedBody;else try{s=await t.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let c;try{Array.isArray(s)?c=s.map(v=>Dr.parse(v)):c=[Dr.parse(s)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let d=c.some(eu);if(d){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(c.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!d){let v=this.validateSession(t);if(v)return v;let b=this.validateProtocolVersion(t);if(b)return b}if(!c.some(Pt)){for(let v of c)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i});return new Response(null,{status:202})}let l=crypto.randomUUID(),m=c.find(v=>eu(v)),h=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??Of;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:o(()=>{this._streamMapping.delete(l)},"cleanup")});for(let b of c)Pt(b)&&this._requestToStreamMapping.set(b.id,l);for(let b of c)this.onmessage?.(b,{authInfo:r?.authInfo,requestInfo:i})});let y=new TextEncoder,_,S=new ReadableStream({start:o(v=>{_=v},"start"),cancel:o(()=>{this._streamMapping.delete(l)},"cancel")}),w={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(w["mcp-session-id"]=this.sessionId);for(let v of c)Pt(v)&&(this._streamMapping.set(l,{controller:_,encoder:y,cleanup:o(()=>{this._streamMapping.delete(l);try{_.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(v.id,l));await this.writePrimingEvent(_,y,l,h);for(let v of c){let b,R;Pt(v)&&this._eventStore&&h>="2025-11-25"&&(b=o(()=>{this.closeSSEStream(v.id)},"closeSSEStream"),R=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i,closeSSEStream:b,closeStandaloneSSEStream:R})}return new Response(S,{status:200,headers:w})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(t){let r=this.validateSession(t);if(r)return r;let n=this.validateProtocolVersion(t);return n||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(t){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(new Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=t.headers.get("mcp-session-id");if(!r)return this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.onerror?.(new Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(t){let r=t.headers.get("mcp-protocol-version");if(r!==null&&!ur.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${ur.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${ur.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:t})=>{t()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(t){let r=this._requestToStreamMapping.get(t);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let t=this._streamMapping.get(this._standaloneSseStreamId);t&&t.cleanup()}async send(t,r){let n=r?.relatedRequestId;if((yt(t)||Un(t))&&(n=t.id),n===void 0){if(yt(t)||Un(t))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let s;this._eventStore&&(s=await this._eventStore.storeEvent(this._standaloneSseStreamId,t));let c=this._streamMapping.get(this._standaloneSseStreamId);if(c===void 0)return;c.controller&&c.encoder&&this.writeSSEEvent(c.controller,c.encoder,t,s);return}let a=this._requestToStreamMapping.get(n);if(!a)throw new Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(a);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let s;this._eventStore&&(s=await this._eventStore.storeEvent(a,t)),this.writeSSEEvent(i.controller,i.encoder,t,s)}if(yt(t)||Un(t)){this._requestResponseMap.set(n,t);let s=Array.from(this._requestToStreamMapping.entries()).filter(([d,p])=>p===a).map(([d])=>d);if(s.every(d=>this._requestResponseMap.has(d))){if(!i)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let d={"Content-Type":"application/json"};this.sessionId!==void 0&&(d["mcp-session-id"]=this.sessionId);let p=s.map(l=>this._requestResponseMap.get(l));p.length===1?i.resolveJson(new Response(JSON.stringify(p[0]),{status:200,headers:d})):i.resolveJson(new Response(JSON.stringify(p),{status:200,headers:d}))}else i.cleanup();for(let d of s)this._requestResponseMap.delete(d),this._requestToStreamMapping.delete(d)}}}};function io(e,t){let r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let a=0;a<n;a++)if(!io(e[a],t[a]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;for(let s of n)if(!io(e[s],t[s]))return!1;return!0}return e===t}o(io,"deepCompareStrict");function at(e){return encodeURI(VU(e))}o(at,"encodePointer");function VU(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(VU,"escapePointer");var FU={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},ZU={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},KU={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},JU=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Xt(e,t=Object.create(null),r=JU,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);s.hash.length>1?t[s.href]=e:(s.hash="",n===""?r=s:Xt(e,t,r))}}else if(e!==!0&&e!==!1)return t;let a=r.href+(n?"#"+n:"");if(t[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(t[a]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:a}),e.$ref&&e.__absolute_ref__===void 0){let i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(KU[i])continue;let s=`${n}/${at(i)}`,c=e[i];if(Array.isArray(c)){if(FU[i]){let d=c.length;for(let p=0;p<d;p++)Xt(c[p],t,r,`${s}/${p}`)}}else if(ZU[i])for(let d in c)Xt(c[d],t,r,`${s}/${at(d)}`);else Xt(c,t,r,s)}return t}o(Xt,"dereference");var WU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,YU=[0,31,28,31,30,31,30,31,31,30,31,30,31],QU=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,XU=/^(?=.{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,eO=/^(?:[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,tO=/^(?:(?:[^\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,rO=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,nO=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,oO=/^(?:\/(?:[^~/]|~0|~1)*)*$/,aO=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,iO=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,sO=o(e=>{if(e[0]==='"')return!1;let[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},"EMAIL"),cO=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,uO=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,dO=o(e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),"DURATION");function zt(e){return e.test.bind(e)}o(zt,"bind");var np={date:c_,time:u_.bind(void 0,!1),"date-time":mO,duration:dO,uri:gO,"uri-reference":zt(eO),"uri-template":zt(tO),url:zt(rO),email:sO,hostname:zt(XU),ipv4:zt(cO),ipv6:zt(uO),regex:SO,uuid:zt(nO),"json-pointer":zt(oO),"json-pointer-uri-fragment":zt(aO),"relative-json-pointer":zt(iO)};function lO(e){return e%4===0&&(e%100!==0||e%400===0)}o(lO,"isLeapYear");function c_(e){let t=e.match(WU);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&lO(r)?29:YU[n])}o(c_,"date");function u_(e,t){let r=t.match(QU);if(!r)return!1;let n=+r[1],a=+r[2],i=+r[3],s=!!r[5];return(n<=23&&a<=59&&i<=59||n==23&&a==59&&i==60)&&(!e||s)}o(u_,"time");var pO=/t|\s/i;function mO(e){let t=e.split(pO);return t.length==2&&c_(t[0])&&u_(!0,t[1])}o(mO,"date_time");var fO=/\/|:/,hO=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function gO(e){return fO.test(e)&&hO.test(e)}o(gO,"uri");var yO=/[^\\]\\Z/;function SO(e){if(yO.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(SO,"regex");var d_;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(d_||(d_={}));function l_(e){let t=0,r=e.length,n=0,a;for(;n<r;)t++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=e.charCodeAt(n),(a&64512)==56320&&n++);return t}o(l_,"ucs2length");function he(e,t,r="2019-09",n=Xt(t),a=!0,i=null,s="#",c="#",d=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let p=typeof e,l;switch(p){case"boolean":case"number":case"string":l=p;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${p}" type are not supported.`)}let{$ref:m,$recursiveRef:h,$recursiveAnchor:y,type:_,const:S,enum:w,required:v,not:b,anyOf:R,allOf:M,oneOf:q,if:Me,then:it,else:Sn,format:or,properties:qt,patternProperties:Ur,additionalProperties:po,unevaluatedProperties:mo,minProperties:fo,maxProperties:ec,propertyNames:qp,dependentRequired:tc,dependentSchemas:rc,dependencies:nc,prefixItems:oc,items:ho,additionalItems:Np,unevaluatedItems:jp,contains:Dp,minContains:Nt,maxContains:Da,minItems:ac,maxItems:ic,uniqueItems:bv,minimum:Or,maximum:$r,exclusiveMinimum:go,exclusiveMaximum:yo,multipleOf:Ha,minLength:La,maxLength:Ba,pattern:Hp,__absolute_ref__:Ga,__absolute_recursive_ref__:Rv}=t,k=[];if(y===!0&&i===null&&(i=t),h==="#"){let N=i===null?n[Rv]:i,$=`${c}/$recursiveRef`,L=he(e,i===null?t:i,r,n,a,N,s,$,d);L.valid||k.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:$,error:"A subschema had errors."},...L.errors)}if(m!==void 0){let $=n[Ga||m];if($===void 0){let P=`Unresolved $ref "${m}".`;throw Ga&&Ga!==m&&(P+=` Absolute URI "${Ga}".`),P+=`
44
52
  Known schemas:
45
53
  - ${Object.keys(n).join(`
46
- - `)}`,new Error(P)}let B=`${c}/$ref`,E=fe(e,z,r,n,a,i,s,B,d);if(E.valid||k.push({instanceLocation:s,keyword:"$ref",keywordLocation:B,error:"A subschema had errors."},...E.errors),r==="4"||r==="7")return{valid:k.length===0,errors:k}}if(Array.isArray(_)){let D=_.length,z=!1;for(let B=0;B<D;B++)if(l===_[B]||_[B]==="integer"&&l==="number"&&e%1===0&&e===e){z=!0;break}z||k.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${_.join('", "')}".`})}else _==="integer"?(l!=="number"||e%1||e!==e)&&k.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${_}".`}):_!==void 0&&l!==_&&k.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${_}".`});if(S!==void 0&&(l==="object"||l==="array"?zn(e,S)||k.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`}):e!==S&&k.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`})),w!==void 0&&(l==="object"||l==="array"?w.some(D=>zn(e,D))||k.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`}):w.some(D=>e===D)||k.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`})),b!==void 0){let D=`${c}/not`;fe(e,b,r,n,a,i,s,D).valid&&k.push({instanceLocation:s,keyword:"not",keywordLocation:D,error:'Instance matched "not" schema.'})}let qa=[];if(R!==void 0){let D=`${c}/anyOf`,z=k.length,B=!1;for(let E=0;E<R.length;E++){let P=R[E],H=Object.create(d),j=fe(e,P,r,n,a,y===!0?i:null,s,`${D}/${E}`,H);k.push(...j.errors),B=B||j.valid,j.valid&&qa.push(H)}B?k.length=z:k.splice(z,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:D,error:"Instance does not match any subschemas."})}if(q!==void 0){let D=`${c}/allOf`,z=k.length,B=!0;for(let E=0;E<q.length;E++){let P=q[E],H=Object.create(d),j=fe(e,P,r,n,a,y===!0?i:null,s,`${D}/${E}`,H);k.push(...j.errors),B=B&&j.valid,j.valid&&qa.push(H)}B?k.length=z:k.splice(z,0,{instanceLocation:s,keyword:"allOf",keywordLocation:D,error:"Instance does not match every subschema."})}if(N!==void 0){let D=`${c}/oneOf`,z=k.length,B=N.filter((E,P)=>{let H=Object.create(d),j=fe(e,E,r,n,a,y===!0?i:null,s,`${D}/${P}`,H);return k.push(...j.errors),j.valid&&qa.push(H),j.valid}).length;B===1?k.length=z:k.splice(z,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:D,error:`Instance does not match exactly one subschema (${B} matches).`})}if((l==="object"||l==="array")&&Object.assign(d,...qa),qe!==void 0){let D=`${c}/if`;if(fe(e,qe,r,n,a,i,s,D,d).valid){if(it!==void 0){let B=fe(e,it,r,n,a,i,s,`${c}/then`,d);B.valid||k.push({instanceLocation:s,keyword:"if",keywordLocation:D,error:'Instance does not match "then" schema.'},...B.errors)}}else if(dn!==void 0){let B=fe(e,dn,r,n,a,i,s,`${c}/else`,d);B.valid||k.push({instanceLocation:s,keyword:"if",keywordLocation:D,error:'Instance does not match "else" schema.'},...B.errors)}}if(l==="object"){if(v!==void 0)for(let E of v)E in e||k.push({instanceLocation:s,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${E}".`});let D=Object.keys(e);if(io!==void 0&&D.length<io&&k.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${io} properties.`}),Zs!==void 0&&D.length>Zs&&k.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${Zs} properties.`}),kp!==void 0){let E=`${c}/propertyNames`;for(let P in e){let H=`${s}/${at(P)}`,j=fe(P,kp,r,n,a,i,H,E);j.valid||k.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:E,error:`Property name "${P}" does not match schema.`},...j.errors)}}if(Ks!==void 0){let E=`${c}/dependantRequired`;for(let P in Ks)if(P in e){let H=Ks[P];for(let j of H)j in e||k.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:E,error:`Instance has "${P}" but does not have "${j}".`})}}if(Ws!==void 0)for(let E in Ws){let P=`${c}/dependentSchemas`;if(E in e){let H=fe(e,Ws[E],r,n,a,i,s,`${P}/${at(E)}`,d);H.valid||k.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:P,error:`Instance has "${E}" but does not match dependant schema.`},...H.errors)}}if(Js!==void 0){let E=`${c}/dependencies`;for(let P in Js)if(P in e){let H=Js[P];if(Array.isArray(H))for(let j of H)j in e||k.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${P}" but does not have "${j}".`});else{let j=fe(e,H,r,n,a,i,s,`${E}/${at(P)}`);j.valid||k.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${P}" but does not match dependant schema.`},...j.errors)}}}let z=Object.create(null),B=!1;if(qt!==void 0){let E=`${c}/properties`;for(let P in qt){if(!(P in e))continue;let H=`${s}/${at(P)}`,j=fe(e[P],qt[P],r,n,a,i,H,`${E}/${at(P)}`);if(j.valid)d[P]=z[P]=!0;else if(B=a,k.push({instanceLocation:s,keyword:"properties",keywordLocation:E,error:`Property "${P}" does not match schema.`},...j.errors),B)break}}if(!B&&Tr!==void 0){let E=`${c}/patternProperties`;for(let P in Tr){let H=new RegExp(P,"u"),j=Tr[P];for(let Ze in e){if(!H.test(Ze))continue;let $p=`${s}/${at(Ze)}`,zp=fe(e[Ze],j,r,n,a,i,$p,`${E}/${at(P)}`);zp.valid?d[Ze]=z[Ze]=!0:(B=a,k.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:E,error:`Property "${Ze}" matches pattern "${P}" but does not match associated schema.`},...zp.errors))}}}if(!B&&oo!==void 0){let E=`${c}/additionalProperties`;for(let P in e){if(z[P])continue;let H=`${s}/${at(P)}`,j=fe(e[P],oo,r,n,a,i,H,E);j.valid?d[P]=!0:(B=a,k.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:E,error:`Property "${P}" does not match additional properties schema.`},...j.errors))}}else if(!B&&ao!==void 0){let E=`${c}/unevaluatedProperties`;for(let P in e)if(!d[P]){let H=`${s}/${at(P)}`,j=fe(e[P],ao,r,n,a,i,H,E);j.valid?d[P]=!0:k.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:E,error:`Property "${P}" does not match unevaluated properties schema.`},...j.errors)}}}else if(l==="array"){Xs!==void 0&&e.length>Xs&&k.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${Xs}).`}),Qs!==void 0&&e.length<Qs&&k.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${Qs}).`});let D=e.length,z=0,B=!1;if(Ys!==void 0){let E=`${c}/prefixItems`,P=Math.min(Ys.length,D);for(;z<P;z++){let H=fe(e[z],Ys[z],r,n,a,i,`${s}/${z}`,`${E}/${z}`);if(d[z]=!0,!H.valid&&(B=a,k.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:E,error:"Items did not match schema."},...H.errors),B))break}}if(so!==void 0){let E=`${c}/items`;if(Array.isArray(so)){let P=Math.min(so.length,D);for(;z<P;z++){let H=fe(e[z],so[z],r,n,a,i,`${s}/${z}`,`${E}/${z}`);if(d[z]=!0,!H.valid&&(B=a,k.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...H.errors),B))break}}else for(;z<D;z++){let P=fe(e[z],so,r,n,a,i,`${s}/${z}`,E);if(d[z]=!0,!P.valid&&(B=a,k.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...P.errors),B))break}if(!B&&Tp!==void 0){let P=`${c}/additionalItems`;for(;z<D;z++){let H=fe(e[z],Tp,r,n,a,i,`${s}/${z}`,P);d[z]=!0,H.valid||(B=a,k.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:P,error:"Items did not match additional items schema."},...H.errors))}}}if(Up!==void 0)if(D===0&&Nt===void 0)k.push({instanceLocation:s,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Nt!==void 0&&D<Nt)k.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${D}) than minContains (${Nt}).`});else{let E=`${c}/contains`,P=k.length,H=0;for(let j=0;j<D;j++){let Ze=fe(e[j],Up,r,n,a,i,`${s}/${j}`,E);Ze.valid?(d[j]=!0,H++):k.push(...Ze.errors)}H>=(Nt||0)&&(k.length=P),Nt===void 0&&Ua===void 0&&H===0?k.splice(P,0,{instanceLocation:s,keyword:"contains",keywordLocation:E,error:"Array does not contain item matching schema."}):Nt!==void 0&&H<Nt?k.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${Nt} items matching schema. Only ${H} items were found.`}):Ua!==void 0&&H>Ua&&k.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${Ua} items matching schema. ${H} items were found.`})}if(!B&&Ep!==void 0){let E=`${c}/unevaluatedItems`;for(z;z<D;z++){if(d[z])continue;let P=fe(e[z],Ep,r,n,a,i,`${s}/${z}`,E);d[z]=!0,P.valid||k.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:E,error:"Items did not match unevaluated items schema."},...P.errors)}}if(Sv)for(let E=0;E<D;E++){let P=e[E],H=typeof P=="object"&&P!==null;for(let j=0;j<D;j++){if(E===j)continue;let Ze=e[j];(P===Ze||H&&(typeof Ze=="object"&&Ze!==null)&&zn(P,Ze))&&(k.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${E} and ${j}.`}),E=Number.MAX_SAFE_INTEGER,j=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(Er!==void 0&&(co===!0&&e<=Er||e<Er)&&k.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${co?"or equal to ":""} ${Er}.`}),Ur!==void 0&&(uo===!0&&e>=Ur||e>Ur)&&k.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${uo?"or equal to ":""} ${Ur}.`})):(Er!==void 0&&e<Er&&k.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Er}.`}),Ur!==void 0&&e>Ur&&k.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${Ur}.`}),co!==void 0&&e<=co&&k.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${co}.`}),uo!==void 0&&e>=uo&&k.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${uo}.`})),Oa!==void 0){let D=e%Oa;Math.abs(0-D)>=11920929e-14&&Math.abs(Oa-D)>=11920929e-14&&k.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Oa}.`})}}else if(l==="string"){let D=$a===void 0&&za===void 0?0:tg(e);$a!==void 0&&D<$a&&k.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${D} < ${$a}).`}),za!==void 0&&D>za&&k.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${D} > ${za}).`}),Op!==void 0&&!new RegExp(Op,"u").test(e)&&k.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),ar!==void 0&&Td[ar]&&!Td[ar](e)&&k.push({instanceLocation:s,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${ar}".`})}return{valid:k.length===0,errors:k}}o(fe,"validate");var ji=class{static{o(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=Kt(t)}validate(t){return fe(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),Kt(t,this.lookup)}};var Mn=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let r=new ji(t,this.draft,this.shortcircuit);return n=>{let a=r.validate(n);return a.valid?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:a.errors.map(i=>`${i.instanceLocation}: ${i.error}`).join("; ")}}}};function Ed(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(Ed,"truncate");function rg(e){return"cause"in e?e.cause:void 0}o(rg,"readCause");function Oe(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=Ed(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=Ed(r.message);let n=rg(r);for(let a=1;a<=4&&n instanceof Error;a+=1){let i=a===1?"cause":`cause${a}`;e[`${i}Name`]=n.name,e[`${i}Message`]=Ed(n.message),n=rg(n)}}o(Oe,"addErrorLogFields");function mt(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}o(mt,"safeHost");function ng(e,t){let r=Object.entries(t).filter(n=>n[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}o(ng,"setLogProperties");function Ud(e,t){ng(e,{subjectId:t.subjectId})}o(Ud,"applyGatewayPrincipalLogProperties");function og(e,t){ng(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(og,"applyGatewayRouteLogProperties");var qn={runtime:{invalid_request:{code:"invalid_request",seam:"runtime",status:400,title:"Bad Request",publicDetail:"The request did not match the route contract.",oauthError:"invalid_request"},forbidden:{code:"forbidden",seam:"runtime",status:403,title:"Forbidden",publicDetail:"The request is not allowed.",oauthError:"invalid_request"},not_found:{code:"not_found",seam:"runtime",status:404,title:"Not Found",publicDetail:"The requested resource was not found.",oauthError:"invalid_request"},internal_server_error:{code:"internal_server_error",seam:"runtime",status:500,title:"Internal Server Error",publicDetail:"The gateway failed to process the request.",oauthError:"server_error"}},config:{virtual_server_not_enabled:{code:"virtual_server_not_enabled",seam:"config",status:404,title:"Not Found",publicDetail:"The requested virtual server is not enabled."},unknown_upstream_server:{code:"unknown_upstream_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream server is not configured.",oauthError:"invalid_request"},unknown_virtual_server:{code:"unknown_virtual_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server is not configured.",oauthError:"invalid_target"},unknown_auth_profile:{code:"unknown_auth_profile",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream auth profile is not configured.",oauthError:"invalid_request"},virtual_server_upstream_mismatch:{code:"virtual_server_upstream_mismatch",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server does not belong to the selected upstream server.",oauthError:"invalid_request"}},downstream_auth:{authentication_required:{code:"authentication_required",seam:"downstream_auth",status:401,title:"Unauthorized",publicDetail:"Authentication is required to access this route.",oauthError:"invalid_client"},identity_context_missing:{code:"identity_context_missing",seam:"downstream_auth",status:403,title:"Forbidden",publicDetail:"Authenticated requests must include a gateway principal subject.",oauthError:"invalid_request"}},downstream_oauth:{browser_login_verification_failed:{code:"browser_login_verification_failed",seam:"downstream_oauth",status:400,title:"Connection failed",publicDetail:"The gateway could not verify the browser login response. Retry the login flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_auth:{provider_access_denied:{code:"provider_access_denied",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream authorization request was denied. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_invalid:{code:"oauth_state_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request could not be verified. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_expired:{code:"oauth_state_expired",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request expired. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_reused:{code:"oauth_state_reused",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"This upstream connection request was already used. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_callback_mismatch:{code:"oauth_callback_mismatch",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream callback did not match the initiating connection request.",callbackFailure:!0,oauthError:"invalid_request"},upstream_token_exchange_failed:{code:"upstream_token_exchange_failed",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The gateway could not complete the upstream token exchange. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"},upstream_client_registration_required:{code:"upstream_client_registration_required",seam:"upstream_auth",status:400,title:"Upstream OAuth client registration required",publicDetail:"The upstream authorization server supports neither gateway-hosted Client ID Metadata Documents nor Dynamic Client Registration. Register an upstream OAuth client manually before retrying.",oauthError:"invalid_request"},upstream_token_response_invalid:{code:"upstream_token_response_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream token response was invalid. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_mcp:{upstream_capability_invocation_failed:{code:"upstream_capability_invocation_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability invocation failed. Retry later or reconnect the upstream if the issue persists."},upstream_import_failed:{code:"upstream_import_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability import failed. Retry later or reconnect the upstream if the issue persists."}}},ag={...qn.runtime,...qn.config,...qn.downstream_auth,...qn.downstream_oauth,...qn.upstream_auth,...qn.upstream_mcp};function Xo(e){return typeof e=="string"&&Object.hasOwn(ag,e)}o(Xo,"isGatewayProblemCode");function Hi(e){return Xo(e)&&Qe(e).callbackFailure===!0}o(Hi,"isGatewayCallbackFailureCode");function Qe(e){return ag[e]}o(Qe,"readGatewayProblemDefinition");function Od(e){switch(e){case 400:return"invalid_request";case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";default:return"internal_server_error"}}o(Od,"readDefaultGatewayProblemCodeForStatus");var ig="gatewayCode";function sg(e){let t=Qe(e);return{title:t.title,body:t.publicDetail}}o(sg,"readGatewayCallbackFailureContent");function he(e){if(!(e instanceof ln))return;let t=e.extensionMembers?.[ig];return Xo(t)?t:void 0}o(he,"readGatewayProblemCode");function g(e,t,r){let n=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...r===void 0?{}:{cause:r}}:e,a=Qe(n.code),i=n.privateDetail??(Li(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),s=dk(n);return new ln({message:i,extensionMembers:{[ig]:n.code}},s===void 0?void 0:{cause:s})}o(g,"createGatewayRuntimeError");async function ft(e,t,r){let n=Qe(r.code),a=lk(r.code,r.detail),i=Li(r.code)?r.title??n.title:n.title,c={problem:{...po.getProblemFromStatus(n.status,{detail:a,instance:r.instance,type:r.type}),...r.extensions??{},status:n.status,title:i,detail:a,code:r.code}};return r.headers!==void 0&&(c.additionalHeaders=r.headers),po.format(c,e,t)}o(ft,"gatewayProblemResponse");function Li(e){return Qe(e).status<500}o(Li,"canExposeGatewayProblemDetail");function dk(e){return!e.privateDetail||Li(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o(dk,"readRuntimeErrorCause");function lk(e,t){let r=Qe(e);return Li(e)&&t||r.publicDetail}o(lk,"readSafeGatewayProblemDetail");ue();var pk=["shared-oauth","user_oauth","static_secret","user-secret","shared-secret"],mk=["none","client_secret_basic","client_secret_post"],Xe=u.string().min(1).brand(),Pe=u.string().min(1).brand(),et=u.string().min(1).brand(),Ot=u.string().min(1).brand(),Bi=u.enum(pk),$d=u.enum(mk),Gi=u.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),zd=u.object({name:Gi,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict();var Md=new Map;function Vi(e){Md.set(e.policyType,e)}o(Vi,"registerMcpAuthorizationPolicy");function qd(e){if(e!==void 0)return Md.get(e)}o(qd,"getMcpAuthorizationPolicy");function Fi(e){return qd(e)!==void 0}o(Fi,"isRegisteredMcpAuthorizationPolicyType");function Nd(){return[...Md.keys()]}o(Nd,"listMcpAuthorizationPolicyTypes");ue();var dg=Xe,fk=u.object({mode:u.literal("auto")}).strict(),hk=u.object({mode:u.literal("manual"),clientId:u.string().trim().min(1),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:$d.default("client_secret_basic")}).strict().superRefine((e,t)=>{e.tokenEndpointAuthMethod!=="none"&&!e.clientSecret&&t.addIssue({code:u.ZodIssueCode.custom,message:`${e.tokenEndpointAuthMethod} requires clientSecret`,path:["clientSecret"]})}),lg=u.discriminatedUnion("mode",[fk,hk]),gk=lg.default({mode:"auto"}),Dd=u.object({scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:gk}).strict(),cg=Dd.extend({redirectPath:u.string().startsWith("/auth/connections/")}).strict(),pg=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),yk=new Set([...pg,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),Sk=u.object({kind:u.literal("bearer_token"),token:u.string().min(1)}).strict(),_k=u.object({kind:u.literal("headers"),headers:u.array(u.object({name:Gi,value:u.string().min(1)}).strict()).min(1)}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.headers.entries()){let i=a.name.toLowerCase();pg.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Header ${a.name} is not allowed for static secret injection`,path:["headers",n,"name"]}),r.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Duplicate static secret header ${a.name}`,path:["headers",n,"name"]}),r.add(i)}}),jd=u.discriminatedUnion("kind",[Sk,_k]),wk=u.object({kind:u.literal("basic_auth_app_password"),usernameLabel:u.string().min(1).default("Username"),passwordLabel:u.string().min(1).default("App password")}).strict(),vk=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key"),capture:u.enum(["browser_login"]).optional()}).strict(),Hd=u.discriminatedUnion("kind",[wk,vk]),Ld=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key")}).strict(),bk=u.discriminatedUnion("mode",[u.object({mode:u.literal("shared-oauth"),oauth:cg}).strict(),u.object({mode:u.literal("user_oauth"),oauth:cg}).strict(),u.object({mode:u.literal("static_secret"),secret:jd}).strict(),u.object({mode:u.literal("user-secret"),secret:Hd}).strict(),u.object({mode:u.literal("shared-secret"),secret:Ld}).strict()]),Rk=u.object({baseUrl:u.url(),resourceMetadataUrl:u.url(),requestHeaders:u.array(zd).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let i=a.name.toLowerCase();yk.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Header ${a.name} is not allowed for native MCP transport request headers`,path:["requestHeaders",n,"name"]}),r.has(i)&&t.addIssue({code:u.ZodIssueCode.custom,message:`Duplicate native MCP transport request header ${a.name}`,path:["requestHeaders",n,"name"]}),r.add(i)}}),VG=u.object({displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:hn.optional(),authProfiles:u.record(et,bk),transport:Rk}).strict().superRefine((e,t)=>{Object.keys(e.authProfiles).length===0&&t.addIssue({code:u.ZodIssueCode.custom,message:"authProfiles must contain at least one profile",path:["authProfiles"]})}),Ck=u.object({"shared-oauth":Dd.optional(),user_oauth:Dd.optional(),static_secret:u.object({secret:jd}).strict().optional(),"user-secret":u.object({secret:Hd}).strict().optional(),"shared-secret":u.object({secret:Ld}).strict().optional()}).strict().superRefine((e,t)=>{Object.values(e).every(r=>r===void 0)&&t.addIssue({code:u.ZodIssueCode.custom,message:"authProfiles must contain at least one upstream auth profile"})}),ug=u.object({id:dg,displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:hn.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url(),requestHeaders:u.array(zd).default([]),authProfiles:Ck}).strict(),Ik=u.object({name:Gi,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict(),Zi={id:dg.optional(),displayName:u.string().min(1),summary:u.string().min(1).optional(),serverInfo:hn.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url().optional(),requestHeaders:u.array(Ik).default([])},Pk=u.discriminatedUnion("authMode",[u.object({...Zi,authMode:u.enum(["shared-oauth","user_oauth"]),scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:lg.optional(),clientId:u.string().trim().min(1).optional(),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:$d.optional()}).strict(),u.object({...Zi,authMode:u.literal("static_secret"),secret:jd}).strict(),u.object({...Zi,authMode:u.literal("user-secret"),secret:Hd}).strict(),u.object({...Zi,authMode:u.literal("shared-secret"),secret:Ld}).strict()]);function mg(e){throw g("internal_server_error",e)}o(mg,"throwGatewayConfigError");function xk(e){let t="mcp-upstream-";return e.startsWith(t)||mg(`Upstream policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`),Xe.parse(e.slice(t.length))}o(xk,"inferUpstreamConnectionIdFromPolicyName");function Ak(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}o(Ak,"buildDefaultProtectedResourceMetadataUrl");function Nn(e,t){return et.parse(`${e}:${t}`)}o(Nn,"buildUpstreamAuthProfileId");function Ki(e,t){let r=ug.safeParse(e);if(r.success)return r.data;let n=Pk.parse(e),a=n.id??(t===void 0?void 0:xk(t));a===void 0&&mg("Upstream policy options must include id when policy name is unavailable.");let i=n.requestHeaders.map(c=>({name:c.name,value:c.value,required:c.required})),s=(()=>{switch(n.authMode){case"shared-oauth":case"user_oauth":{let c=n.clientRegistration??(n.clientId===void 0?{mode:"auto"}:{mode:"manual",clientId:n.clientId,...n.clientSecret===void 0?{}:{clientSecret:n.clientSecret},...n.tokenEndpointAuthMethod===void 0?{}:{tokenEndpointAuthMethod:n.tokenEndpointAuthMethod}});return{[n.authMode]:{scopes:n.scopes,scopeDelimiter:n.scopeDelimiter,clientRegistration:c}}}case"static_secret":case"user-secret":case"shared-secret":return{[n.authMode]:{secret:n.secret}}}})();return ug.parse({id:a,displayName:n.displayName,...n.summary===void 0?{}:{description:n.summary},...n.serverInfo===void 0?{}:{serverInfo:n.serverInfo},mcpUrl:n.mcpUrl,protectedResourceMetadataUrl:n.protectedResourceMetadataUrl??Ak(n.mcpUrl),requestHeaders:i,authProfiles:s})}o(Ki,"parseUpstreamConnectionPolicyOptions");function fg(e){return e.mode==="shared-oauth"||e.mode==="user_oauth"}o(fg,"isUpstreamOAuthAuthConfig");ue();var kk=u.looseObject({name:u.string().min(1),version:u.string().min(1).optional()}),Tk=u.looseObject({}),Ek=u.looseObject({name:Ot,namespace:Ot.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional(),inputSchema:Tk}),Uk=u.looseObject({name:Ot,namespace:Ot.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional()}),Ok=u.looseObject({name:Ot,uri:u.string().min(1),upstreamPolicy:u.string().min(1).optional(),upstreamUri:u.string().min(1).optional(),enabled:u.boolean().optional()}),$k=u.enum(["openapi","upstream_mcp"]),zk=u.object({catalogSource:$k.default("openapi"),serverInfo:kk.optional(),tools:u.array(Ek).default([]),prompts:u.array(Uk).default([]),resources:u.array(Ok).default([])}).strict();function hg(e){return zk.parse(e??{})}o(hg,"parseVirtualServerRouteOptions");function Wi(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Wi,"toMcpTool");function Ji(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Ji,"toMcpPrompt");function Yi(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o(Yi,"toMcpResource");var Mk="mcp-upstream-connection-inbound",gg="/mcp/";function He(e){throw new Or(e)}o(He,"throwRegistryError");function yg(e){return e.policyType===Mk}o(yg,"isUpstreamConnectionPolicy");function qk(e){return Fi(e.policyType)}o(qk,"isMcpOAuthInboundPolicy");function Nk(e){e.startsWith(gg)||He(`MCP virtual server route ${e} must use a /mcp/{virtualServerId} path.`);let t=e.slice(gg.length);return(!t||t.includes("/"))&&He(`MCP virtual server route ${e} must use exactly one /mcp/{virtualServerId} path segment.`),Pe.parse(t)}o(Nk,"readVirtualServerIdFromPath");function Dk(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&He(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&He(`Upstream policy ${e.policyName} does not declare an auth mode.`),Bi.parse(r)}o(Dk,"readSingleAuthMode");function jk(e){let t=e.connection.authProfiles[e.authMode];t||He(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=`/auth/connections/${encodeURIComponent(e.connection.id)}/callback`;switch(e.authMode){case"shared-oauth":case"user_oauth":{let n=t;return{mode:e.authMode,oauth:{scopes:n.scopes,scopeDelimiter:n.scopeDelimiter,redirectPath:r,clientRegistration:n.clientRegistration}}}case"static_secret":return{mode:"static_secret",secret:t.secret};case"user-secret":return{mode:"user-secret",secret:t.secret};case"shared-secret":return{mode:"shared-secret",secret:t.secret}}}o(jk,"buildResolvedAuthConfig");function Hk(e){let t=Dk({policyName:e.policyName,connection:e.connection}),r=Nn(e.connection.id,t),n=jk({connection:e.connection,authMode:t,authProfileId:r}),a={displayName:e.connection.displayName,...e.connection.description===void 0?{}:{description:e.connection.description},...e.connection.serverInfo===void 0?{}:{serverInfo:e.connection.serverInfo},authProfiles:{[r]:n},transport:{baseUrl:e.connection.mcpUrl,resourceMetadataUrl:e.connection.protectedResourceMetadataUrl,requestHeaders:e.connection.requestHeaders}};return{policyName:e.policyName,upstreamServerId:e.connection.id,config:a,authMode:t,authProfileId:r,authConfig:n}}o(Hk,"buildRegisteredConnection");function Lk(e){let t=new Map;for(let r of e)t.has(r.name)&&He(`Duplicate policy name ${r.name} in policies.json.`),t.set(r.name,{name:r.name,policyType:r.policyType,handler:{options:r.handler.options}});return t}o(Lk,"buildPolicyMap");function Bk(e){let t=new Map,r=new Set;for(let n of e.values()){if(!yg(n))continue;let a=Ki(n.handler.options,n.name);r.has(a.id)&&He(`Duplicate upstream MCP connection id ${a.id} in policies.json.`),r.add(a.id);let i=Hk({policyName:n.name,connection:a});t.set(n.name,i)}return t}o(Bk,"buildConnectionsByPolicyName");function Gk(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(Gk,"readOperationId");function Sg(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`;try{return Ot.parse(t)}catch{He(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`)}}o(Sg,"buildPublishedCapabilityName");function Gd(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||He(`MCP virtual server route ${e.routePath} declares capability ${e.capabilityName} for upstream policy ${e.authoredPolicyName}, but that policy is not bound to the route.`),e.authoredPolicyName;if(e.connections.length===1)return e.connections[0]?.policyName;He(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o(Gd,"readCapabilityUpstreamPolicy");function Bd(e){e.seen.has(e.key)&&He(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(Bd,"assertUniqueCatalogKey");function Vk(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=Sg({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:Gd({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(Vk,"normalizeCatalogTool");function Fk(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=Sg({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:Gd({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(Fk,"normalizeCatalogPrompt");function Zk(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:Gd({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o(Zk,"normalizeCatalogResource");function Kk(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>Vk({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>Fk({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>Zk({resource:d,connections:e.connections,routePath:e.routePath})),i=new Set;for(let d of r)Bd({kind:"tool",key:d.name,routePath:e.routePath,seen:i});let s=new Set;for(let d of n)Bd({kind:"prompt",key:d.name,routePath:e.routePath,seen:s});let c=new Set;for(let d of a)Bd({kind:"resource",key:String(d.uri),routePath:e.routePath,seen:c});return{catalogSource:t,...e.catalog.serverInfo===void 0?{}:{serverInfo:e.catalog.serverInfo},tools:r,prompts:n,resources:a}}o(Kk,"normalizeVirtualServerCatalog");function Wk(e){let t=new Map,r=new Set;for(let n of e.routes){let a=n.policies?.inbound??[];if(a.length===0)continue;let i=a[0],s=i===void 0?void 0:e.policyByName.get(i);if(!s||!qk(s))continue;let c=Gk(n);c||He(`MCP virtual server route ${n.path} must declare an operationId in routes.oas.json.`),r.has(c)&&He(`Duplicate MCP virtual server operationId ${c} across routes.`),r.add(c);let d=Nk(n.path);t.has(d)&&He(`Duplicate MCP virtual server id ${d} across routes.`);let p=[];for(let h of a.slice(1)){let y=e.policyByName.get(h);if(!y||!yg(y))continue;let _=e.connectionsByPolicyName.get(h);_||He(`Upstream connection policy ${h} referenced by route ${n.path} could not be resolved.`),p.push(_)}let l=hg(n.handler.options),m=Kk({catalog:l,connections:p,routePath:n.path});m.catalogSource==="upstream_mcp"&&p.length!==1&&He(`MCP virtual server route ${n.path} uses upstream MCP catalog mode but declares ${p.length} upstream bindings; upstream MCP catalog mode requires exactly one upstream binding.`),t.set(d,{virtualServerId:d,operationId:c,routePath:n.path,handlerExport:n.handler.export,serverInfo:m.serverInfo,catalog:m,connections:p})}return t}o(Wk,"buildVirtualServers");function _g(e){let t=Lk(e.policies),r=Bk(t),n=Wk({routes:e.routes,policyByName:t,connectionsByPolicyName:r}),a=new Map;for(let i of r.values())a.set(i.upstreamServerId,i);return{byVirtualServerId:n,connectionsById:a}}o(_g,"buildGatewayConnectionRegistry");var Qi;function wg(e){Qi=e}o(wg,"setGatewayConnectionRegistry");function ht(){if(!Qi)throw g("internal_server_error","MCP gateway connection registry has not been initialized. Ensure routes.oas.json declares at least one MCP virtual server route and policies.json registers an `mcp-oauth-inbound` (or wrapper) policy.");return Qi}o(ht,"getGatewayConnectionRegistry");function vg(e){let t=ht().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown MCP virtual server: ${e}`);return t}o(vg,"getRegisteredVirtualServer");function ea(e){let t=ht().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(ea,"requireRegisteredVirtualServer");function bg(){return Qi}o(bg,"tryGetGatewayConnectionRegistry");var Rg=new Dt("gateway-route");function Cg(e,t){Rg.set(e,t)}o(Cg,"setGatewayRouteContext");function ta(e){return Rg.get(e)}o(ta,"readGatewayRouteContext");function Dn(e){let t=ta(e);if(!t)throw g("internal_server_error","Gateway route context has not been set");return t}o(Dn,"requireGatewayRouteContext");var Fr="2025-06-18";var Jk=new Set(["localhost","::1"]);function gt(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(gt,"normalizeHostname");function Le(e){let t=gt(e.hostname);return e.protocol==="http:"&&(Jk.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(Le,"isLoopbackHttpUrl");function se(e){return new URL(e).origin}o(se,"readGatewayRequestOrigin");import{metrics as Yk,context as Xi,propagation as Pg,SpanKind as xg,SpanStatusCode as Vd,trace as ra}from"@opentelemetry/api";var Qk="mcp-gateway",Xk="mcp-gateway",eT=Fr,tT="2.0",Ag=ra.getTracer(Qk),Fd=Yk.getMeter(Xk),rT=Fd.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),nT=Fd.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),oT=Fd.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),aT=["traceparent","tracestate","baggage"];function Zd(){return performance.now()/1e3}o(Zd,"nowSeconds");function kg(e,t){t(Math.max(Zd()-e,0))}o(kg,"recordDurationSeconds");function Ig(e){return e===void 0?void 0:String(e)}o(Ig,"stringifyAttribute");function $e(e,t,r){r!==void 0&&(e[t]=r)}o($e,"assignAttribute");function iT(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o(iT,"readTargetName");function Tg(e){let t=iT({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(Tg,"buildMcpOperationSpanName");function Kd(e){let t={"mcp.method.name":e.methodName};return $e(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??tT),$e(t,"jsonrpc.request.id",Ig(e.jsonRpcRequestId)),$e(t,"mcp.protocol.version",e.mcpProtocolVersion??eT),$e(t,"mcp.session.id",e.mcpSessionId),$e(t,"mcp.resource.uri",e.resourceUri),$e(t,"rpc.response.status_code",Ig(e.rpcResponseStatusCode)),$e(t,"error.type",e.errorType),e.capabilityType==="tool"&&($e(t,"gen_ai.operation.name","execute_tool"),$e(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&$e(t,"gen_ai.prompt.name",e.capabilityName),$e(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),$e(t,"network.protocol.version",e.networkProtocolVersion),$e(t,"network.transport",e.networkTransport),$e(t,"server.address",e.serverAddress),$e(t,"server.port",e.serverPort),$e(t,"client.address",e.clientAddress),$e(t,"client.port",e.clientPort),t}o(Kd,"buildMcpOperationAttributes");function sT(e){let t=Kd({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(sT,"buildMcpSessionAttributes");function Eg(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:Vd.ERROR}),t instanceof Error&&e.recordException(t)}o(Eg,"setSpanError");function Ug(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o(Ug,"readErrorType");function cT(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?Xi.active():Pg.extract(Xi.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(cT,"readServerParentContext");function uT(e){let t=ra.getSpanContext(Xi.active()),r=ra.getSpanContext(e);if(!(!t||!ra.isSpanContextValid(t))&&!(r&&ra.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(uT,"readAmbientSpanLink");function Og(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(Og,"readResultErrorType");async function Zr(e,t){let r=Zd(),n=Kd({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return Ag.startActiveSpan(Tg(e),{kind:xg.CLIENT,attributes:n},async a=>{try{let i=await t(),s=Og(i);return s&&(a.setAttribute("error.type",s),a.setStatus({code:Vd.ERROR}),n["error.type"]=s),i}catch(i){let s=e.errorType??Ug(i);throw n["error.type"]=s,Eg(a,i,s),i}finally{kg(r,i=>{rT.record(i,n)}),a.end()}})}o(Zr,"runMcpClientOperation");async function Kr(e,t){let r=Zd(),n=cT(e.params),a=Kd({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),i=uT(n);return Ag.startActiveSpan(Tg(e),{kind:xg.SERVER,attributes:a,...i?{links:i}:{}},n,async s=>{try{let c=await t(),d=Og(c);return d&&(s.setAttribute("error.type",d),s.setStatus({code:Vd.ERROR}),a["error.type"]=d),c}catch(c){let d=e.errorType??Ug(c);throw a["error.type"]=d,Eg(s,c,d),c}finally{kg(r,c=>{nT.record(c,a)}),s.end()}})}o(Kr,"runMcpServerOperation");function $g(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return Pg.inject(Xi.active(),t._meta,{set(r,n,a){aT.includes(n)&&(r[n]=a)}}),t}o($g,"injectMcpTraceContextIntoParams");function zg(e,t){let r=sT({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});oT.record(Math.max(t,0),r)}o(zg,"recordMcpClientSessionDuration");var Wd=new Dt("route-upstream-bindings");function dT(e){let t=Wd.get(e);if(t)return t;let r={bindings:[]};return Wd.set(e,r),r}o(dT,"readOrCreateRouteUpstreamBindingRegistry");function Mg(e){return`${e.upstreamServerId}:${e.authProfileId}`}o(Mg,"buildRouteBindingDuplicateKey");function Jd(e,t){let r=dT(e),n=Mg(t);if(r.bindings.find(i=>Mg(i)===n)!==void 0)throw g("internal_server_error",`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.bindings.push(t)}o(Jd,"appendResolvedUpstreamBindingContext");function qg(e){return Wd.get(e)?.bindings??[]}o(qg,"readResolvedUpstreamBindingContexts");ue();var Q=u.string().datetime({offset:!0}).brand();function ne(e){return Q.parse(e.toISOString())}o(ne,"toIsoTimestamp");function Wt(e,t){return new Date(e.getTime()+t*1e3)}o(Wt,"addSeconds");ue();var na=u.string().trim().min(1),oa={accessTokenTtlSeconds:900,refreshTokenTtlSeconds:2592e3,cimdEnabled:!0},lT=u.object({issuer:u.url(),jwksUrl:u.url(),audience:na}),pT=u.object({url:u.url(),tokenUrl:u.url().optional(),clientId:na.optional(),clientSecret:na.optional(),scope:na.default("openid profile email"),audience:na.optional(),remoteTimeoutMs:u.coerce.number().int().positive().default(1e4),stateTtlSeconds:u.coerce.number().int().positive().default(900),sessionTtlSeconds:u.coerce.number().int().positive().default(28800)}).strict(),mT=u.object({accessTokenTtlSeconds:u.coerce.number().int().positive().default(oa.accessTokenTtlSeconds),refreshTokenTtlSeconds:u.coerce.number().int().positive().default(oa.refreshTokenTtlSeconds),cimdEnabled:u.boolean().default(oa.cimdEnabled)}).strict().default(oa),fT=u.object({oidc:lT,browserLogin:pT,gateway:mT.optional().default(oa)}).strict();function Ng(e){return hT(e.browserLogin.url)?"local_dev":"federated_oidc"}o(Ng,"readBrowserLoginKind");function hT(e){let t;try{t=new URL(e)}catch{return!1}return Le(t)&&t.pathname==="/oauth/dev-login"}o(hT,"isLoopbackDevLoginUrl");function es(e){return fT.parse(e)}o(es,"parseMcpOAuthRuntimeConfig");var Yd;function Dg(e){Yd=e}o(Dg,"setGatewayOAuthConfig");function xe(){if(!Yd)throw g("internal_server_error","MCP gateway OAuth config has not been initialized. An `mcp-oauth-inbound` policy (or a provider-specific wrapper such as `mcp-auth0-oauth-inbound`) must be registered in policies.json so the gateway can derive its OAuth runtime configuration from policy options.");return Yd}o(xe,"getGatewayOAuthConfig");function Ct(e){return se(e)}o(Ct,"readGatewayOAuthIssuer");ue();var gT=43,yT=128,ST=/^[A-Za-z0-9._~-]+$/,Qd="S256",ts=u.literal(Qd),rs=u.string().min(gT).max(yT).regex(ST);ue();var ns=["none","client_secret_post","client_secret_basic"],_T=[...ns,"private_key_jwt"],wT=["awaiting_login","awaiting_setup"],vT=u.string().min(1).brand(),Be=u.string().min(1).brand(),aa=u.uuid().brand(),yt=u.uuid().brand(),os=u.uuid().brand(),Xd=u.enum(ns),bT=u.enum(_T),H2=u.enum(wT),jg=u.object({client_id:Be,client_name:u.string().min(1),redirect_uris:u.array(u.string().min(1)).min(1),token_endpoint_auth_method:bT.default("none")}),el=u.object({clientId:Be,clientName:u.string().min(1),redirectUris:u.array(u.string().min(1)),tokenEndpointAuthMethod:Xd,hashedClientSecret:u.string().optional(),clientSecretExpiresAt:Q.optional(),clientExpiresAt:Q,revokedAt:Q.optional(),createdAt:Q}),tl=u.object({clientId:Be,resource:u.string(),virtualServerId:Pe,subjectId:vT,scope:u.string(),roles:u.array(u.string()),createdAt:Q,expiresAt:Q}),L2=tl.extend({id:yt,redirectUri:u.string(),clientState:u.string().optional(),codeChallenge:u.string(),codeChallengeMethod:ts}),rl=tl.extend({id:aa,currentRefreshTokenHash:u.string().optional(),previousRefreshTokenHash:u.string().optional(),revokedAt:Q.optional(),revokedReason:u.string().optional()}),as=tl.extend({tokenHash:u.string(),grantId:aa,revokedAt:Q.optional()});function nl(){return yt.parse(crypto.randomUUID())}o(nl,"createDownstreamAuthorizationTransactionId");function ol(){return os.parse(crypto.randomUUID())}o(ol,"createDownstreamBrowserLoginStateId");function Hg(){return aa.parse(crypto.randomUUID())}o(Hg,"createDownstreamGrantId");var ye="mcp:tools";function Lg(e,t){if(e===t)return!0;let r=new URL(e),n=new URL(t);return Le(r)&&Le(n)&&gt(r.hostname)===gt(n.hostname)&&r.pathname===n.pathname&&r.search===n.search}o(Lg,"redirectUriMatchesRegistration");function Bg(e){return Le(e)&&e.pathname==="/oauth/dev-login"}o(Bg,"isLoopbackDevLoginUrl");function is(e,t){return new URL(e,Ct(t)).toString()}o(is,"buildGatewayOAuthUrl");function al(e){return new URL(`/mcp/${encodeURIComponent(e.virtualServerId)}`,se(e.requestUrl)).toString()}o(al,"buildScopedAuthorizationServerIssuer");function RT(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,se(e.requestUrl)).toString()}o(RT,"buildScopedAuthorizationEndpoint");function il(e){let t=xe();return{issuer:Ct(e),authorization_endpoint:is("/oauth/authorize",e),token_endpoint:is("/oauth/token",e),registration_endpoint:is("/oauth/register",e),revocation_endpoint:is("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[ye],code_challenge_methods_supported:[Qd],token_endpoint_auth_methods_supported:ns,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","none"],client_id_metadata_document_supported:t.gateway.cimdEnabled,"x-zuplo-browser-login-kind":Ng(t)}}o(il,"buildAuthorizationServerMetadata");function Gg(e){let t=al(e);return{...il(e.requestUrl),issuer:t,authorization_endpoint:RT(e)}}o(Gg,"buildScopedAuthorizationServerMetadata");async function Vg(e,t){try{let r=Pe.parse(e.params.virtualServerId),n=ea(r);return Response.json(CT(n.virtualServerId,e.url))}catch(r){let n=he(r);return ft(e,t,{code:n==="unknown_virtual_server"?n:"not_found",detail:(r instanceof Error?r.message:void 0)??"The requested protected resource metadata document was not found."})}}o(Vg,"protectedResourceMetadataHandler");function CT(e,t){return{resource:Wr(e,t),resource_name:e,authorization_servers:[al({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[ye],mcp_protocol_version:Fr}}o(CT,"buildProtectedResourceMetadataResponseBody");function Wr(e,t){return new URL(`/mcp/${encodeURIComponent(e)}`,se(t)).toString()}o(Wr,"buildCanonicalMcpResourceForVirtualServer");function Fg(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,se(t)).toString()}o(Fg,"buildProtectedResourceMetadataUrlForVirtualServer");import{base64url as sl}from"jose";var IT="sha256:",PT=32;function Zg(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Zg,"copyToArrayBuffer");function Jt(){let e=crypto.getRandomValues(new Uint8Array(PT));return sl.encode(e)}o(Jt,"createOpaqueToken");async function pe(e){let t=await crypto.subtle.digest("SHA-256",Zg(new TextEncoder().encode(e)));return`${IT}${sl.encode(new Uint8Array(t))}`}o(pe,"hashOpaqueValue");async function Kg(e){let t=await crypto.subtle.digest("SHA-256",Zg(new TextEncoder().encode(e)));return sl.encode(new Uint8Array(t))}o(Kg,"calculatePkceS256Challenge");ue();var xT=u.record(u.string(),u.unknown()),Wg=u.string().min(1),AT=u.union([Wg.transform(e=>[e]),u.array(Wg)]),Se=u.string().min(1).brand(),kT=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],TT=["https://zuplo.com/roles","roles","role","permissions","groups"],Jg=new Dt("gateway-principal");function ET(e){let t=xT.safeParse(e);return t.success?t.data:{}}o(ET,"toClaimRecord");function UT(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(UT,"readValidationFailureDetail");function OT(e,t,r){for(let i of kT){let s=Se.safeParse(t[i]);if(s.success)return s.data}let n=Se.safeParse(e?.sub);if(!n.success)throw g("identity_context_missing",UT(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===Ct(r)?n.data:Se.parse(`${a}|${n.data}`)}o(OT,"readNormalizedSubjectId");function $T(e){let t=new Set;for(let r of TT){let n=AT.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o($T,"readRoles");function jn(e,t){let r=ET(e?.data),n={subjectId:OT(e,r,t)},a=$T(r);return a&&(n.roles=a),n}o(jn,"parseGatewayPrincipal");function Yg(e){let t=ul(e);if(!t)throw g("identity_context_missing","Gateway principal has not been hydrated");return t}o(Yg,"requireGatewayPrincipal");function Qg(e,t){Jg.set(e,t)}o(Qg,"setGatewayPrincipal");function ul(e){return Jg.get(e)}o(ul,"readGatewayPrincipal");function ss(e){let r=['realm="OAuth"',`resource_metadata="${cl(Fg(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${cl(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${cl(e.scope)}"`),`Bearer ${r.join(", ")}`}o(ss,"buildGatewayBearerChallenge");function cl(e){let t="";for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);n<=31||n===127||(t+=e[r])}return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}o(cl,"sanitizeQuotedHeaderParameter");ue();ue();function cs(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path.");let t=new URL(e,"https://gateway.local");if(t.origin!=="https://gateway.local"||t.username||t.password||t.hash||t.pathname.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}o(cs,"parseSafeRelativeReturnTo");ue();var zT=["user","shared"],Hn=u.enum(zT);function Rr(e){return{mode:"user",subjectId:e}}o(Rr,"buildUserUpstreamConnectionOwner");function us(){return{mode:"shared"}}o(us,"buildSharedUpstreamConnectionOwner");var Xg=u.object({ownerMode:Hn,initiatedBySubjectId:Se,ownerSubjectId:Se.optional(),upstreamServerId:Xe,authProfileId:et,virtualServerId:Pe,returnTo:u.string().min(1).transform(e=>cs(e)).optional()});function ey(e,t){e.ownerMode==="user"&&!e.ownerSubjectId&&t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned state requires ownerSubjectId",path:["ownerSubjectId"]}),e.ownerMode==="shared"&&e.ownerSubjectId&&t.addIssue({code:u.ZodIssueCode.custom,message:"Shared state must not include ownerSubjectId",path:["ownerSubjectId"]})}o(ey,"validateUpstreamOwnerState");var Ln=Xg.superRefine(ey),ty=Xg.omit({returnTo:!0}).superRefine(ey);function ia(e){return Ln.parse({ownerMode:e.owner.mode,initiatedBySubjectId:e.initiatedBySubjectId,ownerSubjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,returnTo:e.returnTo})}o(ia,"buildUpstreamOwnerState");function Bn(e){if(e.ownerMode==="shared")return us();if(!e.ownerSubjectId)throw g("oauth_state_invalid","User-owned upstream state is missing the owner subject.");return Rr(e.ownerSubjectId)}o(Bn,"resolveUpstreamConnectionOwnerFromState");var MT=["active","not_connected","reconsent_required"],qT=["basic_auth_app_password","bearer_token"],ry=u.string().trim().min(1).brand(),Gn=u.uuid().brand(),sa=u.uuid().brand(),dl=u.enum(MT),NT=u.enum(qT),ny=u.object({encryptedClientInformation:u.string().optional(),encryptedDiscoveryState:u.string().optional(),connectedBySubjectId:Se.optional()}),DT=ny.extend({encryptedStaticSecret:u.string().optional(),staticSecretKind:NT.optional(),staticSecretLabel:u.string().min(1).optional(),staticSecretUsername:u.string().min(1).optional()}).strict(),jT=u.object({id:ry,subjectId:Se.optional(),ownerMode:Hn,upstreamServerId:Xe,authProfileId:et,status:dl,encryptedAccessToken:u.string().min(1).optional(),encryptedRefreshToken:u.string().min(1).optional(),scopes:u.array(u.string()),expiresAt:Q.optional(),metadata:DT.optional(),createdAt:Q,updatedAt:Q});function ll(e,t){e.ownerMode==="user"&&(e.subjectId||t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="shared"&&e.subjectId!==void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:"Shared upstream connections must not include subjectId",path:["subjectId"]})}o(ll,"validateUpstreamConnectionOwnerShape");var Vn=jT.superRefine(ll);function Jr(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}o(Jr,"readUpstreamConnectionLookupKey");var pl=Ln.extend({id:Gn,callbackPath:u.string().min(1),expiresAt:Q,codeVerifier:u.string().optional(),redirectUri:u.url(),returnOrigin:u.url().optional()}).extend(ny.shape);function oy(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o(oy,"readUpstreamConnectionStatus");function ds(){return ry.parse(`mcpgw2uc_${crypto.randomUUID()}`)}o(ds,"createUpstreamConnectionId");function ay(){return Gn.parse(crypto.randomUUID())}o(ay,"createOAuthStateId");function iy(){return sa.parse(crypto.randomUUID())}o(iy,"createBrowserConnectTicketId");ue();var fl=u.discriminatedUnion("mode",[u.object({mode:u.literal("user"),subjectId:Se}).strict(),u.object({mode:u.literal("shared")}).strict()]),cy=u.object({owner:fl,upstreamServerId:Xe,authProfileId:et}).strict(),uy=u.object({items:u.array(cy).min(1).max(100)}).strict(),hl=u.object({items:u.array(u.object({key:u.object({ownerMode:Hn,subjectId:Se.optional(),upstreamServerId:Xe,authProfileId:et}).strict(),connection:Vn.strict().optional()}).strict())}).strict(),dy=Vn.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(ll),ly=Vn.strict(),py=u.object({owner:fl,upstreamServerId:Xe,authProfileId:et}).strict(),my=u.object({owner:fl,upstreamServerId:Xe,authProfileId:et,connection:Vn.strict().optional(),connectionStatus:u.object({connected:u.boolean(),status:dl,updatedAt:Vn.shape.updatedAt.optional()}).strict()}).strict(),HT=u.enum(["none","client_secret_basic","client_secret_post"]),Yr=u.object({clientId:Be,clientName:u.string().min(1),tokenEndpointAuthMethod:HT}).strict(),gl=u.discriminatedUnion("method",[u.object({method:u.literal("none"),clientId:Be}).strict(),u.object({method:u.enum(["client_secret_basic","client_secret_post"]),clientId:Be,clientSecretHashInput:u.string().min(1)}).strict()]),yl=u.object({id:yt,currentStateHash:u.string().min(1),clientId:Be,redirectUri:u.string().min(1),resource:u.string().min(1),virtualServerId:Pe,clientState:u.string().optional(),scope:u.string(),codeChallenge:u.string().min(1),codeChallengeMethod:u.literal("S256"),createdAt:Q,expiresAt:Q,consumedAt:Q.optional()}).strict(),sy=yl.omit({id:!0,consumedAt:!0}).extend({transactionId:yt,client:Yr.optional()}).strict(),Sl=u.object({subjectId:Se,roles:u.array(u.string()).optional()}).strict(),LT=yl.extend({phase:u.literal("awaiting_login")}).strict(),ml=yl.extend({phase:u.literal("awaiting_setup"),principal:Sl}).strict(),BT=u.discriminatedUnion("phase",[LT,ml]),_l=u.object({transaction:BT,client:Yr}).strict(),fy=el.omit({revokedAt:!0}).strict(),hy=u.discriminatedUnion("kind",[u.object({kind:u.literal("registered"),client:Yr}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),gy=u.object({clientId:Be}).strict(),yy=u.discriminatedUnion("kind",[u.object({kind:u.literal("found"),client:el.strict()}).strict(),u.object({kind:u.literal("missing")}).strict()]),Sy=u.discriminatedUnion("phase",[sy.extend({phase:u.literal("awaiting_login")}).strict(),sy.extend({phase:u.literal("awaiting_setup"),principal:Sl}).strict()]),_y=u.discriminatedUnion("kind",[_l.extend({kind:u.literal("started")}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("redirect_uri_mismatch")}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),wy=u.object({transactionId:yt,currentStateHash:u.string().min(1),now:Q}).strict(),vy=u.discriminatedUnion("kind",[_l.extend({kind:u.literal("available")}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),by=u.object({transactionId:yt,expectedPhase:u.literal("awaiting_login"),currentStateHash:u.string().min(1),nextStateHash:u.string().min(1),nextPhase:u.literal("awaiting_setup"),principal:Sl,now:Q}).strict(),Ry=u.discriminatedUnion("kind",[_l.extend({kind:u.literal("advanced")}).strict(),u.object({kind:u.literal("wrong_phase"),current:u.enum(["awaiting_login","awaiting_setup"])}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),Cy=u.discriminatedUnion("decision",[u.object({decision:u.literal("approve"),transactionId:yt,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:Se}).strict(),authorizationCodeHash:u.string().min(1),authorizationCodeExpiresAt:Q,grantId:aa,now:Q}).strict(),u.object({decision:u.literal("cancel"),transactionId:yt,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:Se}).strict(),now:Q}).strict()]),Iy=u.discriminatedUnion("kind",[u.object({kind:u.literal("approved"),transaction:ml,client:Yr}).strict(),u.object({kind:u.literal("cancelled"),transaction:ml,client:Yr}).strict(),u.object({kind:u.literal("principal_mismatch")}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed_already")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),Py=u.object({clientAuth:gl,codeHash:u.string().min(1),redirectUri:u.string().min(1),resource:u.string().min(1).optional(),codeChallenge:u.string().min(1),currentRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),grantExpiresAt:Q,accessTokenExpiresAt:Q,now:Q}).strict(),xy=u.discriminatedUnion("kind",[u.object({kind:u.literal("exchanged"),client:Yr,grant:rl.strict()}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("binding_mismatch")}).strict()]),Ay=u.object({clientAuth:gl,currentRefreshTokenHash:u.string().min(1),nextRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),resource:u.string().min(1).optional(),accessTokenExpiresAt:Q,now:Q}).strict(),ky=u.discriminatedUnion("kind",[u.object({kind:u.literal("rotated"),client:Yr,grant:rl.strict(),accessToken:as.strict(),matched:u.literal("current")}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),Ty=u.object({clientAuth:gl,tokenHash:u.string().min(1),now:Q}).strict(),Ey=u.discriminatedUnion("kind",[u.object({kind:u.literal("revoked_access_token")}).strict(),u.object({kind:u.literal("revoked_grant")}).strict(),u.object({kind:u.literal("client_mismatch")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("invalid_client")}).strict()]),Uy=u.object({tokenHash:u.string().min(1),now:Q}).strict(),Oy=u.discriminatedUnion("kind",[u.object({kind:u.literal("valid"),record:as.strict()}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),$y=u.object({accessTokenHash:u.string().min(1),resource:u.string().min(1),virtualServerId:Pe,upstreamConnectionKeys:u.array(cy).max(100),now:Q}).strict(),zy=u.discriminatedUnion("kind",[u.object({kind:u.literal("authorized"),principal:u.object({subjectId:Se,roles:u.array(u.string())}).strict(),accessToken:as.strict(),upstreamConnections:hl.shape.items}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("principal_mismatch")}).strict()]),My=u.object({record:pl}).strict(),qy=u.object({kind:u.literal("saved")}).strict(),Ny=u.object({id:Gn,now:Q}).strict(),Dy=u.discriminatedUnion("kind",[u.object({kind:u.literal("available"),record:pl}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict()]),jy=u.object({id:sa,expiresAt:Q,now:Q}).strict(),Hy=u.discriminatedUnion("kind",[u.object({kind:u.literal("available")}).strict(),u.object({kind:u.literal("consumed")}).strict()]);var Ly=100;function By(e){return e!==null&&typeof e=="object"}o(By,"isProblemDetailsShape");var GT="/zups/v2/mcp/storage";function ze(e){return`${GT}/${e}`}o(ze,"buildStoragePath");function VT(){return ze("upstream-connections/batch-get")}o(VT,"buildBatchGetUpstreamConnectionsPath");function FT(){return ze("upstream-connections/upsert")}o(FT,"buildUpsertUpstreamConnectionPath");function ZT(){return ze("authorization/read-setup")}o(ZT,"buildReadAuthorizationSetupPath");function KT(){return ze("oauth/register-client")}o(KT,"buildRegisterClientPath");function WT(){return ze("oauth/read-client")}o(WT,"buildReadClientPath");function JT(){return ze("authorization/start")}o(JT,"buildStartAuthorizationPath");function YT(){return ze("authorization/read-pending")}o(YT,"buildReadPendingAuthorizationPath");function QT(){return ze("authorization/advance-pending")}o(QT,"buildAdvancePendingAuthorizationPath");function XT(){return ze("authorization/decide-setup")}o(XT,"buildDecideAuthorizationSetupPath");function e0(){return ze("token/exchange-authorization-code")}o(e0,"buildExchangeAuthorizationCodePath");function t0(){return ze("token/refresh")}o(t0,"buildRefreshTokenPath");function r0(){return ze("token/revoke")}o(r0,"buildRevokeOAuthTokenPath");function n0(){return ze("token/validate-access-token")}o(n0,"buildValidateAccessTokenPath");function o0(){return ze("mcp/authorize-and-load-connections")}o(o0,"buildAuthorizeAndLoadConnectionsPath");function a0(){return ze("upstream-oauth-state/save")}o(a0,"buildSaveUpstreamOAuthStatePath");function i0(){return ze("upstream-oauth-state/consume")}o(i0,"buildConsumeUpstreamOAuthStatePath");function s0(){return ze("browser-connect-ticket/consume")}o(s0,"buildConsumeBrowserConnectTicketPath");function c0(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(c0,"responseKeyMatchesLookup");function u0(e,t){return e.owner.mode===t.owner.mode&&(e.owner.mode==="user"?e.owner.subjectId:"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(u0,"authorizationSetupMatchesLookup");function Fy(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}o(Fy,"connectionMatchesLookup");function d0(e,t){return e.ownerMode===t.ownerMode&&(e.subjectId??"")===(t.subjectId??"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId&&e.status===t.status&&(e.encryptedAccessToken??"")===(t.encryptedAccessToken??"")&&(e.encryptedRefreshToken??"")===(t.encryptedRefreshToken??"")&&vl(e.scopes,t.scopes)&&wl(e.expiresAt,t.expiresAt)&&p0(e.metadata,t.metadata)}o(d0,"connectionMatchesUpsertRecord");function wl(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}o(wl,"optionalTimestampInstantsMatch");function l0(e,t){return Date.parse(e)<=Date.parse(t)}o(l0,"timestampInstantIsAtOrBefore");function vl(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}o(vl,"stringArraysMatch");function p0(e,t){let r=Gy(e),n=Gy(t),a=Object.fromEntries(n);return r.length===n.length&&r.every(([i,s])=>a[i]===s)}o(p0,"metadataMatches");function Gy(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}o(Gy,"definedMetadataEntries");function be(e,t){throw g({code:"internal_server_error",privateDetail:e,cause:t})}o(be,"throwInvalidStorageResponse");async function m0(e,t){try{let r=await e.json();return r&&typeof r=="object"&&!Array.isArray(r)&&delete r.$schema,t.parse(r)}catch(r){be("Gateway Service storage response did not match the runtime storage contract.",r)}}o(m0,"parseRuntimeHttpStorageResponse");function Zy(e,t){e.length!==t.length&&be("Gateway Service storage response item count did not match the request.");for(let[r,n]of e.entries()){let a=t[r];c0(n.key,a)||be("Gateway Service storage response key did not match the request."),n.connection!==void 0&&!Fy(n.connection,a)&&be("Gateway Service storage response connection did not match the response key.")}}o(Zy,"validateUpstreamConnectionItemsMatchLookups");function f0(e,t){u0(e,t)||be("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!Fy(e.connection,t)&&be("Gateway Service storage response authorization setup connection did not match the request.");let r=e.connection?.status==="active",n=e.connection?.status??"not_connected",a=e.connection?.updatedAt;(e.connectionStatus.connected!==r||e.connectionStatus.status!==n||!wl(e.connectionStatus.updatedAt,a))&&be("Gateway Service storage response authorization setup status did not match the connection.")}o(f0,"validateAuthorizationSetupResponseMatchesLookup");function h0(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&be("Gateway Service storage response registered client did not match the request.")}o(h0,"validateRegisterClientResponseMatchesRequest");function g0(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&be("Gateway Service storage response client did not match the request.")}o(g0,"validateReadClientResponseMatchesRequest");function y0(e,t){e.kind==="started"&&((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.phase!==t.phase||e.transaction.clientId!==t.clientId||e.transaction.redirectUri!==t.redirectUri||e.transaction.resource!==t.resource||e.transaction.virtualServerId!==t.virtualServerId||(e.transaction.clientState??"")!==(t.clientState??"")||e.transaction.scope!==t.scope||e.transaction.codeChallenge!==t.codeChallenge||e.transaction.codeChallengeMethod!==t.codeChallengeMethod)&&be("Gateway Service storage response started authorization did not match the request."),t.phase==="awaiting_setup"&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&be("Gateway Service storage response started authorization principal did not match the request."))}o(y0,"validateStartAuthorizationResponseMatchesRequest");function Vy(e,t){e.kind!=="available"&&e.kind!=="advanced"||((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==("nextStateHash"in t?t.nextStateHash:t.currentStateHash))&&be("Gateway Service storage response pending authorization did not match the request."),"nextPhase"in t&&(e.transaction.phase!==t.nextPhase||e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&be("Gateway Service storage response advanced authorization did not match the request."))}o(Vy,"validatePendingAuthorizationResponseMatchesRequest");function S0(e,t){e.kind!=="approved"&&e.kind!=="cancelled"||(e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&be("Gateway Service storage response authorization setup transaction did not match the request.")}o(S0,"validateAuthorizationSetupDecisionResponseMatchesRequest");function _0(e,t){e.kind==="exchanged"&&(e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.currentRefreshTokenHash||!wl(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&be("Gateway Service storage response authorization-code exchange did not match the request.")}o(_0,"validateExchangeAuthorizationCodeResponseMatchesRequest");function w0(e,t){e.kind==="rotated"&&((e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.nextRefreshTokenHash||e.grant.previousRefreshTokenHash!==t.currentRefreshTokenHash||t.resource!==void 0&&e.grant.resource!==t.resource)&&be("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!l0(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!R0(e.accessToken,e.grant))&&be("Gateway Service storage response token refresh access token did not match the request."))}o(w0,"validateRefreshTokenResponseMatchesRequest");function v0(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&be("Gateway Service storage response access token did not match the request.")}o(v0,"validateAccessTokenValidationResponseMatchesRequest");function b0(e,t){e.kind==="authorized"&&((e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.resource!==t.resource||e.accessToken.virtualServerId!==t.virtualServerId||e.principal.subjectId!==e.accessToken.subjectId||!vl(e.principal.roles,e.accessToken.roles))&&be("Gateway Service storage response MCP authorization did not match the request."),Zy(e.upstreamConnections,t.upstreamConnectionKeys))}o(b0,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function R0(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.virtualServerId===t.virtualServerId&&e.subjectId===t.subjectId&&e.scope===t.scope&&vl(e.roles,t.roles)}o(R0,"accessTokenMatchesGrant");async function C0(e){try{return await e.clone().json()}catch{return}}o(C0,"readProblemDetails");async function I0(e){let t=await C0(e),r=By(t)&&typeof t.status=="number"?t.status:e.status,n=By(t)&&Xo(t.code)?t.code:Od(r);throw g({code:n,privateDetail:`Gateway Service storage request failed with HTTP ${r}.`})}o(I0,"throwRuntimeHttpStorageError");var ls=class{static{o(this,"RuntimeHttpStorageClient")}#t;#r;constructor(t){this.#t=t.baseUrl??lo.instance.zuploEdgeApiUrl,this.#r=t.fetch??fetch}async#e(t){let r=t.requestSchema.parse(t.input),n=new URL(t.path,this.#t),a=new Headers({"Content-Type":"application/json"});qp(a);let i=await this.#r(n,{method:"POST",headers:a,body:JSON.stringify(r)});return i.ok||await I0(i),{request:r,response:await m0(i,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],n=new Map,a=t.map(s=>{let c=Jr(s),d=n.get(c);if(d!==void 0)return d;let p=r.length;return r.push(s),n.set(c,p),p}),i=[];for(let s=0;s<r.length;s+=Ly){let c=r.slice(s,s+Ly);i.push(...await this.#n(c))}return a.map(s=>i[s])}async upsertUpstreamConnection(t){let{request:r,response:n}=await this.#e({input:t,path:FT(),requestSchema:dy,responseSchema:ly});return d0(n,r)||be("Gateway Service storage response connection did not match the request."),n}async readAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:ZT(),requestSchema:py,responseSchema:my});return f0(n,r),n}async registerClient(t){let{request:r,response:n}=await this.#e({input:t,path:KT(),requestSchema:fy,responseSchema:hy});return h0(n,r),n}async readClient(t){let{request:r,response:n}=await this.#e({input:t,path:WT(),requestSchema:gy,responseSchema:yy});return g0(n,r),n}async startAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:JT(),requestSchema:Sy,responseSchema:_y});return y0(n,r),n}async readPendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:YT(),requestSchema:wy,responseSchema:vy});return Vy(n,r),n}async advancePendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:QT(),requestSchema:by,responseSchema:Ry});return Vy(n,r),n}async decideAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:XT(),requestSchema:Cy,responseSchema:Iy});return S0(n,r),n}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:a0(),requestSchema:My,responseSchema:qy});return r}async consumeUpstreamOAuthState(t){let{request:r,response:n}=await this.#e({input:t,path:i0(),requestSchema:Ny,responseSchema:Dy});return n.kind==="available"&&n.record.id!==r.id&&be("Gateway Service storage response upstream OAuth state did not match the request."),n}async consumeBrowserConnectTicket(t){let{response:r}=await this.#e({input:t,path:s0(),requestSchema:jy,responseSchema:Hy});return r}async exchangeAuthorizationCode(t){let{request:r,response:n}=await this.#e({input:t,path:e0(),requestSchema:Py,responseSchema:xy});return _0(n,r),n}async refreshToken(t){let{request:r,response:n}=await this.#e({input:t,path:t0(),requestSchema:Ay,responseSchema:ky});return w0(n,r),n}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:r0(),requestSchema:Ty,responseSchema:Ey});return r}async validateAccessToken(t){let{request:r,response:n}=await this.#e({input:t,path:n0(),requestSchema:Uy,responseSchema:Oy});return v0(n,r),n}async authorizeAndLoadConnections(t){let{request:r,response:n}=await this.#e({input:t,path:o0(),requestSchema:$y,responseSchema:zy});return b0(n,r),n}async#n(t){let r={items:[...t]},{response:n}=await this.#e({input:r,path:VT(),requestSchema:uy,responseSchema:hl});return Zy(n.items,t),n.items.map(a=>a.connection)}};var P0="__zuploMcpGatewayStorageBackend",bl;function x0(){return new ls({})}o(x0,"buildProductionStorageBackend");function J(){let e=globalThis[P0];return e||(bl||(bl=x0()),bl)}o(J,"getStorage");function Rl(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(Rl,"readBearerToken");function A0(e,t,r){return ft(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(A0,"gatewayAuthenticationRequiredResponse");async function k0(e,t,r){let n=await J().validateAccessToken({tokenHash:await pe(e),now:ne(new Date)});if(n.kind!=="valid")throw t.log.warn({event:"gateway_access_token_validate_failed",code:"authentication_required",validationKind:n.kind,virtualServerId:r},"Gateway access token validation failed"),g("authentication_required","Gateway access token is expired, revoked, or invalid.");return n.record}o(k0,"validateGatewayAccessToken");function T0(e,t){if(e.accessToken.resource!==e.resource||e.accessToken.virtualServerId!==e.virtualServerId)throw t.log.warn({event:"gateway_access_token_resource_mismatch",code:"authentication_required",expectedResource:e.resource,tokenResource:e.accessToken.resource,expectedVirtualServerId:e.virtualServerId,tokenVirtualServerId:e.accessToken.virtualServerId,clientId:e.accessToken.clientId},"Gateway access token resource does not match the requested MCP resource"),g("authentication_required","Gateway access token was not issued for this MCP resource.")}o(T0,"assertAccessTokenResource");function E0(e,t,r){return ft(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":ss({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${ye} scope required by this MCP resource.`,scope:ye})}})}o(E0,"insufficientScopeResponse");function U0(e){return{subjectId:e.subjectId,roles:e.roles}}o(U0,"principalFromAccessToken");function O0(e){let t=he(e.error),r={event:"gateway_access_token_rejected",code:t??"authentication_required",virtualServerId:e.virtualServerId};return e.error instanceof Error?(r.errorName=e.error.name,r.errorMessage=e.error.message):e.error!==void 0&&e.error!==null&&(r.errorMessage=String(e.error)),e.context.log.warn(r,"Gateway access token rejected; MCP request denied"),ft(e.request,e.context,{code:t??"authentication_required",detail:e.error instanceof Error?e.error.message:"Gateway access token could not be verified.",headers:{"WWW-Authenticate":ss({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(O0,"gatewayTokenRejectedResponse");async function Cl(e,t){let r=Dn(t),n=Wr(r.virtualServerId,e.url),a=Rl(e),i=ss({virtualServerId:r.virtualServerId,requestUrl:e.url});if(!a)return t.log.debug({event:"gateway_access_token_missing",code:"authentication_required",virtualServerId:r.virtualServerId,hasAuthorizationHeader:e.headers.get("authorization")!==null},"MCP request did not include a gateway access token"),A0(e,t,i);try{let s=await k0(a,t,r.virtualServerId);if(T0({accessToken:s,resource:n,virtualServerId:r.virtualServerId},t),s.scope!==ye)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:s.scope,requiredScope:ye,virtualServerId:r.virtualServerId,clientId:s.clientId},"Gateway access token does not have the required MCP scope"),E0(e,t,r.virtualServerId);let c=U0(s);return Qg(t,c),Ud(t,c),e}catch(s){return O0({request:e,context:t,error:s,virtualServerId:r.virtualServerId})}}o(Cl,"gatewayTokenInbound");var $0=2,Ky=4,z0=24,M0=16,Wy=512,q0=/(token|secret|authorization|password|cookie|credential|client[_-]?secret|code[_-]?verifier|(^|[_-])(code|state|verifier)($|[_-]))/i,N0=/("(?:access_token|refresh_token|id_token|client_secret|authorization|password|cookie|code|state|code_verifier)"\s*:\s*")([^"]*)(")/gi,D0=/\b(access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|password|cookie|code|state|code[_-]?verifier)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;&]+)/gi,j0=/\b(authorization)(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:Bearer|Basic)\s+[^\s,;]+|[^\s,;]+)/gi,H0=/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,L0=/\bBasic\s+[A-Za-z0-9+/=-]+/gi;function Jy(e){let t=e.route;return t&&typeof t=="object"?t:void 0}o(Jy,"readRoute");function B0(e){let t=Jy(e)?.path;return typeof t=="string"&&t.length>0?t:void 0}o(B0,"readRoutePath");function G0(e){let t=Jy(e)?.raw;if(typeof t!="function")return;let r=t();if(!r||typeof r!="object")return;let n=r.operationId;return typeof n=="string"&&n.length>0?n:void 0}o(G0,"readRouteOperationId");function V0(e){if(!(e===void 0||!Number.isFinite(e)||e<100))return`${Math.trunc(e/100)}xx`}o(V0,"deriveStatusClass");function F0(e,t){if(!(!e&&!t))return e==="user"?t==="user_oauth"?"upstream_user_attributed":"gateway_user_attributed_only":e==="shared"?"shared_upstream_identity":e==="none"?"machine_identity":"unknown"}o(F0,"deriveOriginAttributionMode");function Z0(e){if(!e)return;let t=e.toLowerCase();return t.includes("desktop")||t.includes("claude")||t.includes("chatgpt")?"desktop":t.includes("vscode")||t.includes("cursor")||t.includes("zed")||t.includes("jetbrains")||t.includes("ide")?"ide":t.includes("extension")?"extension":t.includes("agent")||t.includes("bot")||t.includes("worker")||t.includes("service")?"service":"unknown"}o(Z0,"deriveClientKind");function K0(e,t){return t==="success"?"none":e===K.MCP_GATEWAY_REQUEST_RECEIVED||e===K.MCP_GATEWAY_REQUEST_REJECTED||e===K.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"ingress":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===K.MCP_GATEWAY_INITIALIZE_NEGOTIATED?"routing":e===K.MCP_GATEWAY_POLICY_DECISION?"policy":e===K.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===K.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e.startsWith("mcp_gateway_capability_")||e.startsWith("mcp_gateway_catalog_")?"upstream":e===K.MCP_GATEWAY_REQUEST_COMPLETED?"egress":"none"}o(K0,"deriveFailureStage");function W0(e,t){return t==="success"?"none":t==="application_error"?"mcp_application":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===K.MCP_GATEWAY_POLICY_DECISION||e===K.MCP_GATEWAY_GUARDRAIL_DECISION||e===K.MCP_GATEWAY_RATE_LIMIT_DECISION?"policy":e.startsWith("mcp_gateway_upstream_")||e===K.MCP_GATEWAY_CAPABILITY_FAILED||e===K.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED?"upstream":e===K.MCP_GATEWAY_REQUEST_REJECTED||e===K.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR?"client":"gateway"}o(W0,"deriveFailureOrigin");function J0(e,t){return t==="success"?"none":e.startsWith("mcp_gateway_auth_")||e.startsWith("mcp_gateway_oauth_")?"auth":e===K.MCP_GATEWAY_POLICY_DECISION?"policy":e===K.MCP_GATEWAY_GUARDRAIL_DECISION?"guardrail":e===K.MCP_GATEWAY_RATE_LIMIT_DECISION?"rate_limit":e.startsWith("mcp_gateway_upstream_")?"upstream":e===K.MCP_GATEWAY_CLIENT_UNSUPPORTED_BEHAVIOR||e===K.MCP_GATEWAY_REQUEST_REJECTED?"protocol":"none"}o(J0,"deriveReasonClass");function Y0(e){return e.length<=Wy?e:`${e.slice(0,Wy)}...`}o(Y0,"truncateAnalyticsString");function Q0(e){return Y0(e.replace(N0,"$1[REDACTED]$3").replace(j0,"$1$2[REDACTED]").replace(D0,"$1$2[REDACTED]").replace(H0,"Bearer [REDACTED]").replace(L0,"Basic [REDACTED]"))}o(Q0,"redactAnalyticsString");function Yy(e,t){if(e!==void 0){if(e===null||typeof e=="boolean")return e;if(typeof e=="string")return Q0(e);if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(Array.isArray(e))return t>=Ky?"[DEPTH_LIMIT]":e.slice(0,M0).map(r=>Yy(r,t+1)).filter(r=>r!==void 0);if(typeof e=="object")return e instanceof Date?e.toISOString():t>=Ky?"[DEPTH_LIMIT]":Qy(e,t+1)}}o(Yy,"sanitizeAnalyticsValue");function Qy(e,t=0){if(!e)return;let r={};for(let[n,a]of Object.entries(e).slice(0,z0)){if(q0.test(n)){r[n]="[REDACTED]";continue}let i=Yy(a,t);i!==void 0&&(r[n]=i)}return Object.keys(r).length===0?void 0:r}o(Qy,"sanitizeMcpGatewayAnalyticsAttributes");function M(e){return e===void 0?null:e}o(M,"nullable");function X0(e){let t=e.environment;return t&&typeof t=="object"&&typeof t.name=="string"?t.name:null}o(X0,"readEnvironment");function eE(e){let t=e.requestId;return typeof t=="string"&&t.length>0?t:null}o(eE,"readRequestId");function tE(e){if(e===void 0)return null;try{return JSON.stringify(e)}catch{return null}}o(tE,"attributesToJsonString");function rE(e,t){let r=ul(e),n=ta(e),a=Qy(t.attributes),i=eE(e),s=t.ownerMode??t.routeBinding?.ownerMode??null,c=t.upstreamAuthMode??t.routeBinding?.authMode??null,d=t.virtualServerName??t.routeBinding?.virtualServerId??n?.virtualServerId??null,p=t.upstreamServerName??t.routeBinding?.upstreamServerId??n?.upstreamServerId??null,l=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName??null,m=t.authProfileId??t.routeBinding?.authProfileId??n?.authProfileId??null,h=t.clientKind??Z0(t.clientName)??null,y=F0(s??void 0,c??void 0)??null,_=V0(t.httpStatusCode)??null,S=t.reasonClass??J0(t.eventType,t.outcome),w=t.failureOrigin??W0(t.eventType,t.outcome),v=t.failureStage??K0(t.eventType,t.outcome);return{schemaVersion:$0,outcome:t.outcome,subjectId:M(r?.subjectId),environment:X0(e),traceId:t.traceId??i,spanId:M(t.spanId),parentEventId:M(t.parentEventId),mcpSessionId:M(t.mcpSessionId),routeSurface:M(t.routeSurface),routePath:B0(e)??null,operationId:G0(e)??null,virtualServerName:d,virtualServerTitle:M(t.virtualServerTitle),upstreamServerName:p,upstreamServerTitle:l,upstreamBindingId:M(t.upstreamBindingId),clientName:M(t.clientName),clientTitle:M(t.clientTitle),clientVersion:M(t.clientVersion),clientKind:h,authProfileId:m,upstreamAuthMode:c,ownerMode:s,authMethod:M(t.authMethod),originAttributionMode:y,httpMethod:M(t.httpMethod),httpStatusCode:M(t.httpStatusCode),statusClass:_,mcpMethod:M(t.mcpMethod),mcpProtocolVersion:M(t.mcpProtocolVersion),mcpStatus:M(t.mcpStatus),mcpErrorType:M(t.mcpErrorType),applicationError:M(t.applicationError),applicationErrorCode:M(t.applicationErrorCode),toolResultIsError:M(t.toolResultIsError),capabilityType:M(t.capabilityType),capabilityName:M(t.capabilityName),capabilityTitle:M(t.capabilityTitle),upstreamCapabilityName:M(t.upstreamCapabilityName),upstreamCapabilityTitle:M(t.upstreamCapabilityTitle),capabilitySchemaHash:M(t.capabilitySchemaHash),policyId:M(t.policyId),policyAction:M(t.policyAction),guardrailType:M(t.guardrailType),guardrailDirection:M(t.guardrailDirection),guardrailFindingCount:M(t.guardrailFindingCount),redactionCount:M(t.redactionCount),requestMutated:M(t.requestMutated),responseMutated:M(t.responseMutated),latencyMs:M(t.latencyMs),gatewayLatencyMs:M(t.gatewayLatencyMs),upstreamLatencyMs:M(t.upstreamLatencyMs),authLatencyMs:M(t.authLatencyMs),policyLatencyMs:M(t.policyLatencyMs),requestBytes:M(t.requestBytes),responseBytes:M(t.responseBytes),estimatedInputTokens:M(t.estimatedInputTokens),estimatedOutputTokens:M(t.estimatedOutputTokens),estimatedContextTokens:M(t.estimatedContextTokens),contextPressureBucket:M(t.contextPressureBucket),responseMimeTypes:M(t.responseMimeTypes),base64Suspected:M(t.base64Suspected),truncated:M(t.truncated),isLargePayloadRequest:M(t.isLargePayloadRequest),isLargePayloadResponse:M(t.isLargePayloadResponse),payloadCaptureMode:M(t.payloadCaptureMode),reasonCode:M(t.reasonCode),reasonClass:S,errorType:t.errorType??t.reasonCode??null,failureOrigin:w,failureStage:v,customMetadataJson:M(t.customMetadataJson),attributesJson:tE(a)}}o(rE,"buildMcpGatewayAnalyticsMetadata");function tt(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,rE(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_gateway_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(tt,"emitMcpGatewayAnalyticsEvent");function rt(e){let t=ht().connectionsById.get(e);if(!t)throw g("unknown_upstream_server",`Unknown upstream server: ${e}`);return t.config}o(rt,"getUpstreamServerConfig");function nE(e){let t=ht().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw g("unknown_auth_profile",`Unknown auth profile ${String(e.authProfileId)} for upstream server ${e.upstreamServerId}.`);return t.authProfileId}o(nE,"resolveUpstreamAuthProfileId");function Cr(e){nE(e);let t=ht().connectionsById.get(e.upstreamServerId);if(!t)throw g("unknown_auth_profile",`Auth profile could not be resolved for upstream server ${e.upstreamServerId}.`);return t.authConfig}o(Cr,"getUpstreamAuthConfig");function Qr(e,t){let r=Cr({upstreamServerId:e,authProfileId:t});if(!fg(r))throw g("invalid_request",`Upstream server ${e} does not use upstream OAuth.`);return r.oauth}o(Qr,"requireUpstreamOAuthConfig");var oE={"shared-oauth":{authMode:"shared-oauth",ownerMode:"shared",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},user_oauth:{authMode:"user_oauth",ownerMode:"user",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},static_secret:{authMode:"static_secret",ownerMode:"none",connectSupport:"none",connectUnsupportedDetail:"Static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"configured_static_secret"},"shared-secret":{authMode:"shared-secret",ownerMode:"shared",connectSupport:"none",connectUnsupportedDetail:"Shared static-secret upstreams do not support browser connection flows.",callbackSupport:"none",credentialAcquisition:"shared_secret_connection"},"user-secret":{authMode:"user-secret",ownerMode:"user",connectSupport:"user_secret_capture",connectUnsupportedDetail:void 0,callbackSupport:"none",credentialAcquisition:"user_secret_connection"}};function $t(e){return oE[e]}o($t,"describeUpstreamAuthMode");function ps(e){return $t(e).ownerMode}o(ps,"resolveOwnerModeForUpstreamAuthMode");ue();import{errors as iS,jwtVerify as sS,SignJWT as cS}from"jose";import{base64url as aE}from"jose";var iE=new TextEncoder,sE="MCP gateway could not initialize secure key material.",cE=32,Xy=new Map,eS=new Map,uE;function dE(){return uE??lo.instance.authPrivateKey}o(dE,"readAuthPrivateKey");function tS(e){return new ln(sE,e===void 0?void 0:{cause:e})}o(tS,"createGeneratedKeyMaterialError");function rS(e,t){let r=aE.decode(t);if(r.byteLength!==cE)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(rS,"decodeJwkKeyField");function lE(e){let t=dE();if(!t)throw tS();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let n=rS("d",r.d);rS("x",r.x);let a=iE.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(a.byteLength+n.byteLength);return i.set(a),i.set(n,a.byteLength),i}catch(r){throw tS(r)}}o(lE,"decodeGeneratedKeyMaterial");function pE(e){let t=Xy.get(e);return t||(t=lE(e),Xy.set(e,t)),t}o(pE,"getMasterKeyMaterial");async function zt(e){let t=eS.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(pE(e.keyMaterialPurpose));return eS.set(e.purpose,r),r}o(zt,"readCachedDerivedKey");var mE="SHA-256";var fE="zuplo-mcp-gateway:",hE=new TextEncoder,nS=new WeakMap;async function Ir(e,t){let r=nS.get(e);r||(r=new Map,nS.set(e,r));let n=r.get(t);if(n)return n;let a=await gE(e,t);return r.set(t,a),a}o(Ir,"deriveGatewaySigningKey");async function gE(e,t){let r=oS(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=hE.encode(`${fE}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:mE,salt:new Uint8Array,info:oS(a)},n,32*8);return new Uint8Array(i)}o(gE,"hkdfExpand");function oS(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(oS,"copyToArrayBuffer");var ms="HS256",uS=15*60,yE=15*60,fs="zuplo-mcp-gateway",hs="zuplo-mcp-gateway",SE=ty.extend({id:Gn}),_E=SE.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),dS=Ln.extend({id:sa,purpose:u.literal("browser_connect")}),wE=Ln.extend({purpose:u.literal("browser_connect")}),vE=dS.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),lS=uS*1e3;async function pS(){return zt({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"oauth-state"),"derive")})}o(pS,"getOAuthStateKey");async function mS(){return zt({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"browser-connect"),"derive")})}o(mS,"getBrowserConnectKey");async function fS(e){let t=Math.floor(Date.now()/1e3)+uS;return new cS(e).setProtectedHeader({alg:ms,typ:"JWT"}).setIssuer(fs).setAudience(hs).setIssuedAt().setExpirationTime(t).sign(await pS())}o(fS,"signOAuthState");async function gs(e){try{let{payload:t}=await sS(e,await pS(),{algorithms:[ms],issuer:fs,audience:hs});return _E.parse(t)}catch(t){throw t instanceof iS.JWTExpired?g("oauth_state_expired","OAuth state has expired",t):g("oauth_state_invalid","OAuth state could not be verified",t)}}o(gs,"verifyOAuthState");async function hS(e){let t=Math.floor(Date.now()/1e3)+yE,r=wE.parse(e),n=dS.parse({...r,id:iy()});return new cS(n).setProtectedHeader({alg:ms,typ:"JWT"}).setIssuer(fs).setAudience(hs).setIssuedAt().setExpirationTime(t).sign(await mS())}o(hS,"signBrowserConnectTicket");async function ys(e){try{let{payload:t}=await sS(e,await mS(),{algorithms:[ms],issuer:fs,audience:hs});return vE.parse(t)}catch(t){throw t instanceof iS.JWTExpired?g("oauth_state_expired","Browser connect ticket has expired",t):g("oauth_state_invalid","Browser connect ticket could not be verified",t)}}o(ys,"verifyBrowserConnectTicket");async function Ss(e){if((await J().consumeBrowserConnectTicket({id:e.id,expiresAt:ne(new Date(e.exp*1e3)),now:ne(new Date)})).kind==="consumed")throw g("oauth_state_reused","Browser connect ticket has already been used")}o(Ss,"consumeBrowserConnectTicket");function bE(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}o(bE,"buildConnectRequiredMessage");async function gS(e){let t=se(e.requestUrl),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("virtualServerId",e.virtualServerId),r.searchParams.set("browserTicket",await hS({...ia(e),purpose:"browser_connect"})),r.toString()}o(gS,"buildGatewayBrowserTicketUrl");function RE(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(RE,"buildGatewayConnectPath");async function Il(e){return gS({...e,path:RE(e.upstreamServerId),redirect:!0})}o(Il,"buildGatewayConnectUrl");async function yS(e){return gS({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(yS,"buildGatewayAppPasswordCaptureUrl");async function Fn(e){let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Il(t),message:bE(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Fn,"buildRedirectConnectRequiredResponse");function SS(e){return _S({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}o(SS,"buildAdminConnectRequiredResponse");function _S(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}o(_S,"buildAdminSetupRequiredResponse");function wS(e){return _S({...e,message:e.requiresReconsent?`An administrator must replace the ${e.upstreamDisplayName} static credential before this tool can be used.`:`An administrator must configure the ${e.upstreamDisplayName} static credential before this tool can be used.`})}o(wS,"buildAdminStaticSecretRequiredResponse");ue();import{base64url as Pr}from"jose";var CE="SHA-256",Kn="AES-GCM",IE=12,xl="zuplo-secret",Al=1,vS="generated:auth_private_key:token-encryption",PE=u.object({version:u.literal(Al),keyId:u.literal(vS),algorithm:u.literal(Kn),iv:u.string().min(1),ciphertext:u.string().min(1)}).strict();function Zn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Zn,"copyToArrayBuffer");async function Pl(){return zt({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(CE,Zn(e));return crypto.subtle.importKey("raw",t,{name:Kn},!1,["encrypt","decrypt"])},"derive")})}o(Pl,"getEncryptionKey");function bS(e){return Zn(new TextEncoder().encode(`${xl}:v${e.version}:${e.keyId}`))}o(bS,"getAssociatedData");function xE(e){return`${xl}:v${e.version}:${Pr.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(xE,"encodeEnvelope");function AE(e){let t=`${xl}:v${Al}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(Pr.decode(r));return PE.parse(JSON.parse(n))}o(AE,"decodeEnvelope");async function Xr(e){let t=await Pl(),r=crypto.getRandomValues(new Uint8Array(IE)),n={version:Al,keyId:vS},a=await crypto.subtle.encrypt({name:Kn,iv:r,additionalData:bS(n)},t,new TextEncoder().encode(e));return xE({...n,algorithm:Kn,iv:Pr.encode(r),ciphertext:Pr.encode(new Uint8Array(a))})}o(Xr,"encryptSecret");async function Yt(e){let t=AE(e);if(t){let s=await Pl(),c=await crypto.subtle.decrypt({name:Kn,iv:Zn(Pr.decode(t.iv)),additionalData:bS(t)},s,Zn(Pr.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw g("internal_server_error","Encrypted payload is malformed");let a=await Pl(),i=await crypto.subtle.decrypt({name:Kn,iv:Zn(Pr.decode(r))},a,Zn(Pr.decode(n)));return new TextDecoder().decode(i)}o(Yt,"decryptSecret");function kE(e,t){let r=Cr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-secret")throw g("invalid_request",`Upstream server ${e} does not use tenant static credentials.`);return r.secret}o(kE,"requireTenantStaticSecretConfig");function RS(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(RS,"hasUsableTenantStaticSecret");async function TE(e){if(!RS(e.connection))throw g("internal_server_error","Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await Yt(e.connection.metadata.encryptedStaticSecret)}}o(TE,"resolveTenantStaticSecretCredential");async function CS(e){let t=rt(e.upstreamServerId);kE(e.upstreamServerId,e.authProfileId);let r="preloadedConnection"in e?e.preloadedConnection:(await J().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(RS(r))return{kind:"authorized",credential:await TE({connection:r})};let n={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:t.displayName,virtualServerId:e.virtualServerId,requiresReconsent:!!r};return r!==void 0&&(n.connectionId=r.id),{kind:"connect_required",payload:wS(n)}}o(CS,"resolveTenantStaticSecretCredentialForRequest");ue();async function kl(e){return J().upsertUpstreamConnection({id:ds(),ownerMode:e.owner.mode,subjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,status:"active",encryptedAccessToken:void 0,encryptedRefreshToken:void 0,scopes:[],expiresAt:void 0,metadata:e.metadata})}o(kl,"upsertStaticSecretConnection");var EE=u.string().trim().min(1).max(320),UE=u.string().min(1).max(4096),OE=u.string().trim().min(1).max(4096);function Tl(e,t){let r=Cr({upstreamServerId:e,authProfileId:t});if(r.mode!=="user-secret")throw g("invalid_request",`Upstream server ${e} does not use user static credentials.`);return r.secret}o(Tl,"requireUserStaticSecretConfig");function $E(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o($E,"encodeBase64Utf8");function zE(e){return`Basic ${$E(`${e.username}:${e.appPassword}`)}`}o(zE,"buildBasicAuthHeader");function IS(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(IS,"hasEncryptedUserStaticSecret");async function ME(e){if(!IS(e.connection))throw g("internal_server_error","Stored user static credential is incomplete.");if(e.connection.metadata.staticSecretKind==="bearer_token")return{type:"bearer_token",token:await Yt(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:zE({username:e.connection.metadata.staticSecretUsername,appPassword:await Yt(e.connection.metadata.encryptedStaticSecret)})}};throw g("internal_server_error","Stored user static credential kind is unsupported.")}o(ME,"resolveUserStaticSecretCredential");async function PS(e){if(Tl(e.upstreamServerId,e.authProfileId).kind!=="basic_auth_app_password")throw g("invalid_request","This upstream does not use username and app-password credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=EE.parse(e.username),n=UE.parse(e.appPassword);return kl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Xr(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(PS,"saveUserStaticSecretCredential");async function _s(e){let t=Tl(e.upstreamServerId,e.authProfileId);if(t.kind!=="bearer_token")throw g("invalid_request","This upstream does not use bearer token credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=OE.parse(e.token);return kl({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Xr(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(_s,"saveUserStaticBearerTokenCredential");function El(e,t){return Tl(e,t)}o(El,"readUserStaticSecretCaptureConfig");async function xS(e){let t=rt(e.upstreamServerId);if(e.owner.mode!=="user")throw g("internal_server_error","User static credential flow resolved a non-user owner.");let r="preloadedConnection"in e?e.preloadedConnection:(await J().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(IS(r))return{kind:"authorized",credential:await ME({connection:r})};let n={requestUrl:e.request.url,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:t.displayName,virtualServerId:e.virtualServerId,subject:"tool",requiresReconsent:!!r};return r!==void 0&&(n.connectionId=r.id),{kind:"connect_required",payload:await Fn(n)}}o(xS,"resolveUserStaticSecretCredentialForRequest");function AS(e){if(e.owner.mode!=="user")throw g("invalid_request","User static credential capture requires a user-owned connection.");return yS({requestUrl:e.request.url,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}})}o(AS,"buildUserStaticSecretConnectUrl");var Ul;Ul=globalThis.crypto;async function qE(e){return(await Ul).getRandomValues(new Uint8Array(e))}o(qE,"getRandomValues");async function NE(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await qE(e-n.length);for(let i of a)i<r&&(n+=t[i%t.length])}return n}o(NE,"random");async function DE(e){return await NE(e)}o(DE,"generateVerifier");async function jE(e){let t=await(await Ul).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(jE,"generateChallenge");async function Ol(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await DE(e),r=await jE(t);return{code_verifier:t,code_challenge:r}}o(Ol,"pkceChallenge");ue();var Me=Hp().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Vp.custom,message:"URL must be parseable",fatal:!0}),Dp}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),ws=Ce({resource:f().url(),authorization_servers:C(Me).optional(),jwks_uri:f().url().optional(),scopes_supported:C(f()).optional(),bearer_methods_supported:C(f()).optional(),resource_signing_alg_values_supported:C(f()).optional(),resource_name:f().optional(),resource_documentation:f().optional(),resource_policy_uri:f().url().optional(),resource_tos_uri:f().url().optional(),tls_client_certificate_bound_access_tokens:ae().optional(),authorization_details_types_supported:C(f()).optional(),dpop_signing_alg_values_supported:C(f()).optional(),dpop_bound_access_tokens_required:ae().optional()}),ca=Ce({issuer:f(),authorization_endpoint:Me,token_endpoint:Me,registration_endpoint:Me.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),service_documentation:Me.optional(),revocation_endpoint:Me.optional(),revocation_endpoint_auth_methods_supported:C(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:C(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(f()).optional(),code_challenge_methods_supported:C(f()).optional(),client_id_metadata_document_supported:ae().optional()}),HE=Ce({issuer:f(),authorization_endpoint:Me,token_endpoint:Me,userinfo_endpoint:Me.optional(),jwks_uri:Me,registration_endpoint:Me.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),acr_values_supported:C(f()).optional(),subject_types_supported:C(f()),id_token_signing_alg_values_supported:C(f()),id_token_encryption_alg_values_supported:C(f()).optional(),id_token_encryption_enc_values_supported:C(f()).optional(),userinfo_signing_alg_values_supported:C(f()).optional(),userinfo_encryption_alg_values_supported:C(f()).optional(),userinfo_encryption_enc_values_supported:C(f()).optional(),request_object_signing_alg_values_supported:C(f()).optional(),request_object_encryption_alg_values_supported:C(f()).optional(),request_object_encryption_enc_values_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),display_values_supported:C(f()).optional(),claim_types_supported:C(f()).optional(),claims_supported:C(f()).optional(),service_documentation:f().optional(),claims_locales_supported:C(f()).optional(),ui_locales_supported:C(f()).optional(),claims_parameter_supported:ae().optional(),request_parameter_supported:ae().optional(),request_uri_parameter_supported:ae().optional(),require_request_uri_registration:ae().optional(),op_policy_uri:Me.optional(),op_tos_uri:Me.optional(),client_id_metadata_document_supported:ae().optional()}),vs=I({...HE.shape,...ca.pick({code_challenge_methods_supported:!0}).shape}),ua=I({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:Fp.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),TS=I({error:f(),error_description:f().optional(),error_uri:f().optional()}),kS=Me.optional().or(O("").transform(()=>{})),LE=I({redirect_uris:C(Me),token_endpoint_auth_method:f().optional(),grant_types:C(f()).optional(),response_types:C(f()).optional(),client_name:f().optional(),client_uri:Me.optional(),logo_uri:kS,scope:f().optional(),contacts:C(f()).optional(),tos_uri:kS,policy_uri:f().optional(),jwks_uri:Me.optional(),jwks:Bp().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),$l=I({client_id:f(),client_secret:f().optional(),client_id_issued_at:ee().optional(),client_secret_expires_at:ee().optional()}).strip(),da=LE.merge($l),C9=I({error:f(),error_description:f().optional()}).strip(),I9=I({token:f(),token_type_hint:f().optional()}).strip();function ES(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(ES,"resourceUrlFromServerUrl");function US({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return a.startsWith(i)}o(US,"checkResourceAllowed");var Re=class extends Error{static{o(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},la=class extends Re{static{o(this,"InvalidRequestError")}};la.errorCode="invalid_request";var en=class extends Re{static{o(this,"InvalidClientError")}};en.errorCode="invalid_client";var tn=class extends Re{static{o(this,"InvalidGrantError")}};tn.errorCode="invalid_grant";var rn=class extends Re{static{o(this,"UnauthorizedClientError")}};rn.errorCode="unauthorized_client";var pa=class extends Re{static{o(this,"UnsupportedGrantTypeError")}};pa.errorCode="unsupported_grant_type";var ma=class extends Re{static{o(this,"InvalidScopeError")}};ma.errorCode="invalid_scope";var fa=class extends Re{static{o(this,"AccessDeniedError")}};fa.errorCode="access_denied";var Qt=class extends Re{static{o(this,"ServerError")}};Qt.errorCode="server_error";var ha=class extends Re{static{o(this,"TemporarilyUnavailableError")}};ha.errorCode="temporarily_unavailable";var ga=class extends Re{static{o(this,"UnsupportedResponseTypeError")}};ga.errorCode="unsupported_response_type";var ya=class extends Re{static{o(this,"UnsupportedTokenTypeError")}};ya.errorCode="unsupported_token_type";var Sa=class extends Re{static{o(this,"InvalidTokenError")}};Sa.errorCode="invalid_token";var _a=class extends Re{static{o(this,"MethodNotAllowedError")}};_a.errorCode="method_not_allowed";var wa=class extends Re{static{o(this,"TooManyRequestsError")}};wa.errorCode="too_many_requests";var nn=class extends Re{static{o(this,"InvalidClientMetadataError")}};nn.errorCode="invalid_client_metadata";var va=class extends Re{static{o(this,"InsufficientScopeError")}};va.errorCode="insufficient_scope";var ba=class extends Re{static{o(this,"InvalidTargetError")}};ba.errorCode="invalid_target";var OS={[la.errorCode]:la,[en.errorCode]:en,[tn.errorCode]:tn,[rn.errorCode]:rn,[pa.errorCode]:pa,[ma.errorCode]:ma,[fa.errorCode]:fa,[Qt.errorCode]:Qt,[ha.errorCode]:ha,[ga.errorCode]:ga,[ya.errorCode]:ya,[Sa.errorCode]:Sa,[_a.errorCode]:_a,[wa.errorCode]:wa,[nn.errorCode]:nn,[va.errorCode]:va,[ba.errorCode]:ba};var Xt=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function BE(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(BE,"isClientAuthMethod");var zl="code",Ml="S256";function GE(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&BE(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}o(GE,"selectClientAuthMethod");function VE(e,t,r,n){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":FE(a,i,r);return;case"client_secret_post":ZE(a,i,n);return;case"none":KE(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(VE,"applyClientAuthentication");function FE(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}o(FE,"applyBasicAuth");function ZE(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(ZE,"applyPostAuth");function KE(e,t){t.set("client_id",e)}o(KE,"applyPublicAuth");async function zS(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=TS.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:s}=n,c=OS[a]||Qt;return new c(i||"",s)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Qt(a)}}o(zS,"parseErrorResponse");async function xr(e,t){try{return await ql(e,t)}catch(r){if(r instanceof en||r instanceof rn)return await e.invalidateCredentials?.("all"),await ql(e,t);if(r instanceof tn)return await e.invalidateCredentials?.("tokens"),await ql(e,t);throw r}}o(xr,"auth");async function ql(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:a,fetchFn:i}){let s=await e.discoveryState?.(),c,d,p,l=a;if(!l&&s?.resourceMetadataUrl&&(l=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(d=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await qS(d,{fetchFn:i}),!c)try{c=await MS(t,{resourceMetadataUrl:l},i)}catch{}(p!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let R=await eU(t,{resourceMetadataUrl:l,fetchFn:i});d=R.authorizationServerUrl,p=R.authorizationServerMetadata,c=R.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let m=await WE(t,e,c),h=n||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,y=await Promise.resolve(e.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let R=p?.client_id_metadata_document_supported===!0,q=e.clientMetadataUrl;if(q&&!Dl(q))throw new nn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${q}`);if(R&&q)y={client_id:q},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let qe=await aU(d,{metadata:p,clientMetadata:e.clientMetadata,scope:h,fetchFn:i});await e.saveClientInformation(qe),y=qe}}let _=!e.redirectUrl;if(r!==void 0||_){let R=await oU(e,d,{metadata:p,resource:m,authorizationCode:r,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}let S=await e.tokens();if(S?.refresh_token)try{let R=await nU(d,{metadata:p,clientInformation:y,refreshToken:S.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}catch(R){if(!(!(R instanceof Re)||R instanceof Qt))throw R}let w=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:b}=await tU(d,{metadata:p,clientInformation:y,state:w,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(v),"REDIRECT"}o(ql,"authInternal");function Dl(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(Dl,"isHttpsUrl");async function WE(e,t,r){let n=ES(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!US({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}o(WE,"selectResourceURL");function jl(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=Nl(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let s=Nl(e,"scope")||void 0,c=Nl(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}o(jl,"extractWWWAuthenticateParams");function Nl(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(n);return a?a[1]||a[2]:null}o(Nl,"extractFieldFromWwwAuth");async function MS(e,t,r=fetch){let n=await QE(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return ws.parse(await n.json())}o(MS,"discoverOAuthProtectedResourceMetadata");async function Hl(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?Hl(e,void 0,r):void 0;throw n}}o(Hl,"fetchWithCorsRetry");function JE(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(JE,"buildWellKnownPath");async function $S(e,t,r=fetch){return await Hl(e,{"MCP-Protocol-Version":t},r)}o($S,"tryMetadataDiscovery");function YE(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(YE,"shouldAttemptFallback");async function QE(e,t,r,n){let a=new URL(e),i=n?.protocolVersion??ur,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let d=JE(t,a.pathname);s=new URL(d,n?.metadataServerUrl??a),s.search=a.search}let c=await $S(s,i,r);if(!n?.metadataUrl&&YE(c,a.pathname)){let d=new URL(`/.well-known/${t}`,a);c=await $S(d,i,r)}return c}o(QE,"discoverMetadataWithFallback");function XE(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),n.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}o(XE,"buildDiscoveryUrls");async function qS(e,{fetchFn:t=fetch,protocolVersion:r=ur}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=XE(e);for(let{url:i,type:s}of a){let c=await Hl(i,n,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?ca.parse(await c.json()):vs.parse(await c.json())}}}o(qS,"discoverAuthorizationServerMetadata");async function eU(e,t){let r,n;try{r=await MS(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));let a=await qS(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o(eU,"discoverOAuthServerInfo");async function tU(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:a,state:i,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(zl))throw new Error(`Incompatible auth server: does not support response type ${zl}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Ml))throw new Error(`Incompatible auth server: does not support code challenge method ${Ml}`)}else c=new URL("/authorize",e);let d=await Ol(),p=d.code_verifier,l=d.code_challenge;return c.searchParams.set("response_type",zl),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",l),c.searchParams.set("code_challenge_method",Ml),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),a&&c.searchParams.set("scope",a),a?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:p}}o(tU,"startAuthorization");function rU(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(rU,"prepareAuthorizationCodeRequest");async function NS(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),a)await a(d,r,c,t);else if(n){let l=t?.token_endpoint_auth_methods_supported??[],m=GE(n,l);VE(m,n,d,r)}let p=await(s??fetch)(c,{method:"POST",headers:d,body:r});if(!p.ok)throw await zS(p);return ua.parse(await p.json())}o(NS,"executeTokenRequest");async function nU(e,{metadata:t,clientInformation:r,refreshToken:n,resource:a,addClientAuthentication:i,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),d=await NS(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:s});return{refresh_token:n,...d}}o(nU,"refreshAuthorization");async function oU(e,t,{metadata:r,resource:n,authorizationCode:a,fetchFn:i}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!a)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await e.codeVerifier();c=rU(a,p,e.redirectUrl)}let d=await e.clientInformation();return NS(t,{metadata:r,tokenRequestParams:c,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}o(oU,"fetchToken");async function aU(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:a}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let s=await(a??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!s.ok)throw await zS(s);return da.parse(await s.json())}o(aU,"registerClient");function iU(){let e=tc.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP;return typeof e=="string"&&e==="1"}o(iU,"isTestOnlyAllowHttpLoopbackIdpEnabled");var sU=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),cU=[{first:0},{first:10},{first:127},{first:169,secondMin:254,secondMax:254},{first:172,secondMin:16,secondMax:31},{first:192,secondMin:168,secondMax:168},{first:100,secondMin:64,secondMax:127},{first:224,firstMax:239},{first:240,firstMax:255}];function DS(e){if(!/^\d+\.\d+\.\d+\.\d+$/.test(e))return;let t=e.split(".").map(r=>Number(r));if(!(t.length!==4||t.some(r=>Number.isNaN(r)||r<0||r>255)))return t}o(DS,"parseIpv4Octets");function uU([e,t],r){let n=r.firstMax??r.first;return e<r.first||e>n?!1:r.secondMin===void 0||r.secondMax===void 0?!0:t>=r.secondMin&&t<=r.secondMax}o(uU,"ipv4RangeMatches");function jS(e){let t=DS(e);return t!==void 0&&cU.some(r=>uU(t,r))}o(jS,"isPrivateIpv4");function Ll(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}o(Ll,"parseIpv6Word");function dU(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(dU,"formatIpv4FromWords");function lU(e){let t=e.slice(7),r=DS(t);if(r!==void 0)return r.join(".");let[n,a,i]=t.split(":"),s=Ll(n),c=Ll(a);return i===void 0&&s!==void 0&&c!==void 0?dU(s,c):void 0}o(lU,"parseIpv6MappedIpv4");function pU(e){return Ll(e.split(":").find(Boolean))}o(pU,"readFirstIpv6Hextet");function mU(e){let t=gt(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=lU(t);return n===void 0||jS(n)}let r=pU(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(mU,"isPrivateIpv6");function Bl(e){let t=gt(e);return sU.has(t)||t.endsWith(".internal")||jS(t)||mU(t)}o(Bl,"isBlockedOutboundHostname");function HS(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw g("invalid_request",`Unsupported outbound protocol: ${t.protocol}`);let r=Le(t);if(t.protocol==="http:"&&!r)throw g("invalid_request","Configured outbound HTTP URLs must target loopback hosts.");let n=gt(t.hostname);if(!r&&Bl(n))throw g("invalid_request",`Blocked outbound host: ${n}`);return t}o(HS,"validateConfiguredOutboundUrl");function LS(e){let t=new URL(e),r=Le(t),n=r&&iU();if(t.protocol!=="https:"&&!n)throw g("invalid_request","Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw g("invalid_request","Identity provider URLs must not include credentials, query params, or fragments.");let a=gt(t.hostname);if(!r&&Bl(a))throw g("invalid_request",`Blocked identity provider host: ${a}`);return t}o(LS,"validateIdentityProviderUrl");function bs(e){let t=new URL(e);if(t.protocol!=="https:"||t.pathname==="/"||t.username||t.password||t.search||t.hash)throw g("invalid_request","CIMD client_id must be an HTTPS URL with a path and no credentials, query, or fragment.");if(Bl(t.hostname))throw g("invalid_request","CIMD client_id points at a blocked host.");return t}o(bs,"validateCimdClientMetadataUrl");function BS(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=o(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}o(BS,"mergeAbortSignals");async function fU(e){try{await e.cancel()}catch{}}o(fU,"cancelReader");async function Rs(e,t){if(!e)return new Uint8Array;let r=e.getReader(),n=[],a=0,i=await r.read();for(;!i.done;){let d=i.value;if(a+=d.byteLength,a>t.maxBytes)throw await fU(r),t.createLimitError();n.push(d),i=await r.read()}let s=new Uint8Array(a),c=0;for(let d of n)s.set(d,c),c+=d.byteLength;return s}o(Rs,"readBoundedByteStream");var hU=2,gU=1024*1024,yU=1e4,SU=new Set([301,302,303,307,308]),_U=["authorization","proxy-authorization","cookie","cookie2"];function Gl(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(Gl,"readRequestUrl");function Wn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Wn,"readRequestMethod");function wU(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g(r,"Outbound response exceeded the maximum allowed size.")}o(wU,"assertContentLengthWithinLimit");async function vU(e,t,r){return wU(e,t,r),Rs(e.body,{maxBytes:t,createLimitError:o(()=>g(r,"Outbound response exceeded the maximum allowed size."),"createLimitError")})}o(vU,"readBoundedResponseBody");function bU(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}o(bU,"responseFromBufferedBody");function RU(e,t){if(!SU.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(RU,"resolveRedirectUrl");function GS(e,t){try{return t.validateUrl(e)}catch(r){throw g(t.problemCode,"Outbound URL was not allowed.",r)}}o(GS,"validateOutboundUrl");function CU(e,t){throw he(e)!==void 0?e:g(t,"Outbound fetch failed.",e)}o(CU,"normalizeFetchError");function Ra(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,a]of Object.entries(t.extra))a!==void 0&&(r[n]=a);t.error!==void 0&&Oe(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Ra,"logOutboundFailure");async function IU(e,t,r,n,a,i,s){let c=Wn(r,n);try{return await t(r,n)}catch(d){let p=d instanceof DOMException&&d.name==="AbortError";Ra(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:c,host:mt(i),error:d,extra:{abortReason:s()}}),CU(d,a)}}o(IU,"fetchWithNormalizedError");function PU(e){if(e.redirects>=e.maxRedirects)throw g(e.problemCode,"Outbound redirects exceeded the maximum allowed depth.");if(e.method!=="GET"&&e.method!=="HEAD")throw g(e.problemCode,"Outbound redirect after a non-idempotent request was blocked.")}o(PU,"assertRedirectAllowed");function xU(e,t){let r=new Headers(e);for(let n of _U)r.delete(n);for(let n of t)r.delete(n);return r}o(xU,"stripCrossOriginHeaders");function AU(e,t,r,n,a){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=xU(e.headers,a)),i}o(AU,"buildRedirectInit");function kU(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(kU,"buildInitialRequestInit");function TU(e){let t=Wn(e.currentInput,e.currentInit);PU({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=GS(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),n=new URL(e.currentUrl),a=r.origin!==n.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:AU(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(TU,"followRedirect");async function Vl(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??hU,i=r.maxResponseBytes??gU,s=r.timeoutMs??yU,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],p=r.context,l=new AbortController,m=BS(l,t.signal),h=!1,y=setTimeout(()=>{h=!0,l.abort()},s),_=e,S=kU(e,t,l.signal),w;try{w=GS(Gl(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(b){throw Ra(p,{event:"outbound_url_blocked",problemCode:n,method:Wn(e,t),host:mt(Gl(e)),error:b}),clearTimeout(y),m?.(),b}let v=0;try{for(;;){let b=await IU(p,c,_,S,n,w,()=>h?`timeout_after_${s}ms`:void 0),R=RU(b,w);if(R!==void 0)try{let q=TU({currentInput:_,currentInit:S,currentUrl:w,redirectUrl:R,redirects:v,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:l.signal,additionalCrossOriginStrippedHeaders:d});_=q.currentInput,S=q.currentInit,w=q.currentUrl,v=q.redirects;continue}catch(q){throw Ra(p,{event:"outbound_redirect_blocked",problemCode:n,method:Wn(_,S),host:mt(w),error:q,extra:{redirects:v,maxRedirects:a,redirectTargetHost:mt(R)}}),q}try{return bU(b,await vU(b,i,n))}catch(q){throw Ra(p,{event:"outbound_response_size_exceeded",problemCode:n,method:Wn(_,S),host:mt(w),error:q,extra:{maxResponseBytes:i,status:b.status}}),q}}}finally{clearTimeout(y),m?.()}}o(Vl,"runSafeOutboundExchange");async function Fl(e,t,r){let n=await Vl(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw Ra(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Wn(e,t),host:mt(Gl(e)),error:a,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),g(r.problemCode??"invalid_request","Outbound JSON response could not be parsed.",a)}}o(Fl,"runSafeOutboundJsonExchange");function Cs(e,t={},r={}){return Vl(e,t,{...r,validateUrl:HS})}o(Cs,"fetchConfiguredOutbound");function VS(e,t={},r={}){return Fl(e,t,{...r,validateUrl:LS})}o(VS,"fetchIdentityProviderJson");function FS(e,t={},r={}){return Fl(e,t,{...r,validateUrl:bs})}o(FS,"fetchCimdClientMetadataJson");ue();function Zl(e){return`Zuplo MCP Gateway - ${e}`}o(Zl,"buildGatewayOAuthClientName");function ZS(e,t){let r=new URL(e,se(t));return Le(r)&&gt(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(ZS,"buildGatewayOAuthRedirectUri");function Kl(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(Kl,"buildOAuthClientMetadataDocumentUrl");function KS(e){return se(e)}o(KS,"requireOAuthClientMetadataOrigin");function WS(e,t,r){let n=rt(t),a=Qr(t,r);return{client_id:Kl({origin:e,upstreamServerId:t,authProfileId:r}),client_name:Zl(n.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(a.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}o(WS,"buildOAuthClientMetadataDocument");var EU=u.union([da,$l]),UU=u.object({authorizationServerUrl:u.url(),resourceMetadataUrl:u.url().optional(),resourceMetadata:ws.optional(),authorizationServerMetadata:u.union([ca,vs]).optional()}).passthrough(),OU="Bearer";function $U(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o($U,"splitScopes");function zU(e){return rs.parse(e)}o(zU,"parsePkceCodeVerifier");function MU(e){if(typeof e.expires_in=="number")return ne(new Date(Date.now()+e.expires_in*1e3))}o(MU,"readTokenExpiry");async function JS(e){if(e!==void 0)return Xr(JSON.stringify(e))}o(JS,"encryptJson");async function YS(e,t){if(!e)return;let r=await Yt(e);try{return t.parse(JSON.parse(r))}catch(n){throw g("oauth_state_invalid","Stored upstream OAuth JSON state is invalid.",n)}}o(YS,"decryptJson");function qU(e){if(e===void 0)return;let t={authorizationServerUrl:e.authorizationServerUrl};return e.resourceMetadataUrl!==void 0&&(t.resourceMetadataUrl=e.resourceMetadataUrl),e.resourceMetadata!==void 0&&(t.resourceMetadata=e.resourceMetadata),e.authorizationServerMetadata!==void 0&&(t.authorizationServerMetadata=e.authorizationServerMetadata),t}o(qU,"toOAuthDiscoveryState");function NU(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(NU,"clientInformationAllowsRedirectUri");function DU(e,t,r){let n=rt(e),a=Qr(e,t),i;return a.scopes.length>0&&(i=a.scopes.join(a.scopeDelimiter)),{client_name:Zl(n.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:i,token_endpoint_auth_method:"none"}}o(DU,"buildOAuthClientMetadata");function jU(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw g("internal_server_error",`Manual OAuth registration for ${e.upstreamServerId} requires clientSecret.`);return da.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(jU,"buildManualOAuthClientInformation");function HU(e,t,r){let n=Kl({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return Dl(n)?n:void 0}o(HU,"buildClientMetadataUrl");function QS(e){for(let t of e)if(t!==void 0)return t}o(QS,"firstDefined");function LU(e){let t=Qr(e.target.upstreamServerId,e.target.authProfileId),r=DU(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:jU({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=HU(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(LU,"buildInitialOAuthClientSetup");function BU(e,t){if(t===void 0)return QS([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(BU,"readEncryptedClientInformation");function GU(e){return QS([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(GU,"readEncryptedDiscoveryState");var on=class{static{o(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredClientInformation;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=LU({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.connection=t.connection,this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=BU(t,this.configuredClientInformation),this.encryptedDiscoveryState=GU(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return fS({id:t.id,...ia({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.encryptedClientInformation=await JS(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await JS(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=ua.parse(t),n=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0;this.cachedTokens=r,this.tokensLoaded=!0;let a={id:this.connection?.id??ds(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Xr(r.access_token),encryptedRefreshToken:r.refresh_token?await Xr(r.refresh_token):void 0,scopes:$U(r.scope??this.clientMetadataValue.scope),expiresAt:MU(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await J().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:zU(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw g("oauth_state_invalid","OAuth code verifier is missing");return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:ay(),...ia({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,virtualServerId:this.target.virtualServerId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:ne(new Date(Date.now()+lS)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await J().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await YS(this.encryptedClientInformation,EU)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!NU(t,this.redirectUriValue)){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1);return}return this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=qU(await YS(this.encryptedDiscoveryState,UU))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.cachedDiscoveryState}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection?.encryptedAccessToken||this.connection.status!=="active")return;let t=ua.parse({access_token:await Yt(this.connection.encryptedAccessToken),token_type:OU,refresh_token:this.connection.encryptedRefreshToken?await Yt(this.connection.encryptedRefreshToken):void 0,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=t,t}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await J().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var VU=1e4,FU=256*1024,ZU=2;function KU(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(KU,"hasUsableAccessToken");var WU="does not support dynamic client registration";function JU(e){return e instanceof Error&&e.message.includes(WU)}o(JU,"isDynamicClientRegistrationUnsupported");function YU(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(YU,"readOAuthFetchRequest");function QU(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(QU,"responseLooksJson");function XS(e){return async(t,r)=>{let n=YU(t),a=await Cs(t,r,{maxRedirects:ZU,maxResponseBytes:FU,problemCode:"upstream_token_exchange_failed",timeoutMs:VU}),i=await a.clone().text();if(!QU(a,i))return a;try{JSON.parse(i)}catch(s){throw g("upstream_token_exchange_failed",`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,s)}return a}}o(XS,"createUpstreamOAuthFetch");async function e_(e,t){try{return await xr(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:XS(t.upstreamServerId)})}catch(r){throw JU(r)?g("upstream_client_registration_required",`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,r):r}}o(e_,"runUpstreamOAuth");async function XU(e,t){return xr(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:XS(t.upstreamServerId)})}o(XU,"exchangeUpstreamAuthorizationCode");async function t_(e,t){let r=await e_(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?g("upstream_token_exchange_failed",`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`):g("upstream_token_exchange_failed",`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`)}o(t_,"requireUpstreamAuthorizationRedirect");async function r_(e){if(KU(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await e_(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`);if(!e.provider.authorizationUrl)throw g("upstream_token_exchange_failed",`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`);return{kind:"connect_required",payload:await oO({requestUrl:e.target.request.url,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.target.virtualServerId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}o(r_,"authorizeUpstreamOAuthSession");async function eO(e){let t=await gs(e.stateToken),r=await J().consumeUpstreamOAuthState({id:t.id,now:ne(new Date)}),n=tO(r);return rO({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),nO(n),n}o(eO,"consumeStoredCallbackState");function tO(e){switch(e.kind){case"consumed":throw g("oauth_state_reused","OAuth state has already been used");case"missing":throw g("oauth_state_expired","OAuth state is missing or expired");case"available":return e.record}}o(tO,"readConsumedCallbackState");function rO(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.virtualServerId===e.signedState.virtualServerId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw g("oauth_callback_mismatch","OAuth callback did not match the initiating request")}o(rO,"assertStoredCallbackStateMatches");function nO(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw g("oauth_state_expired","OAuth state has expired")}o(nO,"assertStoredCallbackStateFresh");async function oO(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.virtualServerId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),SS(r)}let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,virtualServerId:e.virtualServerId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Fn(t)}o(oO,"buildOAuthConnectRequiredResponse");async function n_(e){let t=await eO({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Bn(t),[n]=await J().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(a.connection=n);let i=new on(a),s=await XU(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`):g("upstream_token_exchange_failed",`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`)}o(n_,"finishUpstreamOAuthCallback");async function o_(e){let t=rt(e.upstreamServerId),r=Qr(e.upstreamServerId,e.authProfileId),n=ZS(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await J().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:n,returnOrigin:se(e.request.url)}}}o(o_,"prepareUpstreamOAuthRequest");async function a_(e){let t=await o_(e),r=new on({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return t_(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(a_,"startUpstreamConnect");async function i_(e){let t=await o_(e),r=new on({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return r_({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(i_,"authorizeUpstreamRequest");function aO(e,t){switch(e.kind){case"bearer_token":{if(!e.token)throw g("internal_server_error",`Static bearer token is not configured for upstream ${t}.`);return{type:"bearer_token",token:e.token}}case"headers":{let r={};for(let n of e.headers){if(!n.value)throw g("internal_server_error",`Static header ${n.name} is not configured for upstream ${t}.`);r[n.name]=n.value}return{type:"headers",headers:r}}}}o(aO,"resolveStaticSecretCredential");async function s_(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user_oauth":return i_({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}});case"shared-secret":return CS({owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}});case"static_secret":{let n=Cr({upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId});if(n.mode!=="static_secret")throw g("internal_server_error",`Resolved static-secret credential context loaded ${n.mode} config.`);return{kind:"authorized",credential:aO(n.secret,t.upstreamServerId)}}case"user-secret":return xS({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}})}throw g("internal_server_error",`Unsupported upstream auth route context ${JSON.stringify(t)}.`)}o(s_,"resolveUpstreamCredentialForRoute");async function c_(e){let t=Rr(e.principal.subjectId),r=ht().byVirtualServerId.get(e.virtualServerId);if(r)for(let n of r.connections)n.authConfig.mode!=="user-secret"||n.authConfig.secret.kind!=="bearer_token"||n.authConfig.secret.capture!=="browser_login"||await _s({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o(c_,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function u_(e){let t,r={request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,virtualServerId:e.connectRequest.virtualServerId,...e.connectRequest.returnTo===void 0?{}:{returnTo:e.connectRequest.returnTo}},n=$t(e.connectRequest.authMode);switch(n.connectSupport){case"oauth_authorization":t=await a_(r);break;case"user_secret_capture":t=await AS(r);break;case"none":throw g("invalid_request",n.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,virtualServerId:e.connectRequest.virtualServerId}}o(u_,"startUpstreamConnectForRequest");async function d_(e){let r=(await gs(e.callbackRequest.state)).authProfileId,n=Cr({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if($t(n.mode).callbackSupport!=="authorization_code")throw g("invalid_request",`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return n_({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:rt(e.callbackRequest.upstreamServerId)})}o(d_,"finishUpstreamCallbackForRequest");var Is=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=pr,n){let a=this._client,i={...n,task:n?.task??(a.isToolTask(t.name)?{}:void 0)},s=a.requestStream({method:"tools/call",params:t},r,i),c=a.getToolOutputValidator(t.name);for await(let d of s){if(d.type==="result"&&c){let p=d.result;if(!p.structuredContent&&!p.isError){yield{type:"error",error:new A(U.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(p.structuredContent)try{let l=c(p.structuredContent);if(!l.valid){yield{type:"error",error:new A(U.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof A){yield{type:"error",error:l};return}yield{type:"error",error:new A(U.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield d}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}};function Ps(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let a of Object.keys(n)){let i=n[a];r[a]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[a]=i.default),r[a]!==void 0&&Ps(i,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Ps(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Ps(r,t)}}o(Ps,"applyElicitationDefaults");function iO(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}o(iO,"getSupportedElicitationModes");var xs=class extends yn{static{o(this,"Client")}constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new $n,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Tc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",xc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Sc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Is(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Qa(this._capabilities,t)}setRequestHandler(t,r){let a=pn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(sr(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let c=o(async(d,p)=>{let l=Ge(Oc,d);if(!l.success){let b=l.error instanceof Error?l.error.message:String(l.error);throw new A(U.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:m}=l.data;m.mode=m.mode??"form";let{supportsFormMode:h,supportsUrlMode:y}=iO(this._capabilities.elicitation);if(m.mode==="form"&&!h)throw new A(U.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!y)throw new A(U.InvalidParams,"Client does not support URL-mode elicitation requests");let _=await Promise.resolve(r(d,p));if(m.task){let b=Ge(Ht,_);if(!b.success){let R=b.error instanceof Error?b.error.message:String(b.error);throw new A(U.InvalidParams,`Invalid task creation result: ${R}`)}return b.data}let S=Ge(mr,_);if(!S.success){let b=S.error instanceof Error?S.error.message:String(S.error);throw new A(U.InvalidParams,`Invalid elicitation result: ${b}`)}let w=S.data,v=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&w.action==="accept"&&w.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Ps(v,w.content)}catch{}return w},"wrappedHandler");return super.setRequestHandler(t,c)}if(s==="sampling/createMessage"){let c=o(async(d,p)=>{let l=Ge(Uc,d);if(!l.success){let w=l.error instanceof Error?l.error.message:String(l.error);throw new A(U.InvalidParams,`Invalid sampling request: ${w}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let w=Ge(Ht,h);if(!w.success){let v=w.error instanceof Error?w.error.message:String(w.error);throw new A(U.InvalidParams,`Invalid task creation result: ${v}`)}return w.data}let _=m.tools||m.toolChoice?bo:zr,S=Ge(_,h);if(!S.success){let w=S.error instanceof Error?S.error.message:String(S.error);throw new A(U.InvalidParams,`Invalid sampling result: ${w}`)}return S.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:ur,capabilities:this._capabilities,clientInfo:this._clientInfo}},dc,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!dr.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break;case"ping":break}}assertTaskCapability(t){Mi(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&qi(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},jt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},$c,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},jt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Pc,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},wc,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},mc,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},fc,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},yc,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},jt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},jt,r)}async callTool(t,r=pr,n){if(this.isToolTaskRequired(t.name))throw new A(U.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let a=await this.request({method:"tools/call",params:t},r,n),i=this.getToolOutputValidator(t.name);if(i){if(!a.structuredContent&&!a.isError)throw new A(U.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(a.structuredContent)try{let s=i(a.structuredContent);if(!s.valid)throw new A(U.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof A?s:new A(U.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return a}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let a=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){let n=await this.request({method:"tools/list",params:t},kc,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let i=cm.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:c}=i.data,{onChanged:d}=n,p=o(async()=>{if(!s){d(null,null);return}try{let m=await a();d(null,m)}catch(m){let h=m instanceof Error?m:new Error(String(m));d(h,null)}},"refresh"),l=o(()=>{if(c){let m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);let h=setTimeout(p,c);this._listChangedDebounceTimers.set(t,h)}else p()},"handler");this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function As(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o(As,"normalizeHeaders");function l_(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...As(t.headers),...As(n.headers)}:t.headers};return e(r,a)}:e}o(l_,"createFetchWithInit");var ks=class extends Error{static{o(this,"ParseError")}constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function Wl(e){}o(Wl,"noop");function p_(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Wl,onError:r=Wl,onRetry:n=Wl,onComment:a}=e,i="",s=!0,c,d="",p="";function l(S){let w=s?S.replace(/^\xEF\xBB\xBF/,""):S,[v,b]=sO(`${i}${w}`);for(let R of v)m(R);i=b,s=!1}o(l,"feed");function m(S){if(S===""){y();return}if(S.startsWith(":")){a&&a(S.slice(S.startsWith(": ")?2:1));return}let w=S.indexOf(":");if(w!==-1){let v=S.slice(0,w),b=S[w+1]===" "?2:1,R=S.slice(w+b);h(v,R,S);return}h(S,"",S)}o(m,"parseLine");function h(S,w,v){switch(S){case"event":p=w;break;case"data":d=`${d}${w}
47
- `;break;case"id":c=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?n(parseInt(w,10)):r(new ks(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:v}));break;default:r(new ks(`Unknown field "${S.length>20?`${S.slice(0,20)}\u2026`:S}"`,{type:"unknown-field",field:S,value:w,line:v}));break}}o(h,"processField");function y(){d.length>0&&t({id:c,event:p||void 0,data:d.endsWith(`
48
- `)?d.slice(0,-1):d}),c=void 0,d="",p=""}o(y,"dispatchEvent");function _(S={}){i&&S.consume&&m(i),s=!0,c=void 0,d="",p="",i=""}return o(_,"reset"),{feed:l,reset:_}}o(p_,"createParser");function sO(e){let t=[],r="",n=0;for(;n<e.length;){let a=e.indexOf("\r",n),i=e.indexOf(`
54
+ - `)}`,new Error(P)}let L=`${c}/$ref`,T=he(e,$,r,n,a,i,s,L,d);if(T.valid||k.push({instanceLocation:s,keyword:"$ref",keywordLocation:L,error:"A subschema had errors."},...T.errors),r==="4"||r==="7")return{valid:k.length===0,errors:k}}if(Array.isArray(_)){let N=_.length,$=!1;for(let L=0;L<N;L++)if(l===_[L]||_[L]==="integer"&&l==="number"&&e%1===0&&e===e){$=!0;break}$||k.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${_.join('", "')}".`})}else _==="integer"?(l!=="number"||e%1||e!==e)&&k.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${_}".`}):_!==void 0&&l!==_&&k.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${_}".`});if(S!==void 0&&(l==="object"||l==="array"?io(e,S)||k.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`}):e!==S&&k.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`})),w!==void 0&&(l==="object"||l==="array"?w.some(N=>io(e,N))||k.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`}):w.some(N=>e===N)||k.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`})),b!==void 0){let N=`${c}/not`;he(e,b,r,n,a,i,s,N).valid&&k.push({instanceLocation:s,keyword:"not",keywordLocation:N,error:'Instance matched "not" schema.'})}let Va=[];if(R!==void 0){let N=`${c}/anyOf`,$=k.length,L=!1;for(let T=0;T<R.length;T++){let P=R[T],D=Object.create(d),j=he(e,P,r,n,a,y===!0?i:null,s,`${N}/${T}`,D);k.push(...j.errors),L=L||j.valid,j.valid&&Va.push(D)}L?k.length=$:k.splice($,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:N,error:"Instance does not match any subschemas."})}if(M!==void 0){let N=`${c}/allOf`,$=k.length,L=!0;for(let T=0;T<M.length;T++){let P=M[T],D=Object.create(d),j=he(e,P,r,n,a,y===!0?i:null,s,`${N}/${T}`,D);k.push(...j.errors),L=L&&j.valid,j.valid&&Va.push(D)}L?k.length=$:k.splice($,0,{instanceLocation:s,keyword:"allOf",keywordLocation:N,error:"Instance does not match every subschema."})}if(q!==void 0){let N=`${c}/oneOf`,$=k.length,L=q.filter((T,P)=>{let D=Object.create(d),j=he(e,T,r,n,a,y===!0?i:null,s,`${N}/${P}`,D);return k.push(...j.errors),j.valid&&Va.push(D),j.valid}).length;L===1?k.length=$:k.splice($,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:N,error:`Instance does not match exactly one subschema (${L} matches).`})}if((l==="object"||l==="array")&&Object.assign(d,...Va),Me!==void 0){let N=`${c}/if`;if(he(e,Me,r,n,a,i,s,N,d).valid){if(it!==void 0){let L=he(e,it,r,n,a,i,s,`${c}/then`,d);L.valid||k.push({instanceLocation:s,keyword:"if",keywordLocation:N,error:'Instance does not match "then" schema.'},...L.errors)}}else if(Sn!==void 0){let L=he(e,Sn,r,n,a,i,s,`${c}/else`,d);L.valid||k.push({instanceLocation:s,keyword:"if",keywordLocation:N,error:'Instance does not match "else" schema.'},...L.errors)}}if(l==="object"){if(v!==void 0)for(let T of v)T in e||k.push({instanceLocation:s,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${T}".`});let N=Object.keys(e);if(fo!==void 0&&N.length<fo&&k.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${fo} properties.`}),ec!==void 0&&N.length>ec&&k.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${ec} properties.`}),qp!==void 0){let T=`${c}/propertyNames`;for(let P in e){let D=`${s}/${at(P)}`,j=he(P,qp,r,n,a,i,D,T);j.valid||k.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:T,error:`Property name "${P}" does not match schema.`},...j.errors)}}if(tc!==void 0){let T=`${c}/dependantRequired`;for(let P in tc)if(P in e){let D=tc[P];for(let j of D)j in e||k.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:T,error:`Instance has "${P}" but does not have "${j}".`})}}if(rc!==void 0)for(let T in rc){let P=`${c}/dependentSchemas`;if(T in e){let D=he(e,rc[T],r,n,a,i,s,`${P}/${at(T)}`,d);D.valid||k.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:P,error:`Instance has "${T}" but does not match dependant schema.`},...D.errors)}}if(nc!==void 0){let T=`${c}/dependencies`;for(let P in nc)if(P in e){let D=nc[P];if(Array.isArray(D))for(let j of D)j in e||k.push({instanceLocation:s,keyword:"dependencies",keywordLocation:T,error:`Instance has "${P}" but does not have "${j}".`});else{let j=he(e,D,r,n,a,i,s,`${T}/${at(P)}`);j.valid||k.push({instanceLocation:s,keyword:"dependencies",keywordLocation:T,error:`Instance has "${P}" but does not match dependant schema.`},...j.errors)}}}let $=Object.create(null),L=!1;if(qt!==void 0){let T=`${c}/properties`;for(let P in qt){if(!(P in e))continue;let D=`${s}/${at(P)}`,j=he(e[P],qt[P],r,n,a,i,D,`${T}/${at(P)}`);if(j.valid)d[P]=$[P]=!0;else if(L=a,k.push({instanceLocation:s,keyword:"properties",keywordLocation:T,error:`Property "${P}" does not match schema.`},...j.errors),L)break}}if(!L&&Ur!==void 0){let T=`${c}/patternProperties`;for(let P in Ur){let D=new RegExp(P,"u"),j=Ur[P];for(let Ze in e){if(!D.test(Ze))continue;let Lp=`${s}/${at(Ze)}`,Bp=he(e[Ze],j,r,n,a,i,Lp,`${T}/${at(P)}`);Bp.valid?d[Ze]=$[Ze]=!0:(L=a,k.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:T,error:`Property "${Ze}" matches pattern "${P}" but does not match associated schema.`},...Bp.errors))}}}if(!L&&po!==void 0){let T=`${c}/additionalProperties`;for(let P in e){if($[P])continue;let D=`${s}/${at(P)}`,j=he(e[P],po,r,n,a,i,D,T);j.valid?d[P]=!0:(L=a,k.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:T,error:`Property "${P}" does not match additional properties schema.`},...j.errors))}}else if(!L&&mo!==void 0){let T=`${c}/unevaluatedProperties`;for(let P in e)if(!d[P]){let D=`${s}/${at(P)}`,j=he(e[P],mo,r,n,a,i,D,T);j.valid?d[P]=!0:k.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:T,error:`Property "${P}" does not match unevaluated properties schema.`},...j.errors)}}}else if(l==="array"){ic!==void 0&&e.length>ic&&k.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${ic}).`}),ac!==void 0&&e.length<ac&&k.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${ac}).`});let N=e.length,$=0,L=!1;if(oc!==void 0){let T=`${c}/prefixItems`,P=Math.min(oc.length,N);for(;$<P;$++){let D=he(e[$],oc[$],r,n,a,i,`${s}/${$}`,`${T}/${$}`);if(d[$]=!0,!D.valid&&(L=a,k.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:T,error:"Items did not match schema."},...D.errors),L))break}}if(ho!==void 0){let T=`${c}/items`;if(Array.isArray(ho)){let P=Math.min(ho.length,N);for(;$<P;$++){let D=he(e[$],ho[$],r,n,a,i,`${s}/${$}`,`${T}/${$}`);if(d[$]=!0,!D.valid&&(L=a,k.push({instanceLocation:s,keyword:"items",keywordLocation:T,error:"Items did not match schema."},...D.errors),L))break}}else for(;$<N;$++){let P=he(e[$],ho,r,n,a,i,`${s}/${$}`,T);if(d[$]=!0,!P.valid&&(L=a,k.push({instanceLocation:s,keyword:"items",keywordLocation:T,error:"Items did not match schema."},...P.errors),L))break}if(!L&&Np!==void 0){let P=`${c}/additionalItems`;for(;$<N;$++){let D=he(e[$],Np,r,n,a,i,`${s}/${$}`,P);d[$]=!0,D.valid||(L=a,k.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:P,error:"Items did not match additional items schema."},...D.errors))}}}if(Dp!==void 0)if(N===0&&Nt===void 0)k.push({instanceLocation:s,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Nt!==void 0&&N<Nt)k.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${N}) than minContains (${Nt}).`});else{let T=`${c}/contains`,P=k.length,D=0;for(let j=0;j<N;j++){let Ze=he(e[j],Dp,r,n,a,i,`${s}/${j}`,T);Ze.valid?(d[j]=!0,D++):k.push(...Ze.errors)}D>=(Nt||0)&&(k.length=P),Nt===void 0&&Da===void 0&&D===0?k.splice(P,0,{instanceLocation:s,keyword:"contains",keywordLocation:T,error:"Array does not contain item matching schema."}):Nt!==void 0&&D<Nt?k.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${Nt} items matching schema. Only ${D} items were found.`}):Da!==void 0&&D>Da&&k.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${Da} items matching schema. ${D} items were found.`})}if(!L&&jp!==void 0){let T=`${c}/unevaluatedItems`;for($;$<N;$++){if(d[$])continue;let P=he(e[$],jp,r,n,a,i,`${s}/${$}`,T);d[$]=!0,P.valid||k.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:T,error:"Items did not match unevaluated items schema."},...P.errors)}}if(bv)for(let T=0;T<N;T++){let P=e[T],D=typeof P=="object"&&P!==null;for(let j=0;j<N;j++){if(T===j)continue;let Ze=e[j];(P===Ze||D&&(typeof Ze=="object"&&Ze!==null)&&io(P,Ze))&&(k.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${T} and ${j}.`}),T=Number.MAX_SAFE_INTEGER,j=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(Or!==void 0&&(go===!0&&e<=Or||e<Or)&&k.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${go?"or equal to ":""} ${Or}.`}),$r!==void 0&&(yo===!0&&e>=$r||e>$r)&&k.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${yo?"or equal to ":""} ${$r}.`})):(Or!==void 0&&e<Or&&k.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Or}.`}),$r!==void 0&&e>$r&&k.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${$r}.`}),go!==void 0&&e<=go&&k.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${go}.`}),yo!==void 0&&e>=yo&&k.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${yo}.`})),Ha!==void 0){let N=e%Ha;Math.abs(0-N)>=11920929e-14&&Math.abs(Ha-N)>=11920929e-14&&k.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Ha}.`})}}else if(l==="string"){let N=La===void 0&&Ba===void 0?0:l_(e);La!==void 0&&N<La&&k.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${N} < ${La}).`}),Ba!==void 0&&N>Ba&&k.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${N} > ${Ba}).`}),Hp!==void 0&&!new RegExp(Hp,"u").test(e)&&k.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),or!==void 0&&np[or]&&!np[or](e)&&k.push({instanceLocation:s,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${or}".`})}return{valid:k.length===0,errors:k}}o(he,"validate");var ks=class{static{o(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=Xt(t)}validate(t){return he(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),Xt(t,this.lookup)}};var so=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let r=new ks(t,this.draft,this.shortcircuit);return n=>{let a=r.validate(n);return a.valid?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:a.errors.map(i=>`${i.instanceLocation}: ${i.error}`).join("; ")}}}};import{metrics as _O,context as Ts,propagation as m_,SpanKind as f_,SpanStatusCode as op,trace as Ea}from"@opentelemetry/api";var wO="mcp-gateway",vO="mcp-gateway",bO=zr,RO="2.0",h_=Ea.getTracer(wO),ap=_O.getMeter(vO),CO=ap.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),IO=ap.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),PO=ap.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),xO=["traceparent","tracestate","baggage"];function ip(){return performance.now()/1e3}o(ip,"nowSeconds");function g_(e,t){t(Math.max(ip()-e,0))}o(g_,"recordDurationSeconds");function p_(e){return e===void 0?void 0:String(e)}o(p_,"stringifyAttribute");function ze(e,t,r){r!==void 0&&(e[t]=r)}o(ze,"assignAttribute");function AO(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o(AO,"readTargetName");function y_(e){let t=AO({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(y_,"buildMcpOperationSpanName");function sp(e){let t={"mcp.method.name":e.methodName};return ze(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??RO),ze(t,"jsonrpc.request.id",p_(e.jsonRpcRequestId)),ze(t,"mcp.protocol.version",e.mcpProtocolVersion??bO),ze(t,"mcp.session.id",e.mcpSessionId),ze(t,"mcp.resource.uri",e.resourceUri),ze(t,"rpc.response.status_code",p_(e.rpcResponseStatusCode)),ze(t,"error.type",e.errorType),e.capabilityType==="tool"&&(ze(t,"gen_ai.operation.name","execute_tool"),ze(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&ze(t,"gen_ai.prompt.name",e.capabilityName),ze(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),ze(t,"network.protocol.version",e.networkProtocolVersion),ze(t,"network.transport",e.networkTransport),ze(t,"server.address",e.serverAddress),ze(t,"server.port",e.serverPort),ze(t,"client.address",e.clientAddress),ze(t,"client.port",e.clientPort),t}o(sp,"buildMcpOperationAttributes");function kO(e){let t=sp({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(kO,"buildMcpSessionAttributes");function S_(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:op.ERROR}),t instanceof Error&&e.recordException(t)}o(S_,"setSpanError");function __(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o(__,"readErrorType");function TO(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?Ts.active():m_.extract(Ts.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(TO,"readServerParentContext");function EO(e){let t=Ea.getSpanContext(Ts.active()),r=Ea.getSpanContext(e);if(!(!t||!Ea.isSpanContextValid(t))&&!(r&&Ea.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(EO,"readAmbientSpanLink");function w_(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(w_,"readResultErrorType");async function xr(e,t){let r=ip(),n=sp({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return h_.startActiveSpan(y_(e),{kind:f_.CLIENT,attributes:n},async a=>{try{let i=await t(),s=w_(i);return s&&(a.setAttribute("error.type",s),a.setStatus({code:op.ERROR}),n["error.type"]=s),i}catch(i){let s=e.errorType??__(i);throw n["error.type"]=s,S_(a,i,s),i}finally{g_(r,i=>{CO.record(i,n)}),a.end()}})}o(xr,"runMcpClientOperation");async function Ar(e,t){let r=ip(),n=TO(e.params),a=sp({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),i=EO(n);return h_.startActiveSpan(y_(e),{kind:f_.SERVER,attributes:a,...i?{links:i}:{}},n,async s=>{try{let c=await t(),d=w_(c);return d&&(s.setAttribute("error.type",d),s.setStatus({code:op.ERROR}),a["error.type"]=d),c}catch(c){let d=e.errorType??__(c);throw a["error.type"]=d,S_(s,c,d),c}finally{g_(r,c=>{IO.record(c,a)}),s.end()}})}o(Ar,"runMcpServerOperation");function v_(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return m_.inject(Ts.active(),t._meta,{set(r,n,a){xO.includes(n)&&(r[n]=a)}}),t}o(v_,"injectMcpTraceContextIntoParams");function b_(e,t){let r=kO({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});PO.record(Math.max(t,0),r)}o(b_,"recordMcpClientSessionDuration");var Es=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=lr,n){let a=this._client,i={...n,task:n?.task??(a.isToolTask(t.name)?{}:void 0)},s=a.requestStream({method:"tools/call",params:t},r,i),c=a.getToolOutputValidator(t.name);for await(let d of s){if(d.type==="result"&&c){let p=d.result;if(!p.structuredContent&&!p.isError){yield{type:"error",error:new A(E.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(p.structuredContent)try{let l=c(p.structuredContent);if(!l.valid){yield{type:"error",error:new A(E.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof A){yield{type:"error",error:l};return}yield{type:"error",error:new A(E.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield d}}async getTask(t,r){return this._client.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._client.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._client.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._client.cancelTask({taskId:t},r)}requestStream(t,r,n){return this._client.requestStream(t,r,n)}};function Us(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let r=t,n=e.properties;for(let a of Object.keys(n)){let i=n[a];r[a]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[a]=i.default),r[a]!==void 0&&Us(i,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Us(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Us(r,t)}}o(Us,"applyElicitationDefaults");function UO(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}o(UO,"getSupportedElicitationModes");var Os=class extends Ln{static{o(this,"Client")}constructor(t,r){super(r),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new ao,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",bu,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",_u,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",du,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Es(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Hi(this._capabilities,t)}setRequestHandler(t,r){let a=Hn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(yr(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let c=o(async(d,p)=>{let l=Ge(Iu,d);if(!l.success){let b=l.error instanceof Error?l.error.message:String(l.error);throw new A(E.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:m}=l.data;m.mode=m.mode??"form";let{supportsFormMode:h,supportsUrlMode:y}=UO(this._capabilities.elicitation);if(m.mode==="form"&&!h)throw new A(E.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!y)throw new A(E.InvalidParams,"Client does not support URL-mode elicitation requests");let _=await Promise.resolve(r(d,p));if(m.task){let b=Ge(Bt,_);if(!b.success){let R=b.error instanceof Error?b.error.message:String(b.error);throw new A(E.InvalidParams,`Invalid task creation result: ${R}`)}return b.data}let S=Ge(pr,_);if(!S.success){let b=S.error instanceof Error?S.error.message:String(S.error);throw new A(E.InvalidParams,`Invalid elicitation result: ${b}`)}let w=S.data,v=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&w.action==="accept"&&w.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Us(v,w.content)}catch{}return w},"wrappedHandler");return super.setRequestHandler(t,c)}if(s==="sampling/createMessage"){let c=o(async(d,p)=>{let l=Ge(Cu,d);if(!l.success){let w=l.error instanceof Error?l.error.message:String(l.error);throw new A(E.InvalidParams,`Invalid sampling request: ${w}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let w=Ge(Bt,h);if(!w.success){let v=w.error instanceof Error?w.error.message:String(w.error);throw new A(E.InvalidParams,`Invalid task creation result: ${v}`)}return w.data}let _=m.tools||m.toolChoice?No:Hr,S=Ge(_,h);if(!S.success){let w=S.error instanceof Error?S.error.message:String(S.error);throw new A(E.InvalidParams,`Invalid sampling result: ${w}`)}return S.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:cr,capabilities:this._capabilities,clientInfo:this._clientInfo}},tu,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!ur.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break;case"ping":break}}assertTaskCapability(t){Is(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Ps(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Lt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Pu,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Lt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Su,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},pu,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},ou,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},iu,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},uu,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Lt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Lt,r)}async callTool(t,r=lr,n){if(this.isToolTaskRequired(t.name))throw new A(E.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let a=await this.request({method:"tools/call",params:t},r,n),i=this.getToolOutputValidator(t.name);if(i){if(!a.structuredContent&&!a.isError)throw new A(E.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(a.structuredContent)try{let s=i(a.structuredContent);if(!s.valid)throw new A(E.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof A?s:new A(E.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return a}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of t){if(r.outputSchema){let a=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,r){let n=await this.request({method:"tools/list",params:t},vu,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let i=Zf.safeParse(n);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:c}=i.data,{onChanged:d}=n,p=o(async()=>{if(!s){d(null,null);return}try{let m=await a();d(null,m)}catch(m){let h=m instanceof Error?m:new Error(String(m));d(h,null)}},"refresh"),l=o(()=>{if(c){let m=this._listChangedDebounceTimers.get(t);m&&clearTimeout(m);let h=setTimeout(p,c);this._listChangedDebounceTimers.set(t,h)}else p()},"handler");this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function $s(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o($s,"normalizeHeaders");function R_(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...$s(t.headers),...$s(n.headers)}:t.headers};return e(r,a)}:e}o(R_,"createFetchWithInit");var zs=class extends Error{static{o(this,"ParseError")}constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function cp(e){}o(cp,"noop");function C_(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=cp,onError:r=cp,onRetry:n=cp,onComment:a}=e,i="",s=!0,c,d="",p="";function l(S){let w=s?S.replace(/^\xEF\xBB\xBF/,""):S,[v,b]=OO(`${i}${w}`);for(let R of v)m(R);i=b,s=!1}o(l,"feed");function m(S){if(S===""){y();return}if(S.startsWith(":")){a&&a(S.slice(S.startsWith(": ")?2:1));return}let w=S.indexOf(":");if(w!==-1){let v=S.slice(0,w),b=S[w+1]===" "?2:1,R=S.slice(w+b);h(v,R,S);return}h(S,"",S)}o(m,"parseLine");function h(S,w,v){switch(S){case"event":p=w;break;case"data":d=`${d}${w}
55
+ `;break;case"id":c=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?n(parseInt(w,10)):r(new zs(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:v}));break;default:r(new zs(`Unknown field "${S.length>20?`${S.slice(0,20)}\u2026`:S}"`,{type:"unknown-field",field:S,value:w,line:v}));break}}o(h,"processField");function y(){d.length>0&&t({id:c,event:p||void 0,data:d.endsWith(`
56
+ `)?d.slice(0,-1):d}),c=void 0,d="",p=""}o(y,"dispatchEvent");function _(S={}){i&&S.consume&&m(i),s=!0,c=void 0,d="",p="",i=""}return o(_,"reset"),{feed:l,reset:_}}o(C_,"createParser");function OO(e){let t=[],r="",n=0;for(;n<e.length;){let a=e.indexOf("\r",n),i=e.indexOf(`
49
57
  `,n),s=-1;if(a!==-1&&i!==-1?s=Math.min(a,i):a!==-1?a===e.length-1?s=-1:s=a:i!==-1&&(s=i),s===-1){r=e.slice(n);break}else{let c=e.slice(n,s);t.push(c),n=s+1,e[n-1]==="\r"&&e[n]===`
50
- `&&n++}}return[t,r]}o(sO,"splitLines");var Ts=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(i){a=p_({onEvent:o(s=>{i.enqueue(s)},"onEvent"),onError(s){t==="terminate"?i.error(s):typeof t=="function"&&t(s)},onRetry:r,onComment:n})},transform(i){a.feed(i)}})}};var cO={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ar=class extends Error{static{o(this,"StreamableHTTPError")}constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},Es=class{static{o(this,"StreamableHTTPClientTransport")}constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=l_(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??cO}async _authThenStart(){if(!this._authProvider)throw new Xt("No auth provider");let t;try{t=await xr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Xt;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=As(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){let{resumptionToken:r}=t;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let a=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new Ar(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),a)}_scheduleReconnection(t,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let a=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,r+1)})},a)}_handleSseStream(t,r,n){if(!t)return;let{onresumptiontoken:a,replayMessageId:i}=r,s,c=!1,d=!1;o(async()=>{try{let l=t.pipeThrough(new TextDecoderStream).pipeThrough(new Ts({onRetry:o(y=>{this._serverRetryMs=y},"onRetry")})).getReader();for(;;){let{value:y,done:_}=await l.read();if(_)break;if(y.id&&(s=y.id,c=!0,a?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{let S=$r.parse(JSON.parse(y.data));St(S)&&(d=!0,i!==void 0&&(S.id=i)),this.onmessage?.(S)}catch(S){this.onerror?.(S)}}(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(y){this.onerror?.(new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}},"processStream")()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new Xt("No auth provider");if(await xr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xt("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:n,onresumptiontoken:a}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:It(t)?t.id:void 0}).catch(h=>this.onerror?.(h));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,s),d=c.headers.get("mcp-session-id");if(d&&(this._sessionId=d),!c.ok){let h=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ar(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:y,scope:_}=jl(c);if(this._resourceMetadataUrl=y,this._scope=_,await xr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Xt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:y,scope:_,error:S}=jl(c);if(S==="insufficient_scope"){let w=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new Ar(403,"Server returned 403 after trying upscoping");if(_&&(this._scope=_),y&&(this._resourceMetadataUrl=y),this._lastUpscopingHeader=w??void 0,await xr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Xt;return this.send(t)}}throw new Ar(c.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),tm(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(h=>this.onerror?.(h));return}let l=(Array.isArray(t)?t:[t]).filter(h=>"method"in h&&"id"in h&&h.id!==void 0).length>0,m=c.headers.get("content-type");if(l)if(m?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:a},!1);else if(m?.includes("application/json")){let h=await c.json(),y=Array.isArray(h)?h.map(_=>$r.parse(_)):[$r.parse(h)];for(let _ of y)this.onmessage?.(_)}else throw await c.body?.cancel(),new Ar(-1,`Unexpected content type: ${m}`);else await c.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Ar(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};function m_(e=[]){let t={};for(let r of e){if(!r.value){if(r.required)throw g("internal_server_error",`Native MCP transport header ${r.name} is required but has no value configured.`);continue}t[r.name]=r.value}return t}o(m_,"resolveNativeMcpRequestHeaders");var uO={name:"zuplo-mcp-gateway",version:"0.1.0"},dO=new Mn({draft:"7",shortcircuit:!1}),lO=5,pO=500,g_=3e4,mO=2*1024*1024,fO=2;function f_(){return performance.now()/1e3}o(f_,"nowSeconds");function hO(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(hO,"readServerPort");function gO(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:hO(e)}}o(gO,"buildNativeMcpOperationContext");function Jn(e){return $g(e)}o(Jn,"withTraceMeta");function Jl(e){if(e>pO)throw g("upstream_import_failed","Upstream import exceeded the maximum allowed capability count.")}o(Jl,"assertImportedCapabilityBudget");function h_(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(h_,"buildRequestInit");function yO(e){return(t,r)=>Cs(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:fO,maxResponseBytes:mO,problemCode:"upstream_capability_invocation_failed",timeoutMs:g_})}o(yO,"createNativeMcpFetch");function SO(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(g("upstream_capability_invocation_failed","Upstream MCP request exceeded the maximum allowed time."))},g_);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(SO,"withNativeMcpRequestTimeout");function _O(e,t=[]){let r=m_(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],i={fetch:yO(a)};if(!e)return{...i,...h_(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...i,...h_(r)};case"bearer_token":return{...i,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...i,requestInit:{headers:{...r,...e.headers}}}}}o(_O,"buildNativeMcpTransportOptions");async function Yn(e,t,r){let{transport:n}=rt(e),a=new URL(n.baseUrl),i=new Es(a,_O(r,n.requestHeaders)),s=new xs(uO,{capabilities:{},jsonSchemaValidator:dO});return SO((async()=>{let c=f_();await s.connect(i);let d=i.sessionId,p=gO(a,d);try{return await t(s,p)}finally{if(i.sessionId)try{await i.terminateSession()}catch{}await s.close(),d&&zg(p,f_()-c)}})())}o(Yn,"withNativeMcpClient");async function wO(e,t,r){let n=[],a,i=0;do{if(i>=lO)throw g("upstream_capability_invocation_failed",`${e} pagination exceeded the maximum allowed page count.`);let s=await t(a);i+=1,n.push(...r(s)),a=s.nextCursor}while(a);return n}o(wO,"collectPaginatedSdkItems");async function Yl(e){return e.enabled?wO(e.label,e.fetchPage,e.readItems):[]}o(Yl,"listNativeMcpCapabilityItems");async function y_(e){return Yn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Zr({methodName:"tools/list",...r},()=>Yl({enabled:!!n?.tools,label:"Tool list",fetchPage:o(i=>t.listTools(Jn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.tools,"readItems")}));return Jl(a.length),{tools:a}},e.credential)}o(y_,"listNativeMcpTools");async function S_(e){return Yn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Zr({methodName:"prompts/list",...r},()=>Yl({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(i=>t.listPrompts(Jn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.prompts,"readItems")}));return Jl(a.length),{prompts:a}},e.credential)}o(S_,"listNativeMcpPrompts");async function __(e){return Yn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Zr({methodName:"resources/list",...r},()=>Yl({enabled:!!n?.resources,label:"Resource list",fetchPage:o(i=>t.listResources(Jn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resources,"readItems")}));return Jl(a.length),{resources:a}},e.credential)}o(__,"listNativeMcpResources");async function w_(e){return Yn(e.upstreamServerId,(t,r)=>Zr({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(Jn(e.params))),e.credential)}o(w_,"callNativeMcpTool");async function v_(e){return Yn(e.upstreamServerId,(t,r)=>Zr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(Jn(e.params))),e.credential)}o(v_,"getNativeMcpPrompt");async function b_(e){return Yn(e.upstreamServerId,(t,r)=>Zr({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(Jn(e.params))),e.credential)}o(b_,"readNativeMcpResource");var Ca=class extends A{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(U.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}};function vO(e){return{content:[{type:"text",text:e}],isError:!0}}o(vO,"buildToolErrorResult");function bO(e){return e.authUrl?new cr([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new Ca(e)}o(bO,"toConnectRequiredError");function RO(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(RO,"buildCredentialResolvedAttributes");function CO(e){tt(e.context,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:RO(e.credential)})}o(CO,"emitCredentialResolvedAnalyticsEvent");function IO(e){tt(e.context,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}})}o(IO,"emitCredentialMissingAnalyticsEvent");function PO(e){return e.ownerMode==="none"?JSON.stringify(["none",e.upstreamServerId,e.authProfileId]):Jr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId})}o(PO,"readRouteBindingCredentialCacheKey");function C_(e){if(e.ownerMode!=="none")return{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}}o(C_,"readOwnedRouteBindingLookup");async function xO(e){let t=Rl(e.request);if(!t)return new Map;let r=new Map;for(let s of e.routeBindings){let c=C_(s);c!==void 0&&r.set(Jr(c),c)}if(r.size===0)return new Map;let n=[...r.values()],a=await J().authorizeAndLoadConnections({accessTokenHash:await pe(t),resource:Wr(e.virtualServerId,e.request.url),virtualServerId:e.virtualServerId,upstreamConnectionKeys:n,now:ne(new Date)});if(a.kind!=="authorized")return new Map;let i=new Map;return a.upstreamConnections.forEach((s,c)=>{let d=n[c];d!==void 0&&i.set(Jr(d),s.connection)}),i}o(xO,"preloadCompositeAuthorizedConnections");function AO(e){let t=new Map;return r=>{let n=PO(r),a=t.get(n);if(a)return a;let i=(async()=>{let s=await e.preloadedConnections,c=C_(r),d=c===void 0?void 0:Jr(c),p=await s_({request:e.request,routeAuth:r,...d!==void 0&&s.has(d)?{preloadedConnection:s.get(d)}:{}});if(p.kind==="connect_required")throw IO({context:e.context,payload:p.payload,routeBinding:r}),bO(p.payload);return CO({context:e.context,credential:p.credential,routeBinding:r}),p.credential})();return t.set(n,i),i}}o(AO,"createCredentialResolver");var R_=500;function kO(e){return e.length<=R_?e:`${e.slice(0,R_)}...`}o(kO,"truncateAnalyticsDetail");function TO(e){tt(e.context,{eventType:K.MCP_GATEWAY_CAPABILITY_COMPLETED,outcome:e.result.isError===!0?"application_error":"success",routeBinding:e.routeBinding,mcpMethod:"tools/call",capabilityName:e.toolName,capabilityType:"tool",toolResultIsError:e.result.isError===!0,applicationError:e.result.isError===!0})}o(TO,"emitToolInvocationCompletedAnalyticsEvent");function EO(e){return e instanceof cr||e instanceof Ca?{eventType:K.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof A&&e.code===U.InvalidParams?{eventType:K.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:K.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(EO,"classifyToolInvocationFailure");function UO(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=EO(e.error);tt(e.context,{eventType:r.eventType,outcome:r.outcome,routeBinding:e.routeBinding,mcpMethod:"tools/call",capabilityName:e.toolName,capabilityType:"tool",reasonCode:r.reasonCode,reasonClass:r.reasonClass,errorType:r.errorType,mcpErrorType:r.mcpErrorType,attributes:{detail:kO(t)}})}o(UO,"emitToolInvocationFailedAnalyticsEvent");var OO=256*1024;function $O(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new A(U.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>OO)throw new A(U.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o($O,"assertToolArgumentsWithinLimit");function Ql(e){if(e.routeBindings.length===1)return e.routeBindings[0];let t=e.routeBindings.filter(r=>r.connectionPolicyName===e.upstreamPolicyName);if(t.length!==1)throw new A(U.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o(Ql,"findBindingForPublishedCapability");function Qn(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new A(U.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(Qn,"requireSingleTransparentBinding");function zO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:Qn(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new A(U.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Ql({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(zO,"resolvePublishedToolRoute");function MO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:Qn(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new A(U.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Ql({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(MO,"resolvePublishedPromptRoute");function qO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:Qn(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new A(U.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Ql({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(qO,"resolvePublishedResourceRoute");function I_(e){let t=xO({request:e.request,routeBindings:e.routeBindings,virtualServerId:e.publishedVirtualServer.virtualServerId}),r=AO({context:e.context,preloadedConnections:t,request:e.request});return{async listTools(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{tools:e.publishedVirtualServer.catalog.tools.filter(a=>a.enabled!==!1).map(Wi)};let n=Qn(e);return y_({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async callTool(n){let a=zO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:n.name});try{$O(n);let i=await r(a.binding),s=await w_({upstreamServerId:a.binding.upstreamServerId,params:{...n,name:a.upstreamName},credential:i});return TO({context:e.context,routeBinding:a.binding,toolName:n.name,result:s}),e.context.log.debug({event:"upstream_tool_invocation_succeeded",toolName:n.name,upstreamName:a.upstreamName,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId,isError:s.isError===!0},"Upstream tool invocation completed"),s}catch(i){if(UO({context:e.context,routeBinding:a.binding,toolName:n.name,error:i}),i instanceof cr||i instanceof Ca)throw e.context.log.info({event:"upstream_tool_invocation_connect_required",toolName:n.name,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId,ownerMode:a.binding.ownerMode,hasAuthUrl:i instanceof cr},"Upstream tool invocation requires user to complete a connect flow"),i;let s={event:"upstream_tool_invocation_failed",code:"upstream_capability_invocation_failed",toolName:n.name,upstreamName:a.upstreamName,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId};return i instanceof A&&(s.mcpErrorCode=i.code),i instanceof Error?(s.errorName=i.name,s.errorMessage=i.message,i.cause instanceof Error&&(s.causeName=i.cause.name,s.causeMessage=i.cause.message)):s.errorMessage=String(i),e.context.log.warn(s,"Upstream tool invocation failed; returning generic gateway error to MCP client"),vO(Qe("upstream_capability_invocation_failed").publicDetail)}},async listPrompts(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{prompts:e.publishedVirtualServer.catalog.prompts.filter(a=>a.enabled!==!1).map(Ji)};let n=Qn(e);return S_({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async getPrompt(n){let a=MO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:n.name});return v_({upstreamServerId:a.binding.upstreamServerId,params:{...n,name:a.upstreamName},credential:await r(a.binding)})},async listResources(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{resources:e.publishedVirtualServer.catalog.resources.filter(a=>a.enabled!==!1).map(Yi)};let n=Qn(e);return __({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async readResource(n){let a=qO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:n.uri});return b_({upstreamServerId:a.binding.upstreamServerId,params:{...n,uri:a.upstreamUri},credential:await r(a.binding)})}}}o(I_,"createCapabilityDispatcher");var NO="0.1.0",x_="POST",DO="POST, OPTIONS",jO=new Mn({draft:"7",shortcircuit:!1});function Xl(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:x_}})}o(Xl,"jsonRpcMethodNotAllowedResponse");function HO(e){let t={Allow:x_},r=e.headers.get("origin"),n=e.headers.get("access-control-request-method");if(r&&n){t["Access-Control-Allow-Methods"]=DO;let a=e.headers.get("access-control-request-headers");a&&(t["Access-Control-Allow-Headers"]=a)}return new Response(null,{status:204,headers:t})}o(HO,"buildOptionsResponse");function Xn(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o(Xn,"readJsonRpcRequestId");function ep(e){return e&&typeof e=="object"?e.params:void 0}o(ep,"readMcpRequestParams");function P_(e,t){return e.headers.get(t)??void 0}o(P_,"readMcpHeader");function LO(e){return{mcpProtocolVersion:P_(e,"mcp-protocol-version")??Fr,mcpSessionId:P_(e,"mcp-session-id")}}o(LO,"buildServerTelemetryBase");function BO(e){if(e.headers.has("mcp-protocol-version"))return e;let t=new Headers(e.headers);return t.set("mcp-protocol-version",Fr),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(BO,"ensureProtocolVersionHeader");async function tp(e,t){if(e.method==="OPTIONS")return HO(e);if(e.method==="GET")return Xl("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return Xl("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return Xl("Only POST is supported by this virtual MCP server.");let r=Dn(t),n=vg(r.virtualServerId),a=qg(t);if(n.catalog.catalogSource==="upstream_mcp"&&a.length!==1)throw t.log.error({event:"virtual_server_binding_count_invalid",code:"internal_server_error",virtualServerId:r.virtualServerId,bindingCount:a.length,catalogSource:n.catalog.catalogSource},"MCP virtual server route requires exactly one upstream binding"),g("internal_server_error",`MCP virtual server route requires exactly one upstream binding; found ${a.length}.`);let i=LO(e),s=I_({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),c=se(e.url),d=new Di({enableDnsRebindingProtection:!0,allowedOrigins:[c]}),p=new Ni(n.catalog.serverInfo??{name:r.virtualServerId,version:NO},{capabilities:{prompts:{},resources:{},tools:{}},jsonSchemaValidator:jO});p.setRequestHandler(Ac,async m=>Kr({methodName:"tools/list",params:ep(m),jsonRpcRequestId:Xn(m),...i},()=>s.listTools())),p.setRequestHandler(wo,async m=>Kr({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:Xn(m),...i},()=>s.callTool(m.params))),p.setRequestHandler(_c,async m=>Kr({methodName:"prompts/list",params:ep(m),jsonRpcRequestId:Xn(m),...i},()=>s.listPrompts())),p.setRequestHandler(vc,async m=>Kr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:Xn(m),...i},()=>s.getPrompt(m.params))),p.setRequestHandler(pc,async m=>Kr({methodName:"resources/list",params:ep(m),jsonRpcRequestId:Xn(m),...i},()=>s.listResources())),p.setRequestHandler(gc,async m=>Kr({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:Xn(m),...i},()=>s.readResource(m.params))),await p.connect(d);let l=await d.handleRequest(e);return BO(l)}o(tp,"virtualServerHandler");async function GO(e,t){return ir("handler.mcp-virtual-server"),tp(e,t)}o(GO,"McpVirtualServerHandler");var eo={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},VO="oauth-protected-resource-metadata",FO="/.well-known/oauth-protected-resource/";function ZO(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}o(ZO,"readRouteOperationId");function KO(e){return e.hasGatewayRouteContext?eo.VIRTUAL_MCP_SERVER:e.routeOperationId===VO||e.routeOperationId===void 0&&e.routePath.startsWith(FO)?eo.OAUTH_PROTECTED_RESOURCE_METADATA:eo.OTHER}o(KO,"classifyAnalyticsRouteSurface");function WO(e){let t=e.route.path;return{routePath:t,routeSurface:KO({routePath:t,routeOperationId:ZO(e),hasGatewayRouteContext:ta(e)!==void 0})}}o(WO,"readAnalyticsRequestContext");function JO(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===eo.VIRTUAL_MCP_SERVER}o(JO,"isIntentionalMethodRejection");function YO(e){return JO(e)||e.response.status===401&&e.routeSurface===eo.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(YO,"classifyRequestCompletedOutcome");async function rp(e,t){let r=Date.now(),n=WO(t);return t.addResponseSendingFinalHook(a=>{let i=YO({response:a,routeSurface:n.routeSurface});tt(t,{eventType:K.MCP_GATEWAY_REQUEST_COMPLETED,outcome:i,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(rp,"analyticsContextInbound");function QO(e){return e instanceof Response}o(QO,"isResponse");var A_="/mcp/";function XO(e){let t=e.route.path;if(!t.startsWith(A_))throw g("internal_server_error",`Route ${t} is bound to mcp-oauth-inbound but does not match the /mcp/{virtualServerId} convention.`);let r=t.slice(A_.length);if(!r||r.includes("/"))throw g("internal_server_error",`Route ${t} is bound to mcp-oauth-inbound but must use exactly one /mcp/{virtualServerId} segment.`);return r}o(XO,"readVirtualServerIdFromRoute");async function Ia(e,t){let n={virtualServerId:Pe.parse(XO(t))};Cg(t,n),og(t,n);let a=await rp(e,t);return QO(a)?a:Cl(a,t)}o(Ia,"mcpOAuthInboundPolicy");var e$=o(async(e,t,r,n)=>(ir("policy.inbound.mcp-auth0-oauth"),Ia(e,t)),"McpAuth0OAuthInboundPolicy");function t$(e){let t=`https://${e.auth0Domain}/`,r=`https://${e.auth0Domain}/.well-known/jwks.json`,n=`https://${e.auth0Domain}/authorize`,a=`https://${e.auth0Domain}/oauth/token`;return es({oidc:{issuer:t,jwksUrl:r,audience:e.audience},browserLogin:{url:n,tokenUrl:a,clientId:e.clientId,clientSecret:e.clientSecret,scope:e.scope??"openid profile email",audience:e.audience,...e.browserLoginOverrides??{}},gateway:e.gateway})}o(t$,"buildAuth0McpOAuthRuntimeConfig");var r$={policyType:"mcp-auth0-oauth-inbound",displayName:"MCP OAuth (Auth0)",getConfig(e){return t$(e)}};Vi(r$);var n$=o(async(e,t,r,n)=>(ir("policy.inbound.mcp-oauth"),Ia(e,t)),"McpOAuthInboundPolicy"),o$={policyType:"mcp-oauth-inbound",displayName:"MCP OAuth",getConfig(e){return es(e)}};Vi(o$);function a$(e){let t=$t(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,virtualServerId:e.virtualServerId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.config.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}o(a$,"buildRouteAuthBaseFromConnection");function T_(e){if(!e.connection.authProfiles[e.authMode])throw g("internal_server_error",`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=$t(e.authMode);return{upstreamServerId:e.connection.id,virtualServerId:e.virtualServerId,authProfileId:Nn(e.connection.id,e.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.authMode,ownerMode:r.ownerMode}}o(T_,"buildRouteAuthBaseFromPolicyOptions");function E_(e,t){let n=ht().byVirtualServerId.get(t);if(!n)throw g("unknown_virtual_server",`Unknown virtual server: ${t}`);let a=n.connections.find(i=>i.upstreamServerId===e);if(!a)throw g("virtual_server_upstream_mismatch",`Virtual server ${t} does not bind upstream ${e}.`);return a$({connection:a,virtualServerId:t})}o(E_,"resolveRouteAuthBase");function k_(e,t){switch(e){case"user":return Rr(t.subjectId);case"shared":return us()}}o(k_,"buildOwnerForPrincipal");function Us(e,t){switch(e.ownerMode){case"shared":return{...e,owner:k_(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:k_(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(Us,"resolveRouteAuthForPrincipal");function i$(e){let t=Object.keys(e.connection.authProfiles);if(t.length!==1)throw g("internal_server_error",`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];if(r===void 0)throw g("internal_server_error",`Upstream policy ${e.policyName} does not declare an auth mode.`);return Bi.parse(r)}o(i$,"readSingleAuthMode");function U_(e){return Ot.parse(e)}o(U_,"buildToolNamePrefixFromConnectionId");async function np(e,t,r,n){let a=Ki(r,n),i=i$({policyName:n,connection:a}),s=Dn(t),c=T_({connection:a,virtualServerId:s.virtualServerId,authMode:i});if(c.ownerMode==="none")return Jd(t,{...c,connectionPolicyName:n,toolNamePrefix:U_(a.id)}),e;let d=Yg(t);return Jd(t,{...Us(c,d),connectionPolicyName:n,toolNamePrefix:U_(a.id)}),e}o(np,"mcpUpstreamConnectionPolicy");var s$=o(async(e,t,r,n)=>(ir("policy.inbound.mcp-upstream-connection"),np(e,t,r,n)),"McpUpstreamConnectionInboundPolicy");ue();ue();var O_="application/json",c$="application/x-www-form-urlencoded";function u$(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(u$,"normalizeContentType");function d$(e,t){return e===t?!0:t===O_&&e.endsWith("+json")}o(d$,"contentTypeMatches");function l$(e,t){if(!t||t.length===0)return;let r=u$(e.headers.get("content-type"));if(!t.some(n=>d$(r,n)))throw g("invalid_request",`Request body must be ${t.join(" or ")}.`)}o(l$,"assertExpectedContentType");function p$(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g("invalid_request",`${r} exceeded the maximum allowed size.`)}o(p$,"assertContentLengthWithinLimit");async function $_(e,t){let r=t.label??"Request body";l$(e,t.expectedContentTypes),p$(e,t.maxBytes,r);let n=await Rs(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>g("invalid_request",`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o($_,"readBoundedTextBody");async function z_(e,t){let r=await $_(e,{...t,expectedContentTypes:[O_]});try{return JSON.parse(r)}catch(n){throw g("invalid_request","Request body must be valid JSON.",n)}}o(z_,"readBoundedJsonBody");async function Os(e,t){let r=await $_(e,{...t,expectedContentTypes:[c$]});return new URLSearchParams(r)}o(Os,"readBoundedFormUrlEncodedBody");var M_=Symbol("Html");function m$(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(m$,"escapeHtml");function f$(e){return e===null||typeof e!="object"?!1:e[M_]===!0}o(f$,"isHtml");function q_(e){return e==null||e===!1?"":Array.isArray(e)?e.map(q_).join(""):f$(e)?e.value:m$(String(e))}o(q_,"renderValue");function er(e){return{[M_]:!0,value:e}}o(er,"trustedHtml");var _e=er("");function T(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=q_(t[n]),r+=e[n+1]??"";return er(r)}o(T,"html");function tr(e){return e.value}o(tr,"renderHtml");var rr=er('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;padding:9px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function nr(e){return T`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" type="image/png" href="https://www.google.com/s2/favicons?domain=${e.host}&sz=64" /><style>
58
+ `&&n++}}return[t,r]}o(OO,"splitLines");var Ms=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(i){a=C_({onEvent:o(s=>{i.enqueue(s)},"onEvent"),onError(s){t==="terminate"?i.error(s):typeof t=="function"&&t(s)},onRetry:r,onComment:n})},transform(i){a.feed(i)}})}};var $O={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},kr=class extends Error{static{o(this,"StreamableHTTPError")}constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},qs=class{static{o(this,"StreamableHTTPClientTransport")}constructor(t,r){this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=R_(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??$O}async _authThenStart(){if(!this._authProvider)throw new Ft("No auth provider");let t;try{t=await gr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Ft;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=$s(this._requestInit?.headers);return new Headers({...t,...r})}async _startOrAuthSse(t){let{resumptionToken:r}=t;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let a=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new kr(a.status,`Failed to open SSE stream: ${a.statusText}`)}this._handleSseStream(a.body,t,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,t),a)}_scheduleReconnection(t,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let a=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,r+1)})},a)}_handleSseStream(t,r,n){if(!t)return;let{onresumptiontoken:a,replayMessageId:i}=r,s,c=!1,d=!1;o(async()=>{try{let l=t.pipeThrough(new TextDecoderStream).pipeThrough(new Ms({onRetry:o(y=>{this._serverRetryMs=y},"onRetry")})).getReader();for(;;){let{value:y,done:_}=await l.read();if(_)break;if(y.id&&(s=y.id,c=!0,a?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{let S=Dr.parse(JSON.parse(y.data));yt(S)&&(d=!0,i!==void 0&&(S.id=i)),this.onmessage?.(S)}catch(S){this.onerror?.(S)}}(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(y){this.onerror?.(new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}},"processStream")()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new Ft("No auth provider");if(await gr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:n,onresumptiontoken:a}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Pt(t)?t.id:void 0}).catch(h=>this.onerror?.(h));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,s),d=c.headers.get("mcp-session-id");if(d&&(this._sessionId=d),!c.ok){let h=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new kr(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:y,scope:_}=nd(c);if(this._resourceMetadataUrl=y,this._scope=_,await gr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:y,scope:_,error:S}=nd(c);if(S==="insufficient_scope"){let w=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===w)throw new kr(403,"Server returned 403 after trying upscoping");if(_&&(this._scope=_),y&&(this._resourceMetadataUrl=y),this._lastUpscopingHeader=w??void 0,await gr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ft;return this.send(t)}}throw new kr(c.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),Df(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(h=>this.onerror?.(h));return}let l=(Array.isArray(t)?t:[t]).filter(h=>"method"in h&&"id"in h&&h.id!==void 0).length>0,m=c.headers.get("content-type");if(l)if(m?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:a},!1);else if(m?.includes("application/json")){let h=await c.json(),y=Array.isArray(h)?h.map(_=>Dr.parse(_)):[Dr.parse(h)];for(let _ of y)this.onmessage?.(_)}else throw await c.body?.cancel(),new kr(-1,`Unexpected content type: ${m}`);else await c.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let t=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:t,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new kr(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,r){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:r?.onresumptiontoken})}};function I_(e=[]){let t={};for(let r of e){if(!r.value){if(r.required)throw g("internal_server_error",`Native MCP transport header ${r.name} is required but has no value configured.`);continue}t[r.name]=r.value}return t}o(I_,"resolveNativeMcpRequestHeaders");var zO={name:"zuplo-mcp-gateway",version:"0.1.0"},MO=new so({draft:"7",shortcircuit:!1}),qO=5,NO=500,A_=3e4,jO=2*1024*1024,DO=2;function P_(){return performance.now()/1e3}o(P_,"nowSeconds");function HO(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(HO,"readServerPort");function LO(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:HO(e)}}o(LO,"buildNativeMcpOperationContext");function sn(e){return v_(e)}o(sn,"withTraceMeta");function Ns(e){if(e>NO)throw g("upstream_import_failed","Upstream import exceeded the maximum allowed capability count.")}o(Ns,"assertImportedCapabilityBudget");function x_(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(x_,"buildRequestInit");function BO(e){return(t,r)=>qn(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:DO,maxResponseBytes:jO,problemCode:"upstream_capability_invocation_failed",timeoutMs:A_})}o(BO,"createNativeMcpFetch");function GO(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(g("upstream_capability_invocation_failed","Upstream MCP request exceeded the maximum allowed time."))},A_);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(GO,"withNativeMcpRequestTimeout");function VO(e,t=[]){let r=I_(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],i={fetch:BO(a)};if(!e)return{...i,...x_(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...i,...x_(r)};case"bearer_token":return{...i,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...i,requestInit:{headers:{...r,...e.headers}}}}}o(VO,"buildNativeMcpTransportOptions");async function cn(e,t,r){let{transport:n}=je(e),a=new URL(n.baseUrl),i=new qs(a,VO(r,n.requestHeaders)),s=new Os(zO,{capabilities:{},jsonSchemaValidator:MO});return GO((async()=>{let c=P_();await s.connect(i);let d=i.sessionId,p=LO(a,d);try{return await t(s,p)}finally{if(i.sessionId)try{await i.terminateSession()}catch{}await s.close(),d&&b_(p,P_()-c)}})())}o(cn,"withNativeMcpClient");async function FO(e,t,r){let n=[],a,i=0;do{if(i>=qO)throw g("upstream_capability_invocation_failed",`${e} pagination exceeded the maximum allowed page count.`);let s=await t(a);i+=1,n.push(...r(s)),a=s.nextCursor}while(a);return n}o(FO,"collectPaginatedSdkItems");async function js(e){return e.enabled?FO(e.label,e.fetchPage,e.readItems):[]}o(js,"listNativeMcpCapabilityItems");async function k_(e){return cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await xr({methodName:"tools/list",...r},()=>js({enabled:!!n?.tools,label:"Tool list",fetchPage:o(i=>t.listTools(sn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.tools,"readItems")}));return Ns(a.length),{tools:a}},e.credential)}o(k_,"listNativeMcpTools");async function T_(e){return cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await xr({methodName:"prompts/list",...r},()=>js({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(i=>t.listPrompts(sn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.prompts,"readItems")}));return Ns(a.length),{prompts:a}},e.credential)}o(T_,"listNativeMcpPrompts");async function E_(e){return cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await xr({methodName:"resources/list",...r},()=>js({enabled:!!n?.resources,label:"Resource list",fetchPage:o(i=>t.listResources(sn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resources,"readItems")}));return Ns(a.length),{resources:a}},e.credential)}o(E_,"listNativeMcpResources");async function U_(e){return cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await xr({methodName:"resources/templates/list",...r},()=>js({enabled:!!n?.resources,label:"Resource template list",fetchPage:o(i=>t.listResourceTemplates(sn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resourceTemplates,"readItems")}));return Ns(a.length),{resourceTemplates:a}},e.credential)}o(U_,"listNativeMcpResourceTemplates");async function O_(e){return cn(e.upstreamServerId,(t,r)=>xr({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(sn(e.params))),e.credential)}o(O_,"callNativeMcpTool");async function $_(e){return cn(e.upstreamServerId,(t,r)=>xr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(sn(e.params))),e.credential)}o($_,"getNativeMcpPrompt");async function z_(e){return cn(e.upstreamServerId,(t,r)=>xr({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(sn(e.params))),e.credential)}o(z_,"readNativeMcpResource");var Ua=class extends A{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(E.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}};function ZO(e){return{content:[{type:"text",text:e}],isError:!0}}o(ZO,"buildToolErrorResult");function KO(e){return e.authUrl?new sr([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new Ua(e)}o(KO,"toConnectRequiredError");function JO(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(JO,"buildCredentialResolvedAttributes");function WO(e){Qe(e.context,{eventType:Z.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:JO(e.credential)})}o(WO,"emitCredentialResolvedAnalyticsEvent");function YO(e){Qe(e.context,{eventType:Z.MCP_GATEWAY_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}})}o(YO,"emitCredentialMissingAnalyticsEvent");function QO(e){return e.ownerMode==="none"?JSON.stringify(["none",e.upstreamServerId,e.authProfileId]):Nr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId})}o(QO,"readRouteBindingCredentialCacheKey");function q_(e){if(e.ownerMode!=="none")return{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}}o(q_,"readOwnedRouteBindingLookup");async function XO(e){let t=Gc(e.request);if(!t)return new Map;let r=new Map;for(let s of e.routeBindings){let c=q_(s);c!==void 0&&r.set(Nr(c),c)}if(r.size===0)return new Map;let n=[...r.values()],a=await K().authorizeAndLoadConnections({accessTokenHash:await le(t),resource:Mr(e.virtualServerId,e.request.url),virtualServerId:e.virtualServerId,upstreamConnectionKeys:n,now:re(new Date)});if(a.kind!=="authorized")return new Map;let i=new Map;return a.upstreamConnections.forEach((s,c)=>{let d=n[c];d!==void 0&&i.set(Nr(d),s.connection)}),i}o(XO,"preloadCompositeAuthorizedConnections");function e$(e){let t=new Map;return r=>{let n=QO(r),a=t.get(n);if(a)return a;let i=(async()=>{let s=await e.preloadedConnections,c=q_(r),d=c===void 0?void 0:Nr(c),p=await ji({request:e.request,routeAuth:r,...d!==void 0&&s.has(d)?{preloadedConnection:s.get(d)}:{}});if(p.kind==="connect_required")throw YO({context:e.context,payload:p.payload,routeBinding:r}),KO(p.payload);return WO({context:e.context,credential:p.credential,routeBinding:r}),p.credential})();return t.set(n,i),i}}o(e$,"createCredentialResolver");var M_=500;function t$(e){return e.length<=M_?e:`${e.slice(0,M_)}...`}o(t$,"truncateAnalyticsDetail");function r$(e){Qe(e.context,{eventType:Z.MCP_GATEWAY_CAPABILITY_COMPLETED,outcome:e.result.isError===!0?"application_error":"success",routeBinding:e.routeBinding,mcpMethod:"tools/call",capabilityName:e.toolName,capabilityType:"tool",toolResultIsError:e.result.isError===!0,applicationError:e.result.isError===!0})}o(r$,"emitToolInvocationCompletedAnalyticsEvent");function n$(e){return e instanceof sr||e instanceof Ua?{eventType:Z.MCP_GATEWAY_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof A&&e.code===E.InvalidParams?{eventType:Z.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:Z.MCP_GATEWAY_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(n$,"classifyToolInvocationFailure");function o$(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=n$(e.error);Qe(e.context,{eventType:r.eventType,outcome:r.outcome,routeBinding:e.routeBinding,mcpMethod:"tools/call",capabilityName:e.toolName,capabilityType:"tool",reasonCode:r.reasonCode,reasonClass:r.reasonClass,errorType:r.errorType,mcpErrorType:r.mcpErrorType,attributes:{detail:t$(t)}})}o(o$,"emitToolInvocationFailedAnalyticsEvent");var a$=256*1024;function i$(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new A(E.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>a$)throw new A(E.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o(i$,"assertToolArgumentsWithinLimit");function up(e){if(e.routeBindings.length===1)return e.routeBindings[0];let t=e.routeBindings.filter(r=>r.connectionPolicyName===e.upstreamPolicyName);if(t.length!==1)throw new A(E.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o(up,"findBindingForPublishedCapability");function un(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new A(E.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(un,"requireSingleTransparentBinding");function s$(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:un(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new A(E.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:up({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(s$,"resolvePublishedToolRoute");function c$(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:un(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new A(E.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:up({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(c$,"resolvePublishedPromptRoute");function u$(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:un(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new A(E.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:up({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(u$,"resolvePublishedResourceRoute");function N_(e){let t=XO({request:e.request,routeBindings:e.routeBindings,virtualServerId:e.publishedVirtualServer.virtualServerId}),r=e$({context:e.context,preloadedConnections:t,request:e.request});return{async listTools(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{tools:e.publishedVirtualServer.catalog.tools.filter(a=>a.enabled!==!1).map(Ci)};let n=un(e);return k_({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async callTool(n){let a=s$({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:n.name});try{i$(n);let i=await r(a.binding),s=await O_({upstreamServerId:a.binding.upstreamServerId,params:{...n,name:a.upstreamName},credential:i});return r$({context:e.context,routeBinding:a.binding,toolName:n.name,result:s}),e.context.log.debug({event:"upstream_tool_invocation_succeeded",toolName:n.name,upstreamName:a.upstreamName,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId,isError:s.isError===!0},"Upstream tool invocation completed"),s}catch(i){if(o$({context:e.context,routeBinding:a.binding,toolName:n.name,error:i}),i instanceof sr||i instanceof Ua)throw e.context.log.info({event:"upstream_tool_invocation_connect_required",toolName:n.name,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId,ownerMode:a.binding.ownerMode,hasAuthUrl:i instanceof sr},"Upstream tool invocation requires user to complete a connect flow"),i;let s={event:"upstream_tool_invocation_failed",code:"upstream_capability_invocation_failed",toolName:n.name,upstreamName:a.upstreamName,upstreamServerId:a.binding.upstreamServerId,authProfileId:a.binding.authProfileId};return i instanceof A&&(s.mcpErrorCode=i.code),i instanceof Error?(s.errorName=i.name,s.errorMessage=i.message,i.cause instanceof Error&&(s.causeName=i.cause.name,s.causeMessage=i.cause.message)):s.errorMessage=String(i),e.context.log.warn(s,"Upstream tool invocation failed; returning generic gateway error to MCP client"),ZO(Ke("upstream_capability_invocation_failed").publicDetail)}},async listPrompts(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{prompts:e.publishedVirtualServer.catalog.prompts.filter(a=>a.enabled!==!1).map(Ii)};let n=un(e);return T_({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async getPrompt(n){let a=c$({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:n.name});return $_({upstreamServerId:a.binding.upstreamServerId,params:{...n,name:a.upstreamName},credential:await r(a.binding)})},async listResources(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{resources:e.publishedVirtualServer.catalog.resources.filter(a=>a.enabled!==!1).map(Pi)};let n=un(e);return E_({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async listResourceTemplates(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{resourceTemplates:[]};let n=un(e);return U_({upstreamServerId:n.upstreamServerId,credential:await r(n)})},async readResource(n){let a=u$({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:n.uri});return z_({upstreamServerId:a.binding.upstreamServerId,params:{...n,uri:a.upstreamUri},credential:await r(a.binding)})}}}o(N_,"createCapabilityDispatcher");var d$="0.1.0",D_="POST",l$="POST, OPTIONS",p$=new so({draft:"7",shortcircuit:!1});function dp(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:D_}})}o(dp,"jsonRpcMethodNotAllowedResponse");function m$(e){let t={Allow:D_},r=e.headers.get("origin"),n=e.headers.get("access-control-request-method");if(r&&n){t["Access-Control-Allow-Methods"]=l$;let a=e.headers.get("access-control-request-headers");a&&(t["Access-Control-Allow-Headers"]=a)}return new Response(null,{status:204,headers:t})}o(m$,"buildOptionsResponse");function dn(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o(dn,"readJsonRpcRequestId");function Ds(e){return e&&typeof e=="object"?e.params:void 0}o(Ds,"readMcpRequestParams");function j_(e,t){return e.headers.get(t)??void 0}o(j_,"readMcpHeader");function f$(e){return{mcpProtocolVersion:j_(e,"mcp-protocol-version")??zr,mcpSessionId:j_(e,"mcp-session-id")}}o(f$,"buildServerTelemetryBase");function h$(e){if(e.headers.has("mcp-protocol-version"))return e;let t=new Headers(e.headers);return t.set("mcp-protocol-version",zr),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(h$,"ensureProtocolVersionHeader");async function lp(e,t){if(e.method==="OPTIONS")return m$(e);if(e.method==="GET")return dp("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return dp("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return dp("Only POST is supported by this virtual MCP server.");let r=bn(t),n=qr(r.virtualServerId),a=Di(t);if(n.catalog.catalogSource==="upstream_mcp"&&a.length!==1)throw t.log.error({event:"virtual_server_binding_count_invalid",code:"internal_server_error",virtualServerId:r.virtualServerId,bindingCount:a.length,catalogSource:n.catalog.catalogSource},"MCP virtual server route requires exactly one upstream binding"),g("internal_server_error",`MCP virtual server route requires exactly one upstream binding; found ${a.length}.`);let i=f$(e),s=N_({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),c=ie(e.url),d=new As({enableDnsRebindingProtection:!0,allowedOrigins:[c]}),p=new xs(n.catalog.serverInfo??{name:r.virtualServerId,version:d$},{capabilities:{prompts:{},resources:{},tools:{}},jsonSchemaValidator:p$});p.setRequestHandler(wu,async m=>Ar({methodName:"tools/list",params:Ds(m),jsonRpcRequestId:dn(m),...i},()=>s.listTools())),p.setRequestHandler(Mo,async m=>Ar({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:dn(m),...i},()=>s.callTool(m.params))),p.setRequestHandler(lu,async m=>Ar({methodName:"prompts/list",params:Ds(m),jsonRpcRequestId:dn(m),...i},()=>s.listPrompts())),p.setRequestHandler(mu,async m=>Ar({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:dn(m),...i},()=>s.getPrompt(m.params))),p.setRequestHandler(nu,async m=>Ar({methodName:"resources/list",params:Ds(m),jsonRpcRequestId:dn(m),...i},()=>s.listResources())),p.setRequestHandler(au,async m=>Ar({methodName:"resources/templates/list",params:Ds(m),jsonRpcRequestId:dn(m),...i},()=>s.listResourceTemplates())),p.setRequestHandler(cu,async m=>Ar({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:dn(m),...i},()=>s.readResource(m.params))),await p.connect(d);let l=await d.handleRequest(e);return h$(l)}o(lp,"virtualServerHandler");async function g$(e,t){return Ct("handler.mcp-virtual-server"),lp(e,t)}o(g$,"McpVirtualServerHandler");function y$(e){let t=xt(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,virtualServerId:e.virtualServerId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.config.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}o(y$,"buildRouteAuthBaseFromConnection");function L_(e){if(!e.connection.authProfiles[e.authMode])throw g("internal_server_error",`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=xt(e.authMode);return{upstreamServerId:e.connection.id,virtualServerId:e.virtualServerId,authProfileId:zn(e.connection.id,e.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.authMode,ownerMode:r.ownerMode}}o(L_,"buildRouteAuthBaseFromPolicyOptions");function B_(e,t){let n=St().byVirtualServerId.get(t);if(!n)throw g("unknown_virtual_server",`Unknown virtual server: ${t}`);let a=n.connections.find(i=>i.upstreamServerId===e);if(!a)throw g("virtual_server_upstream_mismatch",`Virtual server ${t} does not bind upstream ${e}.`);return y$({connection:a,virtualServerId:t})}o(B_,"resolveRouteAuthBase");function H_(e,t){switch(e){case"user":return ir(t.subjectId);case"shared":return oi()}}o(H_,"buildOwnerForPrincipal");function Hs(e,t){switch(e.ownerMode){case"shared":return{...e,owner:H_(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:H_(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(Hs,"resolveRouteAuthForPrincipal");function S$(e){let t=Object.keys(e.connection.authProfiles);if(t.length!==1)throw g("internal_server_error",`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];if(r===void 0)throw g("internal_server_error",`Upstream policy ${e.policyName} does not declare an auth mode.`);return Ka.parse(r)}o(S$,"readSingleAuthMode");async function pp(e,t,r,n){let a=S$({policyName:n,connection:r}),i=bn(t),s=L_({connection:r,virtualServerId:i.virtualServerId,authMode:a});if(s.ownerMode==="none")return cd(t,{...s,connectionPolicyName:n}),e;let c=Rm(t);return cd(t,{...Hs(s,c),connectionPolicyName:n}),e}o(pp,"mcpUpstreamConnectionPolicy");var mp=class extends wn{static{o(this,"McpUpstreamConnectionInboundPolicy")}#t;constructor(t,r){let n=Ri(t,r);super(n,r),this.#t=n}async handler(t,r){return Ct("policy.inbound.mcp-upstream-connection"),pp(t,r,this.#t,this.policyName)}};ae();var G_="application/json",_$="application/x-www-form-urlencoded";function w$(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(w$,"normalizeContentType");function v$(e,t){return e===t?!0:t===G_&&e.endsWith("+json")}o(v$,"contentTypeMatches");function b$(e,t){if(!t||t.length===0)return;let r=w$(e.headers.get("content-type"));if(!t.some(n=>v$(r,n)))throw g("invalid_request",`Request body must be ${t.join(" or ")}.`)}o(b$,"assertExpectedContentType");function R$(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g("invalid_request",`${r} exceeded the maximum allowed size.`)}o(R$,"assertContentLengthWithinLimit");async function V_(e,t){let r=t.label??"Request body";b$(e,t.expectedContentTypes),R$(e,t.maxBytes,r);let n=await Ai(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>g("invalid_request",`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(V_,"readBoundedTextBody");async function F_(e,t){let r=await V_(e,{...t,expectedContentTypes:[G_]});try{return JSON.parse(r)}catch(n){throw g("invalid_request","Request body must be valid JSON.",n)}}o(F_,"readBoundedJsonBody");async function Ls(e,t){let r=await V_(e,{...t,expectedContentTypes:[_$]});return new URLSearchParams(r)}o(Ls,"readBoundedFormUrlEncodedBody");var Z_=Symbol("Html");function C$(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(C$,"escapeHtml");function I$(e){return e===null||typeof e!="object"?!1:e[Z_]===!0}o(I$,"isHtml");function K_(e){return e==null||e===!1?"":Array.isArray(e)?e.map(K_).join(""):I$(e)?e.value:C$(String(e))}o(K_,"renderValue");function er(e){return{[Z_]:!0,value:e}}o(er,"trustedHtml");var Oa=er("");function ce(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=K_(t[n]),r+=e[n+1]??"";return er(r)}o(ce,"html");function Tr(e){return e.value}o(Tr,"renderHtml");var tr=er('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function rr(e){return ce`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
51
59
  ${e.styles}
52
- </style></head><body><main class="card"><header class="card__head"><img class="card__icon" src="https://www.google.com/s2/favicons?domain=${e.host}&sz=64" alt="" width="48" height="48" referrerpolicy="no-referrer" /><h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}o(nr,"renderShell");function N_(e){return T`<form class="actions" method="post" action="/oauth/setup"><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}o(N_,"renderActions");var D_=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function j_(){return T`<p>The API key could not be verified. Start the authorization flow again to try
53
- once more.</p>`}o(j_,"renderApiKeyLoginFailure");function H_(e){return T`<form class="form" method="post" action="/oauth/api-key-login" autocomplete="off" ><input type="hidden" name="state" value="${e.state}" /><label class="form__label" for="apiKey">API key</label><input class="form__input" id="apiKey" name="apiKey" type="password" required autocomplete="off" /><button class="button button--primary button--block form__submit" type="submit" >Continue</button></form>`}o(H_,"renderApiKeyLoginForm");function L_(e){return T`<div class="banner banner--alert" role="alert"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">${e.title}</p><p class="banner__message">${e.message}</p></div></div>`}o(L_,"renderBannerAlert");function B_(e){return T`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${e.message}</p></div></div>`}o(B_,"renderBannerWarning");function G_(e){return T`<section class="capability-section"><h4 class="capability-section__title">${e.label} <span class="muted">(${e.total})</span></h4><ul class="capability-list">${e.rows}${e.moreLine}</ul></section>`}o(G_,"renderCapabilitySection");var op=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),ap=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');function V_(e){return T`${e.banner}<section class="upstreams"><header class="section-label">Upstream services <span class="section-label__count">${e.sectionCount}</span></header><ul class="upstream-list">${e.cards}</ul></section>${e.fineprint}`}o(V_,"renderSetupPage");function F_(e){return T`<article class="${e.cardClass}"><div class="upstream-card__head">${e.iconFrame}<div class="upstream-card__main"><div class="upstream-card__title-row"><h3 class="upstream-card__title">${e.upstreamDisplayName}</h3>${e.control}</div><div class="upstream-card__meta">${e.host}<span>${e.authModeLabel}</span><span class="upstream-card__sep" aria-hidden="true">·</span><span>${e.ownerModeLabel}</span></div>${e.description}</div></div>${e.capabilities} ${e.scopes}</article>`}o(F_,"renderUpstreamCard");var Z_=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var h$="text/html; charset=utf-8";function K_(e,t=200){return new Response(tr(e),{status:t,headers:{"content-type":h$,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(K_,"apiKeyLoginHtmlResponse");function ip(e,t=401){return K_(nr({title:"Sign-in failed",host:e,styles:rr,heading:"Sign-in failed",subhead:"",body:j_(),footer:""}),t)}o(ip,"apiKeyLoginFailureResponse");function W_(e,t){return K_(nr({title:"Sign in",host:e,styles:rr,heading:"Sign in",subhead:T`<p class="card__subtitle">Enter your API key to continue.</p>`,body:H_({state:t}),footer:""}))}o(W_,"renderApiKeyLoginForm");ue();ue();import{errors as iw,jwtVerify as sw,SignJWT as cw}from"jose";ue();import{errors as x$,jwtVerify as A$,SignJWT as k$}from"jose";function kr(e){let t=xe().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw g("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}o(kr,"requireBrowserLoginField");ue();import{createRemoteJWKSet as y$,errors as Pa,jwtVerify as S$}from"jose";var _$=u.object({id_token:u.string().min(1),token_type:u.string().min(1).optional(),expires_in:u.number().optional(),access_token:u.string().min(1).optional(),refresh_token:u.string().min(1).optional(),scope:u.string().min(1).optional()}),w$=u.object({error:u.string().min(1).optional(),error_description:u.string().min(1).optional(),error_uri:u.string().min(1).optional()});function v$(e){let t=w$.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}o(v$,"readIdpErrorFields");function b$(e){return e instanceof Pa.JWTExpired?"expired":e instanceof Pa.JWTClaimValidationFailed?"claim":e instanceof Pa.JWSSignatureVerificationFailed?"signature":e instanceof Pa.JWKSNoMatchingKey?"jwks_no_match":e instanceof Pa.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(b$,"readJwtFailureKind");var R$=u.object({sub:Se,nonce:u.string().min(1)}).catchall(u.unknown()),sp;function C$(e){return e instanceof Error&&"cause"in e?e.cause:e}o(C$,"readErrorCause");function I$(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(I$,"readRuntimeGatewayCode");function P$(){if(!sp){let e=xe();sp=y$(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return sp}o(P$,"readFederatedJwks");async function J_(e){let t=xe(),r=kr("tokenUrl"),n=kr("clientId"),a=kr("clientSecret"),i=new URL("/oauth/callback",Ct(e.requestUrl)).toString(),s=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:n,client_secret:a});try{let{response:c,json:d}=await VS(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:s},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,...e.context===void 0?{}:{context:e.context}});if(!c.ok){let h=v$(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:mt(r),idpStatus:c.status,...h},"Federated browser login token exchange returned non-2xx from the identity provider"),g({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${h.idpError?` idp_error=${h.idpError}`:""}${h.idpErrorDescription?` idp_error_description=${h.idpErrorDescription}`:""})`)})}let p=_$.parse(d),l;try{({payload:l}=await S$(p.id_token,P$(),{issuer:t.oidc.issuer,audience:n}))}catch(h){let y={};throw Oe(y,"error",h),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:b$(h),idpHost:mt(r),expectedIssuer:t.oidc.issuer,...y},"Federated id_token failed jose verification"),h}if(l.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:mt(r),nonceMissingFromIdToken:l.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),g("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let m=R$.parse(l);return jn({sub:m.sub,data:m},e.requestUrl)}catch(c){let d=he(c)??I$(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:g("browser_login_verification_failed","Federated browser login callback could not be verified.",C$(c))}}o(J_,"exchangeFederatedAuthorizationCode");var up="zuplo_mcp_session",Y_="HS256",Q_="zuplo-mcp-gateway",X_="zuplo-mcp-gateway",T$=u.object({purpose:u.literal("gateway_browser_session"),sub:Se,browserLoginOrigin:u.string().min(1),roles:u.array(u.string().min(1)).optional(),exp:u.number().int().positive(),iat:u.number().int().positive().optional()});function E$(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;let a=r.slice(0,n).trim(),i=r.slice(n+1).trim();if(a)try{t.set(a,decodeURIComponent(i))}catch{t.set(a,i)}}return t}o(E$,"parseCookieHeader");async function ew(){return zt({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"browser-session"),"derive")})}o(ew,"getBrowserSessionKey");function cp(e){let t=new URL(se(e)),r=[`${up}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(cp,"buildBrowserSessionEvictionCookie");function U$(e){let t=new URL(se(e.requestUrl)),r=[`${up}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(U$,"serializeSessionCookie");function tw(e={}){return new URL(kr("url")).origin}o(tw,"readBrowserLoginOrigin");function dp(){return xe().browserLogin.stateTtlSeconds}o(dp,"readBrowserLoginStateTtlSeconds");function rw(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return jn(e.user,e.url)}o(rw,"resolveCurrentRequestPrincipal");async function $s(e,t={}){let r=E$(e.headers.get("cookie")).get(up);if(!r)return{};try{let{payload:n}=await A$(r,await ew(),{algorithms:[Y_],issuer:Q_,audience:X_}),a=T$.parse(n);if(a.browserLoginOrigin!==tw(t))return{evictCookie:cp(e.url)};let i={subjectId:a.sub};return a.roles&&a.roles.length>0&&(i.roles=a.roles),{principal:i}}catch(n){return n instanceof x$.JWTExpired?{evictCookie:cp(e.url)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:n instanceof Error?n.name:"unknown",errorMessage:n instanceof Error?n.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:cp(e.url)})}}o($s,"readBrowserSession");async function xa(e){let t=xe().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:tw({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new k$(r).setProtectedHeader({alg:Y_,typ:"JWT"}).setIssuer(Q_).setAudience(X_).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await ew());return U$({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o(xa,"createBrowserSessionCookie");async function nw(e){throw g("forbidden","API-key browser login is not supported in this gateway.")}o(nw,"resolveApiKeyBrowserLoginPrincipal");async function ow(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await $s(e.request,t);if(r.principal)return r.principal;let n=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!n)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");return J_({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(ow,"resolveBrowserLoginCallbackPrincipal");function aw(e){let t=xe().browserLogin,r=new URL(kr("url")),n=new URL("/oauth/callback",Ct(e.requestUrl));return Bg(r)?(r.searchParams.set("redirect_uri",n.toString()),r.searchParams.set("state",e.state),r):(r.searchParams.set("response_type","code"),r.searchParams.set("client_id",kr("clientId")),r.searchParams.set("redirect_uri",n.toString()),r.searchParams.set("scope",t.scope),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),t.audience&&r.searchParams.set("audience",t.audience),r)}o(aw,"buildBrowserLoginUrl");var O$={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},G=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=O$[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var $$=5*60,zs="HS256",Ms="zuplo-mcp-gateway",qs="zuplo-mcp-gateway",z$=u.object({purpose:u.literal("gateway_browser_login"),transactionId:yt,stateId:os,exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),M$=u.object({purpose:u.literal("gateway_authorization_setup"),transactionId:yt,stateId:os,exp:u.number().int().positive(),iat:u.number().int().positive().optional()});async function uw(){return zt({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"browser-login"),"derive")})}o(uw,"getBrowserLoginKey");async function dw(){return zt({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"authorization-csrf"),"derive")})}o(dw,"getCsrfKey");function lw(e){return{now:e.now??new Date,ttlSeconds:dp()}}o(lw,"readPendingTransactionDependencies");function q$(e,t){return e.subjectId===t.subjectId}o(q$,"principalsMatch");function pw(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(pw,"toPendingPrincipal");function mw(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,virtualServerId:e.transaction.virtualServerId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:ne(e.now),expiresAt:ne(Wt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:pw(e.principal)}}o(mw,"createTransactionRecord");async function fw(e){let{id:t,...r}=e.record,n=await J().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw g("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new G("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new G("invalid_request","redirect_uri is not registered for the client.")}}o(fw,"startPendingTransaction");async function N$(e){return new cw({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:zs,typ:"JWT"}).setIssuer(Ms).setAudience(qs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await uw())}o(N$,"signBrowserLoginState");async function hw(e){return new cw({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:ol()}).setProtectedHeader({alg:zs,typ:"JWT"}).setIssuer(Ms).setAudience(qs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await dw())}o(hw,"signCsrfToken");async function Ns(e){try{let{payload:t}=await sw(e,await uw(),{algorithms:[zs],issuer:Ms,audience:qs}),r=z$.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof iw.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}o(Ns,"verifyBrowserLoginStateToken");async function lp(e){try{let{payload:t}=await sw(e,await dw(),{algorithms:[zs],issuer:Ms,audience:qs});return{transactionId:M$.parse(t).transactionId}}catch(t){throw t instanceof iw.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(lp,"verifyCsrfToken");function Ds(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(Ds,"pendingStateErrorCode");function gw(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(gw,"toPendingAuthorizationGetResult");function D$(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(D$,"toPendingAuthorizationAdvanceResult");function yw(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Ds(e==="consumed_already"?"consumed_already":e)}o(yw,"setupDecisionErrorCode");function j$(e){if(e.kind!=="available")throw g(Ds(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(j$,"requireAwaitingSetup");function H$(e){if(e.kind!=="available")throw g(Ds(e.kind),"Browser login state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_login")throw g("oauth_state_invalid","Browser login state is not in the login phase.");return e.record}o(H$,"requireAwaitingLogin");function L$(e){if(!q$(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(L$,"requireCurrentPrincipalMatches");async function Sw(e){let t=e.now??new Date,r=dp(),n=nl(),a=ol(),i=await N$({transactionId:n,stateId:a,ttlSeconds:r}),s=mw({id:n,transaction:e.transaction,currentStateHash:await pe(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await fw({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:i,browserLoginUrl:aw({state:i,nonce:a,virtualServerId:s.virtualServerId,requestUrl:e.requestUrl})}}o(Sw,"startAwaitingLogin");async function _w(e){let{now:t,ttlSeconds:r}=lw(e),n=nl(),a=await hw({transactionId:n,ttlSeconds:r}),i=mw({id:n,transaction:e.transaction,currentStateHash:await pe(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await fw({record:i,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:a}}o(_w,"startAwaitingSetup");async function pp(e){let{now:t,ttlSeconds:r}=lw(e),n=await Ns(e.browserLoginStateToken),a=await hw({transactionId:n.transactionId,ttlSeconds:r}),i=D$(await J().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await pe(e.browserLoginStateToken),nextStateHash:await pe(a),nextPhase:"awaiting_setup",principal:pw(e.principal),now:ne(t)}));if(i.kind!=="advanced")throw g(Ds(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:a}}o(pp,"completeLogin");async function ww(e){let t=e.now??new Date,r=await Ns(e.browserLoginStateToken);return H$(gw(await J().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await pe(e.browserLoginStateToken),now:ne(t)})))}o(ww,"getAwaitingLogin");async function vw(e){let t=await mp(e);return L$({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(vw,"getSetup");async function mp(e){let t=e.now??new Date,r=await lp(e.csrfToken);return j$(gw(await J().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await pe(e.csrfToken),now:ne(t)})))}o(mp,"getSetupTransaction");async function B$(e){let t=await lp(e.csrfToken),r=Jt(),n=ne(Wt(e.now,$$)),a=await J().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await pe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await pe(r),authorizationCodeExpiresAt:n,grantId:Hg(),now:ne(e.now)});if(a.kind!=="approved")throw g(a.kind==="cancelled"?"oauth_state_invalid":yw(a.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(a.transaction.redirectUri);return i.searchParams.set("code",r),a.transaction.clientState&&i.searchParams.set("state",a.transaction.clientState),i}o(B$,"createAuthorizationCodeRedirectWithDecision");async function G$(e){let t=await lp(e.csrfToken),r=await J().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await pe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:ne(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":yw(r.kind),"Authorization setup state is invalid, expired, or already used.");return V$({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}o(G$,"createCancelRedirectWithDecision");function V$(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}o(V$,"buildClientCancelRedirect");async function bw(e){let t=e.now??new Date;return B$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(bw,"approve");async function Rw(e){let t=e.now??new Date;return G$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(Rw,"cancel");ue();var F$=1e4,Z$=5*1024,K$=2,W$=90*24*60*60,fp=["authorization_code","refresh_token"],hp=["code"],J$=u.object({client_name:u.string().min(1).optional(),redirect_uris:u.array(u.string().min(1)).min(1),grant_types:u.array(u.enum(fp)).min(1).max(2).optional(),response_types:u.array(u.enum(hp)).min(1).max(1).optional(),scope:u.literal(ye).optional(),token_endpoint_auth_method:Xd.default("client_secret_basic")});function Y$(e){try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(Y$,"isCimdClientIdCandidate");function Aa(e,t="invalid_request"){if(Q$(e))throw new G(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new G(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new G(t,"redirect_uris must not include credentials or fragments.");if(!(r.protocol==="https:"||Le(r)))throw new G(t,"redirect_uris must use HTTPS except loopback HTTP redirects for local clients.")}o(Aa,"assertValidRedirectUri");function Q$(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}o(Q$,"hasForbiddenRawRedirectUriCharacter");async function X$(e){let{response:t,json:r}=await FS(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:K$,maxResponseBytes:Z$,timeoutMs:F$});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let n=jg.parse(r);if(n.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");if(n.token_endpoint_auth_method!=="none")throw g("invalid_request","CIMD clients must use token_endpoint_auth_method none until private_key_jwt is implemented.");return n}o(X$,"fetchCimdMetadata");async function ez(e){let t=bs(e),r=await X$({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(ez,"resolveCimdClient");async function Cw(e,t){let r=Be.parse(e);if(Y$(r)){if(!xe().gateway.cimdEnabled)throw new G("invalid_client","OAuth client is not registered.");try{return await ez(r)}catch{throw new G("invalid_client","OAuth client is not registered.")}}let n=await J().readClient({clientId:r});if(n.kind==="found"){let a=n.client,i={kind:"dcr",clientId:r,metadata:{client_id:a.clientId,client_name:a.clientName,redirect_uris:a.redirectUris,token_endpoint_auth_method:a.tokenEndpointAuthMethod}};return a.hashedClientSecret&&(i.hashedClientSecret=a.hashedClientSecret),i}throw new G("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(Cw,"resolveClient");function Iw(e,t){if(!e.metadata.redirect_uris.some(r=>Lg(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}o(Iw,"assertRedirectRegistered");function tz(e){let t=Pw(e.grant_types),r=e.response_types??[...hp];if(!rz(t))throw new G("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!nz(r))throw new G("invalid_client_metadata","response_types must be code.");if(!oz(e.scope))throw new G("invalid_client_metadata",`Only the ${ye} scope is supported.`)}o(tz,"assertSupportedDcrRequest");function Pw(e){return e===void 0?[...fp]:Array.from(new Set(e))}o(Pw,"normalizeGrantTypes");function rz(e){return e.length===0?!1:e.every(t=>fp.includes(t))}o(rz,"isSupportedGrantTypes");function nz(e){return e.length===hp.length&&e[0]==="code"}o(nz,"isSupportedResponseTypes");function oz(e){return e===void 0||e===ye}o(oz,"isSupportedDcrScope");function ka(e){if(e===void 0||e===ye)return ye;throw new G("invalid_request",`Only the ${ye} scope is supported.`)}o(ka,"assertSupportedOAuthScope");function to(e,t){let r;try{r=new URL(t)}catch{throw new G("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new G("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!Le(r))throw new G("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=se(e),a=bg(),i=a?[...a.byVirtualServerId.values()].find(s=>new URL(s.routePath,n).toString()===t):void 0;if(!i)throw new G("invalid_target","resource must match a published virtual MCP server.");return i}o(to,"resolveResource");async function xw(e){let t;try{t=J$.parse(e)}catch(l){if(l instanceof u.ZodError){let m=l.issues.some(h=>h.path[0]==="redirect_uris");throw new G(m?"invalid_redirect_uri":"invalid_client_metadata",l.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:l})}throw l}tz(t);for(let l of t.redirect_uris)Aa(l,"invalid_redirect_uri");let r=new Date,n=Be.parse(`dcr:${crypto.randomUUID()}`),a=Wt(r,W$),i=Math.floor(r.getTime()/1e3),s=Math.floor(a.getTime()/1e3),c={client_id:n,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,grant_types:Pw(t.grant_types),response_types:["code"],scope:ye,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:i},d={clientId:n,clientName:String(c.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:ne(r),clientExpiresAt:ne(a)};if(t.token_endpoint_auth_method!=="none"){let l=Jt();d.hashedClientSecret=await pe(l),d.clientSecretExpiresAt=ne(a),c.client_secret=l,c.client_secret_expires_at=s,c.client_secret_issued_at=i}if((await J().registerClient(d)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");return c}o(xw,"registerDownstreamClient");function az(e){try{return new URL(e).host}catch{return""}}o(az,"safeHostFromOrigin");var iz=8;function yp(e){let t=e.trim();try{let r=new URL(t);if(r.protocol==="https:")return r.toString()}catch{}if(/^data:image\/(?:png|jpe?g|webp);/i.test(t))return t}o(yp,"safeIconSrc");function sz(e,t){if(e)try{let r=new URL(t).origin,n=new URL(e,r);return n.origin!==r||!n.pathname.startsWith("/auth/connections/")?void 0:n.toString()}catch{return}}o(sz,"safeGatewayConnectHref");function cz(e){if(e==="any")return Number.POSITIVE_INFINITY;let t=/^(\d+)x(\d+)$/.exec(e);return t?Math.max(Number(t[1]),Number(t[2])):0}o(cz,"parseIconSize");function uz(e,t){let r=e.filter(a=>a.theme===t);if(r.length>0)return r;let n=e.filter(a=>a.theme===void 0);return n.length>0?n:e}o(uz,"selectIconCandidates");function dz(e){return yp(e.src)?e.sizes&&e.sizes.length>0?Math.max(...e.sizes.map(cz)):0:-1}o(dz,"readIconScore");function Aw(e,t){if(!e||e.length===0)return;let r=uz(e,t),n,a=-1;for(let i of r){let s=dz(i);s>a&&(n=i,a=s)}return n}o(Aw,"pickIcon");function lz(e,t){let r=Aw(e,"light");if(!r)return T`<span class="icon-frame icon-frame--fallback" aria-hidden="true">${ap}</span>`;let n=yp(r.src);return n?T`<span class="icon-frame"><img src="${n}" alt="${t}" loading="lazy" decoding="async"></span>`:T`<span class="icon-frame icon-frame--fallback" aria-hidden="true">${ap}</span>`}o(lz,"renderIconFrame");function Hs(e,t){let r=Aw(e,"light");if(!r)return _e;let n=yp(r.src);return n?T`<img class="inline-icon" src="${n}" alt="${t}" loading="lazy" decoding="async">`:_e}o(Hs,"renderInlineIcon");function pz(e){switch(e){case"user":return"your account";case"shared":return"shared by your team";case"none":return"gateway-managed"}}o(pz,"ownerModeLabel");function mz(e){return e.endsWith("_oauth")||e==="oauth"?"OAuth":e.includes("static_secret")?"static credential":e.replaceAll("_"," ")}o(mz,"authModeLabel");function fz(e){switch(e){case"active":return T`<span class="status-badge status-badge--success">Connected</span>`;case"not_connected":return T`<span class="status-badge status-badge--neutral">Not connected</span>`;case"reconsent_required":return T`<span class="status-badge status-badge--warning">Reconnect required</span>`}}o(fz,"statusBadge");function hz(e){if(!e)return _e;let t=[];return e.destructiveHint&&t.push(T`<span class="badge badge--destructive" title="This tool may modify or delete data on your behalf.">destructive</span>`),e.readOnlyHint&&t.push(T`<span class="badge badge--muted" title="This tool only reads data and does not modify state.">read-only</span>`),e.openWorldHint&&t.push(T`<span class="badge badge--muted" title="This tool can access arbitrary URIs supplied at call time.">open-world</span>`),t.length>0?T`<span class="badge-row">${t}</span>`:_e}o(hz,"annotationBadges");function kw(e){let t=0,r=0;for(let n of e.tools)n.annotations?.destructiveHint===!0&&(t+=1),n.annotations?.readOnlyHint===!0&&(r+=1);return{tools:e.tools.length,prompts:e.prompts.length,resources:e.resources.length,destructiveTools:t,readOnlyTools:r}}o(kw,"summarizeCapabilities");function gz(e){let t=e.annotations?.title??e.title??e.name,r=e.description?T`<span class="capability-row__description">${e.description}</span>`:_e;return T`<li class="capability-row">${Hs(e.icons,t)}<span class="capability-row__name">${t}</span>${hz(e.annotations)}${r}</li>`}o(gz,"renderToolRow");function yz(e){let t=e.title??e.name,r=e.description?T`<span class="capability-row__description">${e.description}</span>`:_e;return T`<li class="capability-row">${Hs(e.icons,t)}<span class="capability-row__name">${t}</span>${r}</li>`}o(yz,"renderPromptRow");function Sz(e){let t=e.title??e.name,r=e.mimeType===void 0?_e:T` · ${e.mimeType}`,n=e.description===void 0?_e:T` — ${e.description}`,a=T`<span class="capability-row__description"><code>${e.uri}</code>${r}${n}</span>`;return T`<li class="capability-row">${Hs(e.icons,t)}<span class="capability-row__name">${t}</span>${a}</li>`}o(Sz,"renderResourceRow");function gp(e,t,r,n){if(t===0)return _e;let a=r.slice(0,iz),i=t-a.length,s=i>0?T`<li class="capability-row capability-row--more">+ ${i} more</li>`:_e;return G_({label:e,total:t,rows:T`${a.map(n)}`,moreLine:s})}o(gp,"renderCapabilitySection");function js(e,t,r=!1){return r?T`<span class="count-pill count-pill--destructive"><span class="count-pill__num">${t}</span><span class="count-pill__label">${e}</span></span>`:T`<span class="count-pill"><span class="count-pill__num">${t}</span><span class="count-pill__label">${e}</span></span>`}o(js,"countPill");function _z(e){let t=kw(e);if(t.tools+t.prompts+t.resources===0)return T`<div class="upstream-card__capabilities upstream-card__capabilities--empty">No tools, prompts, or resources advertised.</div>`;let n=[];t.tools>0&&n.push(js(t.tools===1?"tool":"tools",t.tools)),t.prompts>0&&n.push(js(t.prompts===1?"prompt":"prompts",t.prompts)),t.resources>0&&n.push(js(t.resources===1?"resource":"resources",t.resources)),t.destructiveTools>0&&n.push(js("destructive",t.destructiveTools,!0));let a=[gp("Tools",t.tools,e.tools,gz),gp("Prompts",t.prompts,e.prompts,yz),gp("Resources",t.resources,e.resources,Sz)];return T`<details class="upstream-card__capabilities"><summary class="capabilities-summary"><span class="capabilities-summary__counts">${n}</span><span class="capabilities-summary__chevron" aria-hidden="true">${op}</span></summary><div class="capabilities-detail">${a}</div></details>`}o(_z,"renderUpstreamCapabilities");function wz(e){if(!e||e.length===0)return _e;let t=e.map(n=>T`<code class="scope-chip">${n}</code>`),r=e.length===1?"scope":"scopes";return T`<details class="upstream-card__scopes"><summary class="scopes-summary"><span>Requested ${r} <span class="muted">(${e.length})</span></span><span class="capabilities-summary__chevron" aria-hidden="true">${op}</span></summary><div class="scopes-list">${t}</div></details>`}o(wz,"renderUpstreamScopes");function vz(e,t){if(e.ownerMode!=="user")return _e;let r=sz(e.connectUrl,t);if(!r)return _e;let n=e.status==="active"?"Redo auth":e.status==="reconsent_required"?"Reconnect":"Connect",a=e.status==="active"?"Reconnect this upstream account or approve updated scopes.":void 0;return T`<a class="button button--secondary button--small" href="${r}"${a===void 0?_e:T` title="${a}"`}>${n}</a>`}o(vz,"renderActionButton");function bz(e,t){let r=vz(e,t);return tr(r)!==""?r:fz(e.status)}o(bz,"renderUpstreamControl");function Rz(e,t){let n=e.ownerMode==="user"&&e.status!=="active"?"upstream-card upstream-card--needs-action":"upstream-card",a=e.description?T`<p class="upstream-card__description">${e.description}</p>`:_e,i=e.transportHost?T`<code class="upstream-card__host">${e.transportHost}</code><span class="upstream-card__sep" aria-hidden="true">·</span>`:_e;return F_({cardClass:n,iconFrame:lz(e.serverIcons,e.upstreamDisplayName),upstreamDisplayName:e.upstreamDisplayName,control:bz(e,t),host:i,authModeLabel:mz(e.authMode),ownerModeLabel:pz(e.ownerMode),description:a,capabilities:_z(e.capabilities),scopes:wz(e.scopesRequested)})}o(Rz,"renderUpstreamCard");function Cz(e){return e.reduce((t,r)=>{let n=kw(r.capabilities);return t.tools+=n.tools,t.prompts+=n.prompts,t.resources+=n.resources,t.destructiveTools+=n.destructiveTools,t.readOnlyTools+=n.readOnlyTools,t},{tools:0,prompts:0,resources:0,destructiveTools:0,readOnlyTools:0})}o(Cz,"aggregateCapabilities");function Iz(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(Iz,"deriveMode");function Pz(e){if(e.mode==="setup"){let n=e.upstreams.filter(c=>c.ownerMode==="user"&&c.status!=="active"),a=n.length>0&&n.every(c=>c.status==="reconsent_required"),i=n.length===1?"the service":`the ${n.length} services`,s=a?T`Re-authorize ${i} below to refresh access. Authorization will continue automatically once each is ready.`:T`Connect ${i} below before continuing. Authorization will continue automatically once each is ready.`;return B_({icon:Z_,message:s})}let t=Cz(e.upstreams);if(t.destructiveTools===0)return _e;let r=t.destructiveTools===1?"tool can":"tools can";return L_({icon:D_,title:T`${t.destructiveTools} ${r} modify or delete data`,message:T`Review the destructive tools below before authorizing <strong>${e.clientDisplayName}</strong>.`})}o(Pz,"renderBanner");function xz(e){let t=e.mode==="setup"?T`disabled aria-disabled="true" title="Connect the required upstream services first"`:_e;return N_({state:e.state,authorizeAttrs:t})}o(xz,"renderActions");function Sp(e){let t=Iz(e.upstreams),r=[...e.upstreams].sort((h,y)=>{let _=o(w=>w.ownerMode!=="user"?2:w.status==="active"?1:0,"blockedRank"),S=_(h)-_(y);return S!==0?S:h.upstreamDisplayName.localeCompare(y.upstreamDisplayName)}),n=Hs(e.virtualServerIcons,e.virtualServerDisplayName),a=Pz({mode:t,upstreams:r,clientDisplayName:e.clientDisplayName}),i=r.length===0?T`<li class="empty">This virtual server does not declare any upstream services.</li>`:T`${r.map(h=>T`<li>${Rz(h,e.gatewayOrigin)}</li>`)}`,s=xz({mode:t,state:e.state}),c=t==="grant"?T`<p class="card__fineprint"><strong>${e.clientDisplayName}</strong> will receive a token scoped to <strong>${e.virtualServerDisplayName}</strong>. You can revoke access at any time.</p>`:T`<p class="card__fineprint">Authorization continues automatically once every required service is connected.</p>`,d=r.length>0?T`(${r.length})`:_e,p=T`<p class="card__subtitle"><strong>${e.clientDisplayName}</strong> wants to access <strong>${n}${e.virtualServerDisplayName}</strong></p>${e.virtualServerDescription?T`<p class="card__description">${e.virtualServerDescription}</p>`:_e}${e.principalLabel?T`<span class="card__principal" title="Signed in as ${e.principalLabel}">${e.principalLabel}</span>`:_e}`,l=V_({banner:a,sectionCount:d,cards:i,fineprint:c}),m=T`<footer class="card__footer">${s}</footer>`;return tr(nr({title:`Authorize access \xB7 ${e.virtualServerDisplayName}`,host:az(e.gatewayOrigin),styles:rr,heading:"Authorize access",subhead:p,body:l,footer:m}))}o(Sp,"renderConsentPage");function Az(e){try{return new URL(e).host}catch{return}}o(Az,"safeUrlHost");function kz(e){if(e.mode==="user_oauth"||e.mode==="shared-oauth")return e.oauth.scopes}o(kz,"readOAuthScopes");function _p(e){return e!==void 0&&e.length>0}o(_p,"hasItems");function Tz(e){let t=e.registeredConnection.config.serverInfo?.icons;if(_p(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&_p(r)?r:void 0}o(Tz,"readServerIcons");async function Ez(e){if(!(e.returnTo===void 0||!e.isUserOwned))return Il({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,virtualServerId:e.virtualServer.virtualServerId,returnTo:e.returnTo})}o(Ez,"readConnectUrl");function an(e,t){return t===void 0?{}:{[e]:t}}o(an,"optionalRequirementField");function Uz(e){return e.isUserOwned?oy(e.connection):{connected:!0,status:"active"}}o(Uz,"readSetupConnectionStatus");function Oz(e){let t=kz(e);return _p(t)?t:void 0}o(Oz,"readScopesRequested");function $z(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o($z,"readUpdatedAt");function zz(e){if(e.virtualServer.catalog.catalogSource!=="openapi")return{tools:[],prompts:[],resources:[]};let t=o(r=>r.upstreamPolicyName===e.registeredConnection.policyName,"ownsCapability");return{tools:e.virtualServer.catalog.tools.filter(r=>r.enabled!==!1&&t(r)).map(Wi),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(Ji),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map(Yi)}}o(zz,"readVirtualServerCapabilities");async function Mz(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:i}=e.registeredConnection,s=ps(r),c=s==="user",d=Uz({connection:e.connection,isUserOwned:c}),p=await Ez({...e,connected:d.connected,isUserOwned:c});return{upstreamServerId:a,authProfileId:i,authMode:r,ownerMode:s,upstreamDisplayName:n.displayName,status:d.status,connected:d.connected,capabilities:zz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...an("description",n.description),...an("transportHost",Az(n.transport.baseUrl)),...an("scopesRequested",Oz(t)),...an("serverIcons",Tz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...an("connectUrl",p),...an("updatedAt",$z({connectionStatus:d,isUserOwned:c})),...an("expiresAt",e.connection?.expiresAt)}}o(Mz,"buildSetupRequirement");function Tw(e){let t=ht().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(Tw,"requireVirtualServer");async function wp(e){let t=Tw(e.transaction.virtualServerId),r=Rr(e.transaction.principal.subjectId),n=[],a=new Map;for(let c of t.connections)ps(c.authMode)==="user"&&(a.set(c,n.length),n.push({owner:r,upstreamServerId:c.upstreamServerId,authProfileId:c.authProfileId}));let i=await J().batchGetUpstreamConnections(n),s=[];for(let c of t.connections){let d=ps(c.authMode)==="user",p=a.get(c);s.push(await Mz({connection:d&&p!==void 0?i[p]:void 0,registeredConnection:c,virtualServer:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r}))}return s}o(wp,"requirementsForSetup");function qz(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(qz,"readVirtualServerDisplayName");async function vp(e){let t=Tw(e.transaction.virtualServerId),r=qz({virtualServer:t}),n=await J().readClient({clientId:e.transaction.clientId}),a=n.kind==="found"?n.client:void 0,i={gatewayOrigin:se(e.requestUrl),virtualServerDisplayName:r,clientDisplayName:a?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},s=t.serverInfo?.title;return s!==void 0&&s!==r&&(i.virtualServerDescription=s),i}o(vp,"consentContext");function Ew(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(Ew,"hasUnresolvedUserUpstream");var Nz=["mcp_user"],Dz="dev-browser-user",jz=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/mcp/{virtualServerId} or add resource={protected resource URI from protected-resource metadata}."].join(" "),Hz=u.object({response_type:u.literal("code"),client_id:u.string().min(1),redirect_uri:u.string().min(1),resource:u.url(),code_challenge:u.string().min(43),code_challenge_method:ts,state:u.string().min(1).optional(),scope:u.literal(ye).default(ye)}),Lz=u.enum(["continue","approve","cancel"]).default("continue"),Bz=u.object({state:u.string().min(1),decision:Lz}),Gz=u.object({state:u.string().min(1),apiKey:u.string().min(1)}),sn=class extends Error{static{o(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function Uw(e){return typeof e=="string"&&e.length>0?e:void 0}o(Uw,"readQueryString");function Vz(e,t){let r=Uw(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new G("invalid_target",jz)}let n=Wr(t,e.url);if(r===void 0||r===n)return n;throw new G("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(Vz,"requireAuthorizeResource");async function Fz(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await $s(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let i=rw(e);return{principal:i,setCookie:await xa({principal:i,requestUrl:e.url,virtualServerId:t})}}o(Fz,"resolveBrowserPrincipal");async function Zz(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await $s(e,n);if(!a.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(Zz,"requireSetupPrincipal");async function Ow(e){let t=await wp({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:`/oauth/setup?state=${encodeURIComponent(e.csrfToken)}`}),r=await vp({transaction:e.transaction,requestUrl:e.requestUrl}),n={kind:"setup_page",html:Sp({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(Ow,"renderSetup");function Kz(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;if(t==="private_key_jwt")throw new G("invalid_client","OAuth client authentication method is not supported.");return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(Kz,"toAuthorizationTransactionClient");async function bp(e,t={}){let r=Hz.parse({...e.query,resource:Vz(e,t.virtualServerId),state:Uw(e.query.state)}),n=ka(r.scope);Aa(r.redirect_uri);let a=new Date,i=Be.parse(r.client_id),s=await Cw(r.client_id,a);Iw(s,r.redirect_uri);try{let c=to(e.url,r.resource),d=Kz(s);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:i,virtualServerId:c.virtualServerId,scope:n,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved");let p={clientId:s?.clientId??i,...d===void 0?{}:{client:d},redirectUri:r.redirect_uri,resource:r.resource,virtualServerId:c.virtualServerId,scope:n,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:l,setCookie:m}=await Fz(e,c.virtualServerId,t.context);if(!l){let y=await Sw({transaction:p,requestUrl:e.url,now:a});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:i,virtualServerId:c.virtualServerId},"Downstream OAuth authorize: redirecting to browser login (no session)");let _={kind:"redirect",location:y.browserLoginUrl};return m!==void 0&&(_.setCookie=m),_}let h=await _w({transaction:p,principal:l,now:a});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:i,virtualServerId:c.virtualServerId,subjectId:l.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),Ow({transaction:h.transaction,csrfToken:h.csrfToken,requestUrl:e.url,setCookie:m})}catch(c){throw Wz({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}o(bp,"authorizeDownstreamClient");function Wz(e){if(e.cause instanceof sn)return e.cause;let t=Jz(e.cause);return t?new sn({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(Wz,"toDownstreamAuthorizeRedirectError");function Jz(e){if(e instanceof G)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof u.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}o(Jz,"mapToOAuthRedirectError");async function $w(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let p=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,l=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...p===void 0?{}:{idpErrorDescription:p},...l===void 0?{}:{idpErrorUri:l}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",p??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let a=await Ns(n),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let s=await ow(i),c=await pp({browserLoginStateToken:n,principal:s}),d=await Ow({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return d.setCookie=await xa({principal:s,requestUrl:e.url,virtualServerId:c.transaction.virtualServerId}),d}o($w,"completeBrowserLoginCallback");async function zw(e){let t=xe(),r=new URL(e.url);if(!Le(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw g("oauth_state_invalid","Local browser login is missing state.");let a=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",se(e.url)),i=new URL(se(e.url)).origin;if(a.origin!==i||a.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");a.searchParams.set("state",n);let s={subjectId:Se.parse(Dz),roles:Nz};return{kind:"redirect",location:a,setCookie:await xa({principal:s,requestUrl:e.url})}}o(zw,"completeLocalDevBrowserLogin");async function Mw(e){let t=Gz.parse(e.body),r=await ww({browserLoginStateToken:t.state}),n=await nw({apiKey:t.apiKey,virtualServerId:r.virtualServerId}),a=await pp({browserLoginStateToken:t.state,principal:n});await c_({apiKey:t.apiKey,principal:n,virtualServerId:a.transaction.virtualServerId});let i=new URL("/oauth/setup",Ct(e.request.url));return i.searchParams.set("state",a.csrfToken),{kind:"redirect",location:i,setCookie:await xa({principal:n,requestUrl:e.request.url,virtualServerId:a.transaction.virtualServerId})}}o(Mw,"completeApiKeyBrowserLogin");function Yz(e){let t=e.method==="POST"?e.body:e.query;return Bz.parse(t)}o(Yz,"readSetupContinueRequest");async function qw(e){let{state:t,decision:r}=Yz({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,a=await mp({csrfToken:t,now:n}),i=await Zz(e.request,a.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await Rw({csrfToken:t,currentBrowserPrincipal:i,now:n})};let s=await vw({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await wp({transaction:s,requestUrl:e.request.url,returnTo:`/oauth/setup?state=${encodeURIComponent(t)}`});if(r==="continue"||Ew(c)){let d=await vp({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:Sp({state:t,virtualServerId:s.virtualServerId,upstreams:c,...d})}}return{kind:"redirect",location:await bw({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(qw,"continueDownstreamAuthorizeSetup");ue();var Qz=new Set(["authorization_code","refresh_token"]),Xz=u.discriminatedUnion("grant_type",[u.object({grant_type:u.literal("authorization_code"),code:u.string().min(1),redirect_uri:u.string().min(1),client_id:u.string().min(1).optional(),code_verifier:rs,resource:u.url(),scope:u.literal(ye).optional(),client_secret:u.string().min(1).optional()}),u.object({grant_type:u.literal("refresh_token"),refresh_token:u.string().min(1),client_id:u.string().min(1).optional(),resource:u.url(),scope:u.literal(ye).optional(),client_secret:u.string().min(1).optional()})]);function eM(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!Qz.has(t)))throw new G("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(eM,"assertSupportedGrantType");var tM=u.object({token:u.string().min(1),client_id:u.string().min(1).optional(),token_type_hint:u.string().optional(),client_secret:u.string().min(1).optional()});function Nw(){return xe().gateway.accessTokenTtlSeconds}o(Nw,"readAccessTokenTtlSeconds");function rM(){return xe().gateway.refreshTokenTtlSeconds}o(rM,"readRefreshTokenTtlSeconds");function nM(e,t){let r=Nw(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:ne(Wt(e,a)),expiresIn:a}}o(nM,"calculateAccessTokenExpiresAt");function Dw(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new G("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new G("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new G("invalid_client","Malformed HTTP Basic client authentication.")}}o(Dw,"readBasicClientSecret");function jw(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new G("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t===void 0)throw new G("invalid_client","Client authentication or client_id is required.");return t}o(jw,"resolveAuthenticatedClientId");function Hw(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new G("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}o(Hw,"resolveClientSecretInput");async function Lw(e){let t=Be.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await pe(e.clientSecret)}}o(Lw,"buildRuntimeHttpClientAuth");async function Bw(e){eM(e.body);let t=Xz.parse(e.body),r=Dw(e.authorizationHeader),n=jw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=new Date,i=Hw({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});return oM({parsed:t,clientId:n,clientSecretInput:i,now:a,requestUrl:e.requestUrl})}o(Bw,"exchangeDownstreamToken");async function oM(e){let t=await Lw({clientId:e.clientId,...e.clientSecretInput});if(e.parsed.grant_type==="authorization_code"){Aa(e.parsed.redirect_uri),ka(e.parsed.scope),e.parsed.resource!==void 0&&to(e.requestUrl??e.parsed.resource,e.parsed.resource);let c=Jt(),d=Jt(),p=ne(Wt(e.now,rM())),l=nM(e.now,p),m=await J().exchangeAuthorizationCode({clientAuth:t,codeHash:await pe(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await Kg(e.parsed.code_verifier),currentRefreshTokenHash:await pe(c),accessTokenHash:await pe(d),grantExpiresAt:p,accessTokenExpiresAt:l.expiresAt,now:ne(e.now)});if(m.kind==="invalid_client")throw new G("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new G("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new G("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return{access_token:d,token_type:"Bearer",expires_in:l.expiresIn,refresh_token:c,scope:m.grant.scope,resource:m.grant.resource}}ka(e.parsed.scope),e.parsed.resource!==void 0&&to(e.requestUrl??e.parsed.resource,e.parsed.resource);let r=Jt(),n=Jt(),a=ne(Wt(e.now,Nw())),i=await J().refreshToken({clientAuth:t,currentRefreshTokenHash:await pe(e.parsed.refresh_token),nextRefreshTokenHash:await pe(r),accessTokenHash:await pe(n),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:a,now:ne(e.now)});if(i.kind==="invalid_client")throw new G("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new G("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new G("invalid_grant","Refresh token is invalid, expired, or revoked.");to(e.requestUrl??i.grant.resource,i.grant.resource);let s=i.accessToken.expiresAt;return{access_token:n,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(s).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}o(oM,"exchangeDownstreamTokenWithRuntimeHttp");async function Gw(e){let t=tM.parse(e.body),r=Dw(e.authorizationHeader),n=jw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=Hw({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret}),i=new Date;if((await J().revokeOAuthToken({clientAuth:await Lw({clientId:n,...a}),tokenHash:await pe(t.token),now:ne(i)})).kind==="invalid_client")throw new G("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed")}o(Gw,"revokeDownstreamToken");var aM=64*1024,iM=16*1024,sM="text/html; charset=utf-8";function cM(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(cM,"formDataToObject");async function uM(e){return z_(e,{maxBytes:aM,label:"Request body"})}o(uM,"readJsonBody");async function Ls(e){return cM(await Os(e,{maxBytes:iM,label:"Request body"}))}o(Ls,"readFormBody");async function Bs(e,t,r){let n=he(r),a=r instanceof u.ZodError?Vw(r):r instanceof Error?r.message:void 0,i={code:n??"invalid_request"};return a!==void 0&&(i.detail=a),ft(e,t,i)}o(Bs,"handleProblem");function Ta(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}o(Ta,"oauthErrorResponse");function dM(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(dM,"readOAuthProtocolHeaders");function lM(e,t){let r=Qe("internal_server_error");return Ta({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:dM(e,t)})}o(lM,"oauthProtocolErrorResponse");function pM(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(pM,"readZodOAuthErrorCode");function mM(e){let t={error:pM(e)},r=Vw(e);return r!==void 0&&(t.errorDescription=r),Ta(t)}o(mM,"oauthZodErrorResponse");function fM(e){let t=he(e);if(t===void 0)return;let r=Qe(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:gM(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,Ta(n)}o(fM,"oauthGatewayProblemResponse");function hM(){let t={error:"server_error",status:500,errorDescription:Qe("internal_server_error").publicDetail};return Ta(t)}o(hM,"oauthFallbackErrorResponse");function gM(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(gM,"readOAuthStatus");function ro(e,t={}){return e instanceof sn?yM(e):e instanceof G?lM(e,t):e instanceof u.ZodError?mM(e):fM(e)??hM()}o(ro,"oauthProblemResponse");function Mt(e,t,r){let n={event:t},a=!1;if(r instanceof G)n.oauthError=r.errorCode,n.status=r.status,Oe(n,"error",r);else if(r instanceof sn)n.oauthError=r.errorCode,Oe(n,"error",r);else if(r instanceof u.ZodError){n.code="invalid_request",Oe(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=he(r);if(i!==void 0){let s=Qe(i);n.code=i,n.status=s.status,s.oauthError!==void 0&&(n.oauthError=s.oauthError),a=s.status>=500||s.oauthError==="server_error",Oe(n,"error",r)}else a=!0,Oe(n,"error",r)}if(a){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(Mt,"logUnexpectedOAuthHandlerError");function yM(e){let t;try{t=new URL(e.redirectUri)}catch{return Ta({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}o(yM,"downstreamAuthorizeRedirectErrorResponse");function Vw(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Vw,"formatZodErrorDetail");function SM(e,t){let r={event:"browser_login_callback_failed",code:he(t)??"invalid_request"};Oe(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(SM,"logBrowserLoginCallbackFailure");function Rp(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}o(Rp,"redirectResultResponse");function Gs(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":sM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return Rp(e)}o(Gs,"authorizeResultResponse");async function Fw(e,t){try{return Response.json(il(e.url))}catch(r){return Mt(t,"oauth_authorization_server_metadata_failed",r),Bs(e,t,r)}}o(Fw,"authorizationServerMetadataHandler");async function Zw(e,t){try{let r=Pe.parse(e.params.virtualServerId),n=ea(r);return Response.json(Gg({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return Mt(t,"oauth_authorization_server_metadata_failed",r),Bs(e,t,r)}}o(Zw,"scopedAuthorizationServerMetadataHandler");async function Kw(e,t){try{let r=await xw(await uM(e)),n=r;return t.log.info({event:"oauth_dcr_client_registered",clientId:typeof n.client_id=="string"?n.client_id:void 0,clientName:typeof n.client_name=="string"?n.client_name:void 0,redirectUriCount:Array.isArray(n.redirect_uris)?n.redirect_uris.length:void 0,tokenEndpointAuthMethod:typeof n.token_endpoint_auth_method=="string"?n.token_endpoint_auth_method:void 0},"OAuth Dynamic Client Registration completed"),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Mt(t,"oauth_register_failed",r),ro(r)}}o(Kw,"registerHandler");async function Ww(e,t){try{return Gs(await bp(e,{context:t}))}catch(r){return Mt(t,"oauth_authorize_failed",r),ro(r,{includeInvalidClientChallenge:!1})}}o(Ww,"authorizeHandler");async function Jw(e,t){try{let r=Pe.parse(e.params.virtualServerId),n=ea(r);return Gs(await bp(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return Mt(t,"oauth_authorize_scoped_failed",r),ro(r,{includeInvalidClientChallenge:!1})}}o(Jw,"scopedAuthorizeHandler");async function Yw(e,t){try{let r=await $w(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Gs(r)}catch(r){return SM(t,r),Bs(e,t,r)}}o(Yw,"callbackHandler");async function Qw(e,t){try{return Rp(await zw(e))}catch(r){return Mt(t,"oauth_dev_login_failed",r),ro(r)}}o(Qw,"devLoginHandler");async function Xw(e,t){let r=(()=>{try{return new URL(e.url).host}catch{return""}})();try{if(e.method==="GET"){let n=typeof e.query.state=="string"?e.query.state:void 0;return n?W_(r,n):ip(r,400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):Rp(await Mw({request:e,body:await Ls(e)}))}catch(n){return Mt(t,"oauth_api_key_login_failed",n),ip(r)}}o(Xw,"apiKeyLoginHandler");async function ev(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await qw({request:e,body:e.method==="POST"?await Ls(e):void 0,context:t});return Gs(r)}catch(r){return Mt(t,"oauth_setup_failed",r),Bs(e,t,r)}}o(ev,"setupHandler");async function tv(e,t){try{return Response.json(await Bw({body:await Ls(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Mt(t,"oauth_token_failed",r),ro(r)}}o(tv,"tokenHandler");async function rv(e,t){try{return await Gw({body:await Ls(e),authorizationHeader:e.headers.get("authorization"),context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Mt(t,"oauth_revoke_failed",r),ro(r)}}o(rv,"revokeHandler");var _M={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},nv=new Dt("upstream-request");function wM(e){let t=nv.get(e);if(!t)throw g("internal_server_error","Upstream request context has not been set");return t}o(wM,"readUpstreamRequestContext");function vM(e,t){return t.some(r=>r===e)}o(vM,"requestContextMatchesKind");function bM(e){return typeof e=="string"?[e]:e}o(bM,"toExpectedKinds");function cn(e,t){nv.set(e,t)}o(cn,"setUpstreamRequestContext");function un(e,t){let r=wM(e),n=bM(t);if(!vM(r.kind,n)){let a=_M[n[0]];throw g("internal_server_error",`${a} request context has not been set`)}return r}o(un,"requireUpstreamRequestContext");function ov(e){return T`<form class="form" method="post" action="${e.action}" autocomplete="off"><input type="hidden" name="browserTicket" value="${e.browserTicket}" />${e.fields}<p class="form__note">The gateway stores this encrypted and keeps it out of MCP client
54
- configuration.</p><button class="button button--primary button--block form__submit" type="submit" >Connect</button></form>`}o(ov,"renderAppPassword");function av(e){return T`<p data-gateway-error-code="${e.code}">${e.body}</p>`}o(av,"renderBrowserResult");var RM="text/html; charset=utf-8",CM="none";function iv(e){return nr({title:e.title,host:e.host,styles:rr,heading:e.title,subhead:"",body:av({body:e.body,code:e.code??CM}),footer:""})}o(iv,"browserResultHtml");function sv(e,t=200){return new Response(tr(e),{status:t,headers:{"content-type":RM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(sv,"browserResultResponse");function Vs(e){return sv(iv(e))}o(Vs,"browserConnectionSuccessResponse");function no(e,t){let r=sg(t);return sv(iv({host:e,title:r.title,body:r.body,code:t}),400)}o(no,"browserConnectionFailureResponse");function Cp(e){try{return new URL(e).host}catch{return""}}o(Cp,"safeHostFromUrl");var IM="text/html; charset=utf-8",PM=16*1024;function xM(e,t=200){return new Response(tr(e),{status:t,headers:{"content-type":IM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(xM,"htmlResponse");function AM(e,t){return Response.redirect(new URL(t,e).toString(),302)}o(AM,"safeRedirect");function kM(e){if(!e)throw g("oauth_state_invalid","App password capture requires a signed browser ticket.");return e}o(kM,"requireBrowserTicket");function TM(e,t){return[e.ownerMode!=="user"||e.upstreamServerId!==t.upstreamServerId||t.virtualServerId!==void 0&&e.virtualServerId!==t.virtualServerId].every(n=>!n)}o(TM,"appPasswordTicketMatchesTarget");async function cv(e){let t=kM(e.browserTicket),r=await ys(t);if(!TM(r,e))throw g("oauth_callback_mismatch","App password capture ticket did not match the requested upstream flow.");return{upstreamServerId:e.upstreamServerId,authProfileId:r.authProfileId,virtualServerId:r.virtualServerId,browserTicket:t,ticket:r}}o(cv,"readAppPasswordTarget");function EM(e,t){let r=El(e.upstreamServerId,e.authProfileId),n=`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`,a=r.kind==="basic_auth_app_password"?T`<label class="form__label" for="username">${r.usernameLabel}</label><input class="form__input" id="username" name="username" required autocomplete="username"><label class="form__label" for="appPassword">${r.passwordLabel}</label><input class="form__input" id="appPassword" name="appPassword" type="password" required autocomplete="current-password">`:T`<label class="form__label" for="token">${r.label}</label><input class="form__input" id="token" name="token" type="password" required autocomplete="off">`;return xM(nr({title:"Connect upstream",host:t,styles:rr,heading:"Connect upstream",subhead:T`<p class="card__subtitle">Enter the per-user credential for this approved upstream.</p>`,body:ov({action:n,browserTicket:e.browserTicket,fields:a}),footer:""}))}o(EM,"renderCaptureForm");function Fs(e,t){let r=e.get(t);if(typeof r!="string"||r.length===0)throw g("invalid_request",`Missing form field: ${t}`);return r}o(Fs,"readRequiredFormValue");function UM(e){return{upstreamServerId:e.upstreamServerId,...e.virtualServerId===void 0?{}:{virtualServerId:e.virtualServerId},...e.browserTicket===void 0?{}:{browserTicket:e.browserTicket}}}o(UM,"readCaptureFormTargetInput");async function OM(e,t){return EM(await cv(UM(e)),t)}o(OM,"handleCaptureFormRequest");async function $M(e){let t=await Os(e.request,{maxBytes:PM,label:"App password request body"});return{form:t,target:await cv({upstreamServerId:e.upstreamServerId,browserTicket:Fs(t,"browserTicket")})}}o($M,"readSubmittedAppPasswordTarget");async function zM(e){let t=Bn(e.target.ticket);if(await Ss(e.target.ticket),El(e.target.upstreamServerId,e.target.authProfileId).kind==="bearer_token"){await _s({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,token:Fs(e.form,"token")});return}await PS({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,username:Fs(e.form,"username"),appPassword:Fs(e.form,"appPassword")})}o(zM,"saveSubmittedAppPasswordCredential");function MM(e,t){return t.ticket.returnTo?AM(e,t.ticket.returnTo):Vs({host:Cp(e),title:"Connection complete",body:"The upstream credential was saved. Return to your MCP client and retry the request."})}o(MM,"appPasswordSuccessResponse");async function qM(e){let t=await $M({request:e.request,upstreamServerId:e.appPasswordRequest.upstreamServerId});return await zM(t),MM(e.request.url,t.target)}o(qM,"handleAppPasswordSubmission");function NM(){return new Response(null,{status:405,headers:{Allow:"GET, POST"}})}o(NM,"methodNotAllowedResponse");function DM(e,t){let r=he(t);return no(e,Hi(r)?r:"oauth_state_invalid")}o(DM,"appPasswordFailureResponse");async function jM(e){let t=Cp(e.request.url);switch(e.request.method){case"GET":return OM(e.appPasswordRequest,t);case"POST":return qM(e);default:return NM()}}o(jM,"handleAppPasswordMethod");async function Ip(e,t){let r=un(t,"app_password");try{return await jM({request:e,appPasswordRequest:r})}catch(n){return DM(Cp(e.url),n)}}o(Ip,"appPasswordHandler");var HM=["callback_authorization_code","callback_provider_error","callback_invalid"];function LM(e){return"cause"in e?e.cause:void 0}o(LM,"readErrorCause");function BM(e){return e.stack?.split(`
55
- `).slice(1,4).map(t=>t.trim()).join(" | ")}o(BM,"readFirstStackFrame");function uv(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=BM(r))}o(uv,"addErrorAttributes");function dv(e){try{return new URL(e).host}catch{return""}}o(dv,"safeHostFromUrl");function GM(e,t,r){switch(t.kind){case"callback_provider_error":return e.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:t.upstreamServerId,providerError:t.error,...t.errorDescription===void 0?{}:{providerErrorDescription:t.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),tt(e,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),no(r,"provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),no(r,"oauth_state_invalid");case"callback_authorization_code":return t}}o(GM,"requireAuthorizationCallbackRequest");function VM(e,t){tt(e,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(VM,"emitCallbackReceivedAnalyticsEvent");function FM(e,t){tt(e,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(FM,"emitTokenExchangeSucceededAnalyticsEvent");function ZM(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Vs({host:dv(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(ZM,"buildSuccessfulCallbackResponse");function KM(e){let t={detail:e instanceof Error?e.message:void 0};return uv(t,"error",e),e instanceof Error&&uv(t,"cause",LM(e)),t}o(KM,"buildTokenExchangeFailureAttributes");function WM(e){tt(e.context,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:he(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:KM(e.error)})}o(WM,"emitTokenExchangeFailedAnalyticsEvent");function JM(e,t){let r=he(t);return no(e,Hi(r)?r:"upstream_token_exchange_failed")}o(JM,"tokenExchangeFailureResponse");async function Pp(e,t){let r=un(t,HM),n=dv(e.url),a=GM(t,r,n);if(a instanceof Response)return a;VM(t,a);try{let i=await d_({request:e,callbackRequest:a});return FM(t,i),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:i.upstreamServerId,virtualServerId:i.virtualServerId,authProfileId:i.authProfileId,ownerMode:i.ownerMode},"Upstream OAuth token exchange completed; user connection established"),ZM(e,i)}catch(i){let s={event:"upstream_oauth_token_exchange_failed",code:he(i)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return Oe(s,"error",i),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),WM({context:t,callbackRequest:a,error:i}),JM(n,i)}}o(Pp,"callbackHandler");function YM(e){let t=he(e);return t==="unknown_upstream_server"?t:"not_found"}o(YM,"clientMetadataProblemCode");function QM(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(QM,"clientMetadataProblemDetail");async function lv(e,t){let r=un(t,"connect"),n=await u_({request:e,connectRequest:r});if(tt(t,{eventType:K.MCP_GATEWAY_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:n.virtualServerId,upstreamServerTitle:n.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:n.authProfileId,virtualServerId:n.virtualServerId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(n.authUrl,302);let a=await Fn({requestUrl:e.url,owner:n.owner,initiatedBySubjectId:n.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:n.authProfileId,upstreamDisplayName:n.upstreamDisplayName,virtualServerId:n.virtualServerId,subject:"virtual server",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(a,{status:428})}o(lv,"connectHandler");async function pv(e,t){let r=un(t,"client_metadata");try{let n=KS(e.url),a=WS(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){let a=YM(n),i=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",code:a,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),ft(e,t,{code:a,detail:QM(n)})}}o(pv,"oauthClientMetadataHandler");function or(e){if(typeof e=="string"&&e.length!==0)return e}o(or,"readOptionalQueryString");function XM(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw g("internal_server_error",`Validated path parameter ${t} is missing`);return r}o(XM,"requirePathString");function mv(e){let t=or(e);return t?Pe.parse(t):void 0}o(mv,"readOptionalVirtualServerId");function eq(e,t){let r=or(e);return r?et.parse(r):Nn(t,"user_oauth")}o(eq,"readOptionalAuthProfileId");function tq(e){let t=mv(e);if(!t)throw g("invalid_request","virtualServerId query parameter is required.");return t}o(tq,"readRequiredVirtualServerId");function rq(e){let t=or(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(rq,"readOptionalBrowserTicket");function nq(e){let t=cs(or(e));return t===void 0?{}:{returnTo:t}}o(nq,"readOptionalReturnTo");function oq(e){let t=mv(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(oq,"readOptionalVirtualServerIdContext");function aq(e){let t=or(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o(aq,"readOptionalProviderErrorDescription");function iq(e){let t=$t(e.authMode);if(t.connectSupport!=="none")return e;throw g("invalid_request",t.connectUnsupportedDetail??"This upstream does not support browser connection flows.")}o(iq,"requireConnectableRouteAuth");function sq(e,t,r,n){let a=Us(e,t);if(a.ownerMode==="none"||a.authMode==="shared-secret")throw g("invalid_request","Static-secret upstreams do not support browser connection flows.");return{kind:"connect",...a,...n===void 0?{}:{returnTo:n},redirect:r}}o(sq,"buildConnectContextForPrincipal");function cq(e,t,r){let n=Bn(t),a=$t(e.authMode);if(n.mode!==a.ownerMode)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:n,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}o(cq,"buildConnectContextForTicket");async function uq(e,t){let r=iq(E_(t,tq(e.query.virtualServerId))),n=e.query.redirect==="true",a=or(e.query.browserTicket);if(e.user){if(a)throw g("invalid_request","Use either an authenticated gateway request or a browser connect ticket, not both.");let s=jn(e.user,e.url);return sq(r,s,n,nq(e.query.returnTo).returnTo)}if(!a)throw g("authentication_required","Authentication is required to start the upstream connection flow.");let i=await ys(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.virtualServerId!==r.virtualServerId)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return await Ss(i),cq(r,i,n)}o(uq,"resolveConnectContext");async function dq(e,t,r){let n=Xe.parse(XM(e,"connection"));switch(r){case"connect":cn(t,await uq(e,n));return;case"app_password":cn(t,{kind:"app_password",upstreamServerId:n,...oq(e),...rq(e)});return;case"callback":{let a=or(e.query.error);if(a){cn(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...aq(e)});return}let i=or(e.query.code),s=or(e.query.state);if(i&&s){cn(t,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:s});return}cn(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":cn(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:eq(e.query.authProfileId,n)});return}}o(dq,"resolveUpstreamRequestInbound");async function lq(e,t,r){try{await dq(e,t,r);return}catch(n){let a=he(n);if(!a)throw n;let i=n instanceof Error?n.message:void 0;return ft(e,t,{code:a,...i===void 0?{}:{detail:i}})}}o(lq,"applyUpstreamRequestContext");function Ea(e,t){return o(async(n,a)=>{let i=await lq(n,a,e);return i||t(n,a)},"wrapped")}o(Ea,"withUpstreamRequestContext");var pq={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function mq(){return new Response(null,{status:204,headers:pq})}o(mq,"buildWellKnownPreflightResponse");function fq(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(fq,"withWellKnownCorsHeaders");function xp(e){return async(t,r)=>t.method==="OPTIONS"?mq():fq(await e(t,r))}o(xp,"wrapWellKnownHandler");var hq=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:xp(Fw)},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:xp(Zw)},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:xp(Vg)},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:Kw},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:Ww},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:Jw},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:Yw},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:Qw},{routeName:"oauth_api_key_login",path:"/oauth/api-key-login",methods:["GET","POST"],handler:Xw},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:ev},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:tv},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:rv},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Ea("client_metadata",pv)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Ea("connect",lv)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Ea("callback",Pp)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:Ea("app_password",Ip)}];function fv(e){if(e)return e.find(t=>Fi(t.policyType))}o(fv,"findMcpOAuthPolicy");function hv(e){return fv(e)!==void 0}o(hv,"shouldRegisterMcpGatewayInternalRoutes");function gq(e){let t=qd(e.policyType);if(!t){let r=Nd();throw new Or(`MCP gateway: unknown MCP authorization policy type '${String(e.policyType)}'. Registered policy types: ${r.length>0?r.join(", "):"<none>"}.`)}try{return t.getConfig(e.handler.options)}catch(r){throw r instanceof u.ZodError?new Or(yq(e.name??e.policyType,r),{cause:r}):r}}o(gq,"resolveOAuthConfigFromPolicy");function yq(e,t){let r=t.issues.map(n=>` - ${n.path.length>0?n.path.join("."):"<root>"}: ${n.message}`).join(`
56
- `);return`MCP OAuth policy "${e}" is misconfigured. Missing/invalid options:
57
- ${r}`}o(yq,"formatPolicyConfigError");function gv(e){let t=fv(e.policies);if(!t){let r=Nd(),n=r.length>0?`Add one of [${r.map(a=>`\`${a}\``).join(", ")}] and reference it on your MCP routes.`:"Register an MCP authorization policy descriptor and reference it on your MCP routes.";throw new Or(`MCP gateway: could not find an MCP authorization policy in policies.json. ${n}`)}Dg(gq(t)),wg(_g({routes:e.routes,policies:e.policies}))}o(gv,"initializeMcpGatewayState");function Sq(e,t){return async(r,n)=>{let a=n,i=r.method==="OPTIONS",s=Date.now();i||a.log.info({event:`${e}_received`,method:r.method},`MCP gateway: ${e} received`);try{let c=await t(r,n);return i||a.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-s},`MCP gateway: ${e} responded`),c}catch(c){let d={event:`${e}_threw`,durationMs:Date.now()-s};throw Oe(d,"err",c),a.log.error(d,`MCP gateway: ${e} threw`),c}}}o(Sq,"wrapInternalHandler");function yv(e){for(let t of hq){let r=Sq(t.routeName,t.handler),n=o((a,i)=>r(a,i),"handler");e.addPluginRoute({path:t.path,methods:t.methods,handler:n,processors:[ec],corsPolicy:"none"})}}o(yv,"registerMcpGatewayInternalRoutes");var Ap=class extends Np{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;r&&hv(r.policies)&&(gv({routes:r.routes,policies:r.policies}),yv(t.router))}};export{e$ as McpAuth0OAuthInboundPolicy,Ap as McpGatewayPlugin,n$ as McpOAuthInboundPolicy,s$ as McpUpstreamConnectionInboundPolicy,GO as McpVirtualServerHandler};
60
+ </style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}o(rr,"renderShell");var fp="zuplo.com";function J_(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(J_,"s2FaviconHref");function P$(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}o(P$,"strictFaviconHref");var ln=J_(fp);function pn(e){let t=e.toLowerCase();return t===fp||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?J_(fp):P$(e)}o(pn,"resolveIconHref");function mn(e){return ce`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}o(mn,"renderShellIcon");function W_(e){return ce`<form class="actions" method="post" action="/oauth/setup" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}o(W_,"renderActions");var B5=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function Y_(){return ce`<p>The API key could not be verified. Start the authorization flow again to try
61
+ once more.</p>`}o(Y_,"renderApiKeyLoginFailure");function Q_(e){return ce`<form class="form" method="post" action="/oauth/api-key-login" autocomplete="off" ><input type="hidden" name="state" value="${e.state}" /><label class="form__label" for="apiKey">API key</label><input class="form__input" id="apiKey" name="apiKey" type="password" required autocomplete="off" /><button class="button button--primary button--block form__submit" type="submit" >Continue</button></form>`}o(Q_,"renderApiKeyLoginForm");var G5=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),V5=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var F5=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var x$="text/html; charset=utf-8";function X_(e,t=200){return new Response(Tr(e),{status:t,headers:{"content-type":x$,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(X_,"apiKeyLoginHtmlResponse");function hp(e,t=401){let r=pn(e);return X_(rr({title:"Sign-in failed",iconHref:r,styles:tr,headerIcon:mn({iconHref:r,fallbackIconHref:ln}),heading:"Sign-in failed",subhead:"",body:Y_(),footer:""}),t)}o(hp,"apiKeyLoginFailureResponse");function ew(e,t){let r=pn(e);return X_(rr({title:"Sign in",iconHref:r,styles:tr,headerIcon:mn({iconHref:r,fallbackIconHref:ln}),heading:"Sign in",subhead:ce`<p class="card__subtitle">Enter your API key to continue.</p>`,body:Q_({state:t}),footer:""}))}o(ew,"renderApiKeyLoginForm");ae();ae();import{errors as lw,jwtVerify as pw,SignJWT as mw}from"jose";ae();import{errors as j$,jwtVerify as D$,SignJWT as H$}from"jose";function Er(e){let t=Pe().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw g("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}o(Er,"requireBrowserLoginField");ae();import{createRemoteJWKSet as k$,errors as $a,jwtVerify as T$}from"jose";var E$=u.object({id_token:u.string().min(1),token_type:u.string().min(1).optional(),expires_in:u.number().optional(),access_token:u.string().min(1).optional(),refresh_token:u.string().min(1).optional(),scope:u.string().min(1).optional()}),U$=u.object({error:u.string().min(1).optional(),error_description:u.string().min(1).optional(),error_uri:u.string().min(1).optional()});function O$(e){let t=U$.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}o(O$,"readIdpErrorFields");function $$(e){return e instanceof $a.JWTExpired?"expired":e instanceof $a.JWTClaimValidationFailed?"claim":e instanceof $a.JWSSignatureVerificationFailed?"signature":e instanceof $a.JWKSNoMatchingKey?"jwks_no_match":e instanceof $a.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o($$,"readJwtFailureKind");var z$=u.object({sub:_e,nonce:u.string().min(1)}).catchall(u.unknown()),gp;function M$(e){return e instanceof Error&&"cause"in e?e.cause:e}o(M$,"readErrorCause");function q$(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(q$,"readRuntimeGatewayCode");function N$(){if(!gp){let e=Pe();gp=k$(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return gp}o(N$,"readFederatedJwks");async function tw(e){let t=Pe(),r=Er("tokenUrl"),n=Er("clientId"),a=Er("clientSecret"),i=new URL("/oauth/callback",gt(e.requestUrl)).toString(),s=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:n,client_secret:a});try{let{response:c,json:d}=await mh(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:s},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,...e.context===void 0?{}:{context:e.context}});if(!c.ok){let h=O$(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:ct(r),idpStatus:c.status,...h},"Federated browser login token exchange returned non-2xx from the identity provider"),g({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${h.idpError?` idp_error=${h.idpError}`:""}${h.idpErrorDescription?` idp_error_description=${h.idpErrorDescription}`:""})`)})}let p=E$.parse(d),l;try{({payload:l}=await T$(p.id_token,N$(),{issuer:t.oidc.issuer,audience:n}))}catch(h){let y={};throw Ye(y,"error",h),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:$$(h),idpHost:ct(r),expectedIssuer:t.oidc.issuer,...y},"Federated id_token failed jose verification"),h}if(l.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:ct(r),nonceMissingFromIdToken:l.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),g("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let m=z$.parse(l);return Cn({sub:m.sub,data:m},e.requestUrl)}catch(c){let d=ge(c)??q$(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:g("browser_login_verification_failed","Federated browser login callback could not be verified.",M$(c))}}o(tw,"exchangeFederatedAuthorizationCode");var Sp="zuplo_mcp_session",rw="HS256",nw="zuplo-mcp-gateway",ow="zuplo-mcp-gateway",L$=u.object({purpose:u.literal("gateway_browser_session"),sub:_e,browserLoginOrigin:u.string().min(1),roles:u.array(u.string().min(1)).optional(),exp:u.number().int().positive(),iat:u.number().int().positive().optional()});function B$(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;let a=r.slice(0,n).trim(),i=r.slice(n+1).trim();if(a)try{t.set(a,decodeURIComponent(i))}catch{t.set(a,i)}}return t}o(B$,"parseCookieHeader");async function aw(){return At({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>fr(e,"browser-session"),"derive")})}o(aw,"getBrowserSessionKey");function yp(e){let t=new URL(ie(e)),r=[`${Sp}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(yp,"buildBrowserSessionEvictionCookie");function G$(e){let t=new URL(ie(e.requestUrl)),r=[`${Sp}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(G$,"serializeSessionCookie");function iw(e={}){return new URL(Er("url")).origin}o(iw,"readBrowserLoginOrigin");function _p(){return Pe().browserLogin.stateTtlSeconds}o(_p,"readBrowserLoginStateTtlSeconds");function sw(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return Cn(e.user,e.url)}o(sw,"resolveCurrentRequestPrincipal");async function Bs(e,t={}){let r=B$(e.headers.get("cookie")).get(Sp);if(!r)return{};try{let{payload:n}=await D$(r,await aw(),{algorithms:[rw],issuer:nw,audience:ow}),a=L$.parse(n);if(a.browserLoginOrigin!==iw(t))return{evictCookie:yp(e.url)};let i={subjectId:a.sub};return a.roles&&a.roles.length>0&&(i.roles=a.roles),{principal:i}}catch(n){return n instanceof j$.JWTExpired?{evictCookie:yp(e.url)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:n instanceof Error?n.name:"unknown",errorMessage:n instanceof Error?n.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:yp(e.url)})}}o(Bs,"readBrowserSession");async function za(e){let t=Pe().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:iw({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new H$(r).setProtectedHeader({alg:rw,typ:"JWT"}).setIssuer(nw).setAudience(ow).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await aw());return G$({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o(za,"createBrowserSessionCookie");async function cw(e){throw g("forbidden","API-key browser login is not supported in this gateway.")}o(cw,"resolveApiKeyBrowserLoginPrincipal");async function uw(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await Bs(e.request,t);if(r.principal)return r.principal;let n=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!n)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");return tw({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(uw,"resolveBrowserLoginCallbackPrincipal");function dw(e){let t=Pe().browserLogin,r=new URL(Er("url")),n=new URL("/oauth/callback",gt(e.requestUrl));return ym(r)?(r.searchParams.set("redirect_uri",n.toString()),r.searchParams.set("state",e.state),r):(r.searchParams.set("response_type","code"),r.searchParams.set("client_id",Er("clientId")),r.searchParams.set("redirect_uri",n.toString()),r.searchParams.set("scope",t.scope),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),t.audience&&r.searchParams.set("audience",t.audience),r)}o(dw,"buildBrowserLoginUrl");var V$={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},B=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=V$[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var F$=5*60,Gs="HS256",Vs="zuplo-mcp-gateway",Fs="zuplo-mcp-gateway",Z$=u.object({purpose:u.literal("gateway_browser_login"),transactionId:ut,stateId:Xa,exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),K$=u.object({purpose:u.literal("gateway_authorization_setup"),transactionId:ut,stateId:Xa,exp:u.number().int().positive(),iat:u.number().int().positive().optional()});async function fw(){return At({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>fr(e,"browser-login"),"derive")})}o(fw,"getBrowserLoginKey");async function hw(){return At({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>fr(e,"authorization-csrf"),"derive")})}o(hw,"getCsrfKey");function gw(e){return{now:e.now??new Date,ttlSeconds:_p()}}o(gw,"readPendingTransactionDependencies");function J$(e,t){return e.subjectId===t.subjectId}o(J$,"principalsMatch");function yw(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(yw,"toPendingPrincipal");function Sw(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,virtualServerId:e.transaction.virtualServerId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:re(e.now),expiresAt:re(Dt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:yw(e.principal)}}o(Sw,"createTransactionRecord");async function _w(e){let{id:t,...r}=e.record,n=await K().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw g("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new B("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new B("invalid_request","redirect_uri is not registered for the client.")}}o(_w,"startPendingTransaction");async function W$(e){return new mw({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:Gs,typ:"JWT"}).setIssuer(Vs).setAudience(Fs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await fw())}o(W$,"signBrowserLoginState");async function ww(e){return new mw({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Ic()}).setProtectedHeader({alg:Gs,typ:"JWT"}).setIssuer(Vs).setAudience(Fs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await hw())}o(ww,"signCsrfToken");async function Zs(e){try{let{payload:t}=await pw(e,await fw(),{algorithms:[Gs],issuer:Vs,audience:Fs}),r=Z$.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof lw.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}o(Zs,"verifyBrowserLoginStateToken");async function wp(e){try{let{payload:t}=await pw(e,await hw(),{algorithms:[Gs],issuer:Vs,audience:Fs});return{transactionId:K$.parse(t).transactionId}}catch(t){throw t instanceof lw.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(wp,"verifyCsrfToken");function Ks(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(Ks,"pendingStateErrorCode");function vw(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(vw,"toPendingAuthorizationGetResult");function Y$(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(Y$,"toPendingAuthorizationAdvanceResult");function bw(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Ks(e==="consumed_already"?"consumed_already":e)}o(bw,"setupDecisionErrorCode");function Q$(e){if(e.kind!=="available")throw g(Ks(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(Q$,"requireAwaitingSetup");function X$(e){if(e.kind!=="available")throw g(Ks(e.kind),"Browser login state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_login")throw g("oauth_state_invalid","Browser login state is not in the login phase.");return e.record}o(X$,"requireAwaitingLogin");function ez(e){if(!J$(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(ez,"requireCurrentPrincipalMatches");async function Rw(e){let t=e.now??new Date,r=_p(),n=Cc(),a=Ic(),i=await W$({transactionId:n,stateId:a,ttlSeconds:r}),s=Sw({id:n,transaction:e.transaction,currentStateHash:await le(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await _w({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:i,browserLoginUrl:dw({state:i,nonce:a,virtualServerId:s.virtualServerId,requestUrl:e.requestUrl})}}o(Rw,"startAwaitingLogin");async function Cw(e){let{now:t,ttlSeconds:r}=gw(e),n=Cc(),a=await ww({transactionId:n,ttlSeconds:r}),i=Sw({id:n,transaction:e.transaction,currentStateHash:await le(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await _w({record:i,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:a}}o(Cw,"startAwaitingSetup");async function vp(e){let{now:t,ttlSeconds:r}=gw(e),n=await Zs(e.browserLoginStateToken),a=await ww({transactionId:n.transactionId,ttlSeconds:r}),i=Y$(await K().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await le(e.browserLoginStateToken),nextStateHash:await le(a),nextPhase:"awaiting_setup",principal:yw(e.principal),now:re(t)}));if(i.kind!=="advanced")throw g(Ks(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:a}}o(vp,"completeLogin");async function Iw(e){let t=e.now??new Date,r=await Zs(e.browserLoginStateToken);return X$(vw(await K().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await le(e.browserLoginStateToken),now:re(t)})))}o(Iw,"getAwaitingLogin");async function Pw(e){let t=await bp(e);return ez({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(Pw,"getSetup");async function bp(e){let t=e.now??new Date,r=await wp(e.csrfToken);return Q$(vw(await K().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await le(e.csrfToken),now:re(t)})))}o(bp,"getSetupTransaction");async function tz(e){let t=await wp(e.csrfToken),r=Ht(),n=re(Dt(e.now,F$)),a=await K().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await le(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await le(r),authorizationCodeExpiresAt:n,grantId:hm(),now:re(e.now)});if(a.kind!=="approved")throw g(a.kind==="cancelled"?"oauth_state_invalid":bw(a.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(a.transaction.redirectUri);return i.searchParams.set("code",r),a.transaction.clientState&&i.searchParams.set("state",a.transaction.clientState),i}o(tz,"createAuthorizationCodeRedirectWithDecision");async function rz(e){let t=await wp(e.csrfToken),r=await K().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await le(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:re(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":bw(r.kind),"Authorization setup state is invalid, expired, or already used.");return nz({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}o(rz,"createCancelRedirectWithDecision");function nz(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}o(nz,"buildClientCancelRedirect");async function xw(e){let t=e.now??new Date;return tz({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(xw,"approve");async function Aw(e){let t=e.now??new Date;return rz({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(Aw,"cancel");ae();var oz=1e4,az=5*1024,iz=2,sz=90*24*60*60,Rp=["authorization_code","refresh_token"],Cp=["code"],cz=u.object({client_name:u.string().min(1).optional(),redirect_uris:u.array(u.string().min(1)).min(1),grant_types:u.array(u.enum(Rp)).min(1).max(2).optional(),response_types:u.array(u.enum(Cp)).min(1).max(1).optional(),scope:u.literal(Se).optional(),token_endpoint_auth_method:wc.default("none")});function uz(e){try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(uz,"isCimdClientIdCandidate");function Ma(e,t="invalid_request"){if(dz(e))throw new B(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new B(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new B(t,"redirect_uris must not include credentials or fragments.");if(!(r.protocol==="https:"||qe(r)))throw new B(t,"redirect_uris must use HTTPS except loopback HTTP redirects for local clients.")}o(Ma,"assertValidRedirectUri");function dz(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}o(dz,"hasForbiddenRawRedirectUriCharacter");async function lz(e){let{response:t,json:r}=await fh(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:iz,maxResponseBytes:az,timeoutMs:oz});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let n=fm.parse(r);if(n.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");if(n.token_endpoint_auth_method!=="none")throw g("invalid_request","CIMD clients must use token_endpoint_auth_method none until private_key_jwt is implemented.");return n}o(lz,"fetchCimdMetadata");async function pz(e){let t=xi(e),r=await lz({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(pz,"resolveCimdClient");async function kw(e,t){let r=Ne.parse(e);if(uz(r)){if(!Pe().gateway.cimdEnabled)throw new B("invalid_client","OAuth client is not registered.");try{return await pz(r)}catch{throw new B("invalid_client","OAuth client is not registered.")}}let n=await K().readClient({clientId:r});if(n.kind==="found"){let a=n.client,i={kind:"dcr",clientId:r,metadata:{client_id:a.clientId,client_name:a.clientName,redirect_uris:a.redirectUris,token_endpoint_auth_method:a.tokenEndpointAuthMethod}};return a.hashedClientSecret&&(i.hashedClientSecret=a.hashedClientSecret),i}throw new B("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(kw,"resolveClient");function Tw(e,t){if(!e.metadata.redirect_uris.some(r=>gm(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}o(Tw,"assertRedirectRegistered");function mz(e){let t=Ew(e.grant_types),r=e.response_types??[...Cp];if(!fz(t))throw new B("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!hz(r))throw new B("invalid_client_metadata","response_types must be code.");if(!gz(e.scope))throw new B("invalid_client_metadata",`Only the ${Se} scope is supported.`)}o(mz,"assertSupportedDcrRequest");function Ew(e){return e===void 0?[...Rp]:Array.from(new Set(e))}o(Ew,"normalizeGrantTypes");function fz(e){return e.length===0?!1:e.every(t=>Rp.includes(t))}o(fz,"isSupportedGrantTypes");function hz(e){return e.length===Cp.length&&e[0]==="code"}o(hz,"isSupportedResponseTypes");function gz(e){return e===void 0||e===Se}o(gz,"isSupportedDcrScope");function qa(e){if(e===void 0||e===Se)return Se;throw new B("invalid_request",`Only the ${Se} scope is supported.`)}o(qa,"assertSupportedOAuthScope");function co(e,t){let r;try{r=new URL(t)}catch{throw new B("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new B("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!qe(r))throw new B("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=ie(e),a=ih(),i=a?[...a.byVirtualServerId.values()].find(s=>new URL(s.routePath,n).toString()===t):void 0;if(!i)throw new B("invalid_target","resource must match a published virtual MCP server.");return i}o(co,"resolveResource");async function Uw(e){let t;try{t=cz.parse(e)}catch(l){if(l instanceof u.ZodError){let m=l.issues.some(h=>h.path[0]==="redirect_uris");throw new B(m?"invalid_redirect_uri":"invalid_client_metadata",l.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:l})}throw l}mz(t);for(let l of t.redirect_uris)Ma(l,"invalid_redirect_uri");let r=new Date,n=Ne.parse(`dcr:${crypto.randomUUID()}`),a=Dt(r,sz),i=Math.floor(r.getTime()/1e3),s=Math.floor(a.getTime()/1e3),c={client_id:n,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,grant_types:Ew(t.grant_types),response_types:["code"],scope:Se,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:i},d={clientId:n,clientName:String(c.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:re(r),clientExpiresAt:re(a)};if(t.token_endpoint_auth_method!=="none"){let l=Ht();d.hashedClientSecret=await le(l),d.clientSecretExpiresAt=re(a),c.client_secret=l,c.client_secret_expires_at=s,c.client_secret_issued_at=i}if((await K().registerClient(d)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");return c}o(Uw,"registerDownstreamClient");var yz="data:,",Ow=ce`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,$w=ce`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function Sz(e,t){if(e)try{let r=new URL(t).origin,n=new URL(e,r);return n.origin!==r||!n.pathname.startsWith("/auth/connections/")?void 0:n.toString()}catch{return}}o(Sz,"safeGatewayConnectHref");function _z(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(_z,"deriveMode");function wz(e){return W_({state:e.state,submitOnceAttrs:Ow,authorizeAttrs:Oa})}o(wz,"renderActions");function Ip(e,t,r){for(let n of e){if(n.ownerMode!=="user"||n.status!==r)continue;let a=Sz(n.connectUrl,t);if(a)return a}}o(Ip,"firstUserConnectHref");function vz(e){let t=e.connectHref?ce`<a class="button button--primary" href="${e.connectHref}" ${$w}>Connect</a>`:ce`<button class="button button--primary" type="button" disabled aria-disabled="true">Connect</button>`;return ce`<form class="actions" method="post" action="/oauth/setup" ${Ow}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}o(vz,"renderSetupActions");function bz(e){return e?ce`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${$w}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:Oa}o(bz,"renderReconnectAction");function Pp(e){let t=_z(e.upstreams),r=Ip(e.upstreams,e.gatewayOrigin,"not_connected"),n=Ip(e.upstreams,e.gatewayOrigin,"reconsent_required"),a=Ip(e.upstreams,e.gatewayOrigin,"active"),i=t==="setup"?r??n:void 0,s=ce`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.virtualServerDisplayName}</strong>' on your behalf?</p>`,c=t==="setup"?ce`<footer class="card__footer">${vz({state:e.state,connectHref:i})}</footer>`:ce`<footer class="card__footer">${bz(a)}${wz({state:e.state})}</footer>`;return Tr(rr({title:`Authorize access \xB7 ${e.virtualServerDisplayName}`,iconHref:yz,styles:tr,headerIcon:Oa,heading:"MCP Gateway",subhead:Oa,body:s,footer:c}))}o(Pp,"renderConsentPage");function Rz(e){try{return new URL(e).host}catch{return}}o(Rz,"safeUrlHost");function Cz(e){if(e.mode==="user_oauth"||e.mode==="shared-oauth")return e.oauth.scopes}o(Cz,"readOAuthScopes");function xp(e){return e!==void 0&&e.length>0}o(xp,"hasItems");function Iz(e){let t=e.registeredConnection.config.serverInfo?.icons;if(xp(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&xp(r)?r:void 0}o(Iz,"readServerIcons");async function Pz(e){if(!(e.returnTo===void 0||!e.isUserOwned))return Lu({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,virtualServerId:e.virtualServer.virtualServerId,returnTo:e.returnTo})}o(Pz,"readConnectUrl");function fn(e,t){return t===void 0?{}:{[e]:t}}o(fn,"optionalRequirementField");function xz(e){return e.isUserOwned?Tm(e.connection):{connected:!0,status:"active"}}o(xz,"readSetupConnectionStatus");function Az(e){let t=Cz(e);return xp(t)?t:void 0}o(Az,"readScopesRequested");function kz(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o(kz,"readUpdatedAt");function Tz(e){if(e.virtualServer.catalog.catalogSource!=="openapi")return{tools:[],prompts:[],resources:[]};let t=o(r=>r.upstreamPolicyName===e.registeredConnection.policyName,"ownsCapability");return{tools:e.virtualServer.catalog.tools.filter(r=>r.enabled!==!1&&t(r)).map(Ci),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(Ii),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map(Pi)}}o(Tz,"readVirtualServerCapabilities");async function Ez(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:i}=e.registeredConnection,s=ki(r),c=s==="user",d=xz({connection:e.connection,isUserOwned:c}),p=await Pz({...e,connected:d.connected,isUserOwned:c});return{upstreamServerId:a,authProfileId:i,authMode:r,ownerMode:s,upstreamDisplayName:n.displayName,status:d.status,connected:d.connected,capabilities:Tz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...fn("description",n.description),...fn("transportHost",Rz(n.transport.baseUrl)),...fn("scopesRequested",Az(t)),...fn("serverIcons",Iz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...fn("connectUrl",p),...fn("updatedAt",kz({connectionStatus:d,isUserOwned:c})),...fn("expiresAt",e.connection?.expiresAt)}}o(Ez,"buildSetupRequirement");function zw(e){let t=St().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(zw,"requireVirtualServer");async function Ap(e){let t=zw(e.transaction.virtualServerId),r=ir(e.transaction.principal.subjectId),n=[],a=new Map;for(let c of t.connections)ki(c.authMode)==="user"&&(a.set(c,n.length),n.push({owner:r,upstreamServerId:c.upstreamServerId,authProfileId:c.authProfileId}));let i=await K().batchGetUpstreamConnections(n),s=[];for(let c of t.connections){let d=ki(c.authMode)==="user",p=a.get(c);s.push(await Ez({connection:d&&p!==void 0?i[p]:void 0,registeredConnection:c,virtualServer:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r}))}return s}o(Ap,"requirementsForSetup");function Uz(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(Uz,"readVirtualServerDisplayName");async function kp(e){let t=zw(e.transaction.virtualServerId),r=Uz({virtualServer:t}),n=await K().readClient({clientId:e.transaction.clientId}),a=n.kind==="found"?n.client:void 0,i={gatewayOrigin:ie(e.requestUrl),virtualServerDisplayName:r,clientDisplayName:a?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},s=t.serverInfo?.title;return s!==void 0&&s!==r&&(i.virtualServerDescription=s),i}o(kp,"consentContext");function Mw(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(Mw,"hasUnresolvedUserUpstream");var Oz=["mcp_user"],$z="dev-browser-user",zz=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/mcp/{virtualServerId} or add resource={protected resource URI from protected-resource metadata}."].join(" "),Mz=u.object({response_type:u.literal("code"),client_id:u.string().min(1),redirect_uri:u.string().min(1),resource:u.url(),code_challenge:u.string().min(43),code_challenge_method:Wa,state:u.string().min(1).optional(),scope:u.literal(Se).default(Se)}),qz=u.enum(["continue","approve","cancel"]).default("continue"),Nz=u.object({state:u.string().min(1),decision:qz}),jz=u.object({state:u.string().min(1),apiKey:u.string().min(1)}),hn=class extends Error{static{o(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function qw(e){return typeof e=="string"&&e.length>0?e:void 0}o(qw,"readQueryString");function Dz(e,t){let r=qw(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new B("invalid_target",zz)}let n=Mr(t,e.url);if(r===void 0||r===n)return n;throw new B("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(Dz,"requireAuthorizeResource");async function Hz(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Bs(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let i=sw(e);return{principal:i,setCookie:await za({principal:i,requestUrl:e.url,virtualServerId:t})}}o(Hz,"resolveBrowserPrincipal");async function Lz(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Bs(e,n);if(!a.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(Lz,"requireSetupPrincipal");async function Nw(e){let t=await Ap({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:`/oauth/setup?state=${encodeURIComponent(e.csrfToken)}`}),r=await kp({transaction:e.transaction,requestUrl:e.requestUrl}),n={kind:"setup_page",html:Pp({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(Nw,"renderSetup");function Bz(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;if(t==="private_key_jwt")throw new B("invalid_client","OAuth client authentication method is not supported.");return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(Bz,"toAuthorizationTransactionClient");async function Tp(e,t={}){let r=Mz.parse({...e.query,resource:Dz(e,t.virtualServerId),state:qw(e.query.state)}),n=qa(r.scope);Ma(r.redirect_uri);let a=new Date,i=Ne.parse(r.client_id),s=await kw(r.client_id,a);Tw(s,r.redirect_uri);try{let c=co(e.url,r.resource),d=Bz(s);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:i,virtualServerId:c.virtualServerId,scope:n,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved");let p={clientId:s?.clientId??i,...d===void 0?{}:{client:d},redirectUri:r.redirect_uri,resource:r.resource,virtualServerId:c.virtualServerId,scope:n,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:l,setCookie:m}=await Hz(e,c.virtualServerId,t.context);if(!l){let y=await Rw({transaction:p,requestUrl:e.url,now:a});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:i,virtualServerId:c.virtualServerId},"Downstream OAuth authorize: redirecting to browser login (no session)");let _={kind:"redirect",location:y.browserLoginUrl};return m!==void 0&&(_.setCookie=m),_}let h=await Cw({transaction:p,principal:l,now:a});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:i,virtualServerId:c.virtualServerId,subjectId:l.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),Nw({transaction:h.transaction,csrfToken:h.csrfToken,requestUrl:e.url,setCookie:m})}catch(c){throw Gz({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}o(Tp,"authorizeDownstreamClient");function Gz(e){if(e.cause instanceof hn)return e.cause;let t=Vz(e.cause);return t?new hn({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(Gz,"toDownstreamAuthorizeRedirectError");function Vz(e){if(e instanceof B)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof u.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}o(Vz,"mapToOAuthRedirectError");async function jw(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let p=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,l=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...p===void 0?{}:{idpErrorDescription:p},...l===void 0?{}:{idpErrorUri:l}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",p??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let a=await Zs(n),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let s=await uw(i),c=await vp({browserLoginStateToken:n,principal:s}),d=await Nw({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return d.setCookie=await za({principal:s,requestUrl:e.url,virtualServerId:c.transaction.virtualServerId}),d}o(jw,"completeBrowserLoginCallback");async function Dw(e){let t=Pe(),r=new URL(e.url);if(!qe(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw g("oauth_state_invalid","Local browser login is missing state.");let a=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",ie(e.url)),i=new URL(ie(e.url)).origin;if(a.origin!==i||a.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");a.searchParams.set("state",n);let s={subjectId:_e.parse($z),roles:Oz};return{kind:"redirect",location:a,setCookie:await za({principal:s,requestUrl:e.url})}}o(Dw,"completeLocalDevBrowserLogin");async function Hw(e){let t=jz.parse(e.body),r=await Iw({browserLoginStateToken:t.state}),n=await cw({apiKey:t.apiKey,virtualServerId:r.virtualServerId}),a=await vp({browserLoginStateToken:t.state,principal:n});await hg({apiKey:t.apiKey,principal:n,virtualServerId:a.transaction.virtualServerId});let i=new URL("/oauth/setup",gt(e.request.url));return i.searchParams.set("state",a.csrfToken),{kind:"redirect",location:i,setCookie:await za({principal:n,requestUrl:e.request.url,virtualServerId:a.transaction.virtualServerId})}}o(Hw,"completeApiKeyBrowserLogin");function Fz(e){let t=e.method==="POST"?e.body:e.query;return Nz.parse(t)}o(Fz,"readSetupContinueRequest");async function Lw(e){let{state:t,decision:r}=Fz({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,a=await bp({csrfToken:t,now:n}),i=await Lz(e.request,a.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await Aw({csrfToken:t,currentBrowserPrincipal:i,now:n})};let s=await Pw({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await Ap({transaction:s,requestUrl:e.request.url,returnTo:`/oauth/setup?state=${encodeURIComponent(t)}`});if(r==="continue"||Mw(c)){let d=await kp({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:Pp({state:t,virtualServerId:s.virtualServerId,upstreams:c,...d})}}return{kind:"redirect",location:await xw({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(Lw,"continueDownstreamAuthorizeSetup");ae();var Zz=new Set(["authorization_code","refresh_token"]),Kz=u.discriminatedUnion("grant_type",[u.object({grant_type:u.literal("authorization_code"),code:u.string().min(1),redirect_uri:u.string().min(1),client_id:u.string().min(1).optional(),code_verifier:Ya,resource:u.url().optional(),scope:u.literal(Se).optional(),client_secret:u.string().min(1).optional()}),u.object({grant_type:u.literal("refresh_token"),refresh_token:u.string().min(1),client_id:u.string().min(1).optional(),resource:u.url().optional(),scope:u.literal(Se).optional(),client_secret:u.string().min(1).optional()})]);function Jz(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!Zz.has(t)))throw new B("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(Jz,"assertSupportedGrantType");var Wz=u.object({token:u.string().min(1),client_id:u.string().min(1).optional(),token_type_hint:u.string().optional(),client_secret:u.string().min(1).optional()});function Bw(){return Pe().gateway.accessTokenTtlSeconds}o(Bw,"readAccessTokenTtlSeconds");function Yz(){return Pe().gateway.refreshTokenTtlSeconds}o(Yz,"readRefreshTokenTtlSeconds");function Qz(e,t){let r=Bw(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:re(Dt(e,a)),expiresIn:a}}o(Qz,"calculateAccessTokenExpiresAt");function Gw(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new B("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new B("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new B("invalid_client","Malformed HTTP Basic client authentication.")}}o(Gw,"readBasicClientSecret");function Vw(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new B("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t===void 0)throw new B("invalid_client","Client authentication or client_id is required.");return t}o(Vw,"resolveAuthenticatedClientId");function Fw(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new B("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}o(Fw,"resolveClientSecretInput");async function Zw(e){let t=Ne.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await le(e.clientSecret)}}o(Zw,"buildRuntimeHttpClientAuth");async function Kw(e){Jz(e.body);let t=Kz.parse(e.body),r=Gw(e.authorizationHeader),n=Vw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=new Date,i=Fw({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});return Xz({parsed:t,clientId:n,clientSecretInput:i,now:a,requestUrl:e.requestUrl})}o(Kw,"exchangeDownstreamToken");async function Xz(e){let t=await Zw({clientId:e.clientId,...e.clientSecretInput});if(e.parsed.grant_type==="authorization_code"){Ma(e.parsed.redirect_uri),qa(e.parsed.scope),e.parsed.resource!==void 0&&co(e.requestUrl??e.parsed.resource,e.parsed.resource);let c=Ht(),d=Ht(),p=re(Dt(e.now,Yz())),l=Qz(e.now,p),m=await K().exchangeAuthorizationCode({clientAuth:t,codeHash:await le(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await bf(e.parsed.code_verifier),currentRefreshTokenHash:await le(c),accessTokenHash:await le(d),grantExpiresAt:p,accessTokenExpiresAt:l.expiresAt,now:re(e.now)});if(m.kind==="invalid_client")throw new B("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new B("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new B("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return{access_token:d,token_type:"Bearer",expires_in:l.expiresIn,refresh_token:c,scope:m.grant.scope,resource:m.grant.resource}}qa(e.parsed.scope),e.parsed.resource!==void 0&&co(e.requestUrl??e.parsed.resource,e.parsed.resource);let r=Ht(),n=Ht(),a=re(Dt(e.now,Bw())),i=await K().refreshToken({clientAuth:t,currentRefreshTokenHash:await le(e.parsed.refresh_token),nextRefreshTokenHash:await le(r),accessTokenHash:await le(n),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:a,now:re(e.now)});if(i.kind==="invalid_client")throw new B("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new B("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new B("invalid_grant","Refresh token is invalid, expired, or revoked.");co(e.requestUrl??i.grant.resource,i.grant.resource);let s=i.accessToken.expiresAt;return{access_token:n,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(s).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}o(Xz,"exchangeDownstreamTokenWithRuntimeHttp");async function Jw(e){let t=Wz.parse(e.body),r=Gw(e.authorizationHeader),n=Vw({basicClientId:r.clientId,bodyClientId:t.client_id}),a=Fw({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret}),i=new Date;if((await K().revokeOAuthToken({clientAuth:await Zw({clientId:n,...a}),tokenHash:await le(t.token),now:re(i)})).kind==="invalid_client")throw new B("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed")}o(Jw,"revokeDownstreamToken");var eM=64*1024,tM=16*1024,rM="text/html; charset=utf-8";function nM(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(nM,"formDataToObject");async function oM(e){return F_(e,{maxBytes:eM,label:"Request body"})}o(oM,"readJsonBody");async function Js(e){return nM(await Ls(e,{maxBytes:tM,label:"Request body"}))}o(Js,"readFormBody");async function Ws(e,t,r){let n=ge(r),a=r instanceof u.ZodError?Ww(r):void 0,i={code:n??(r instanceof u.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(i.detail=a),st(e,t,i)}o(Ws,"handleProblem");function Na(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}o(Na,"oauthErrorResponse");function aM(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(aM,"readOAuthProtocolHeaders");function iM(e,t){let r=Ke("internal_server_error");return Na({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:aM(e,t)})}o(iM,"oauthProtocolErrorResponse");function sM(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(sM,"readZodOAuthErrorCode");function cM(e){let t={error:sM(e)},r=Ww(e);return r!==void 0&&(t.errorDescription=r),Na(t)}o(cM,"oauthZodErrorResponse");function uM(e){let t=ge(e);if(t===void 0)return;let r=Ke(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:lM(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,Na(n)}o(uM,"oauthGatewayProblemResponse");function dM(){let t={error:"server_error",status:500,errorDescription:Ke("internal_server_error").publicDetail};return Na(t)}o(dM,"oauthFallbackErrorResponse");function lM(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(lM,"readOAuthStatus");function uo(e,t={}){return e instanceof hn?pM(e):e instanceof B?iM(e,t):e instanceof u.ZodError?cM(e):uM(e)??dM()}o(uo,"oauthProblemResponse");function Mt(e,t,r){let n={event:t},a=!1;if(r instanceof B)n.oauthError=r.errorCode,n.status=r.status,Ye(n,"error",r);else if(r instanceof hn)n.oauthError=r.errorCode,Ye(n,"error",r);else if(r instanceof u.ZodError){n.code="invalid_request",Ye(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=ge(r);if(i!==void 0){let s=Ke(i);n.code=i,n.status=s.status,s.oauthError!==void 0&&(n.oauthError=s.oauthError),a=s.status>=500||s.oauthError==="server_error",Ye(n,"error",r)}else a=!0,Ye(n,"error",r)}if(a){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(Mt,"logUnexpectedOAuthHandlerError");function pM(e){let t;try{t=new URL(e.redirectUri)}catch{return Na({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}o(pM,"downstreamAuthorizeRedirectErrorResponse");function Ww(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Ww,"formatZodErrorDetail");function mM(e,t){let r={event:"browser_login_callback_failed",code:ge(t)??"invalid_request"};Ye(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(mM,"logBrowserLoginCallbackFailure");function Ep(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}o(Ep,"redirectResultResponse");function Ys(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":rM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return Ep(e)}o(Ys,"authorizeResultResponse");async function Yw(e,t){try{return Response.json(xc(e.url))}catch(r){return Mt(t,"oauth_authorization_server_metadata_failed",r),Ws(e,t,r)}}o(Yw,"authorizationServerMetadataHandler");async function Qw(e,t){try{let r=xe.parse(e.params.virtualServerId),n=qr(r);return Response.json(Sm({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return Mt(t,"oauth_authorization_server_metadata_failed",r),Ws(e,t,r)}}o(Qw,"scopedAuthorizationServerMetadataHandler");async function Xw(e,t){try{let r=await Uw(await oM(e)),n=r;return t.log.info({event:"oauth_dcr_client_registered",clientId:typeof n.client_id=="string"?n.client_id:void 0,clientName:typeof n.client_name=="string"?n.client_name:void 0,redirectUriCount:Array.isArray(n.redirect_uris)?n.redirect_uris.length:void 0,tokenEndpointAuthMethod:typeof n.token_endpoint_auth_method=="string"?n.token_endpoint_auth_method:void 0},"OAuth Dynamic Client Registration completed"),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Mt(t,"oauth_register_failed",r),uo(r)}}o(Xw,"registerHandler");async function ev(e,t){try{return Ys(await Tp(e,{context:t}))}catch(r){return Mt(t,"oauth_authorize_failed",r),uo(r,{includeInvalidClientChallenge:!1})}}o(ev,"authorizeHandler");async function tv(e,t){try{let r=xe.parse(e.params.virtualServerId),n=qr(r);return Ys(await Tp(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return Mt(t,"oauth_authorize_scoped_failed",r),uo(r,{includeInvalidClientChallenge:!1})}}o(tv,"scopedAuthorizeHandler");async function rv(e,t){try{let r=await jw(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Ys(r)}catch(r){return mM(t,r),Ws(e,t,r)}}o(rv,"callbackHandler");async function nv(e,t){try{return Ep(await Dw(e))}catch(r){return Mt(t,"oauth_dev_login_failed",r),uo(r)}}o(nv,"devLoginHandler");async function ov(e,t){let r=(()=>{try{return new URL(e.url).host}catch{return""}})();try{if(e.method==="GET"){let n=typeof e.query.state=="string"?e.query.state:void 0;return n?ew(r,n):hp(r,400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):Ep(await Hw({request:e,body:await Js(e)}))}catch(n){return Mt(t,"oauth_api_key_login_failed",n),hp(r)}}o(ov,"apiKeyLoginHandler");async function av(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await Lw({request:e,body:e.method==="POST"?await Js(e):void 0,context:t});return Ys(r)}catch(r){return Mt(t,"oauth_setup_failed",r),Ws(e,t,r)}}o(av,"setupHandler");async function iv(e,t){try{return Response.json(await Kw({body:await Js(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Mt(t,"oauth_token_failed",r),uo(r)}}o(iv,"tokenHandler");async function sv(e,t){try{return await Jw({body:await Js(e),authorizationHeader:e.headers.get("authorization"),context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Mt(t,"oauth_revoke_failed",r),uo(r)}}o(sv,"revokeHandler");var fM={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},cv=new It("upstream-request");function hM(e){let t=cv.get(e);if(!t)throw g("internal_server_error","Upstream request context has not been set");return t}o(hM,"readUpstreamRequestContext");function gM(e,t){return t.some(r=>r===e)}o(gM,"requestContextMatchesKind");function yM(e){return typeof e=="string"?[e]:e}o(yM,"toExpectedKinds");function gn(e,t){cv.set(e,t)}o(gn,"setUpstreamRequestContext");function yn(e,t){let r=hM(e),n=yM(t);if(!gM(r.kind,n)){let a=fM[n[0]];throw g("internal_server_error",`${a} request context has not been set`)}return r}o(yn,"requireUpstreamRequestContext");function uv(e){return ce`<form class="form" method="post" action="${e.action}" autocomplete="off"><input type="hidden" name="browserTicket" value="${e.browserTicket}" />${e.fields}<p class="form__note">The gateway stores this encrypted and keeps it out of MCP client
62
+ configuration.</p><button class="button button--primary button--block form__submit" type="submit" >Connect</button></form>`}o(uv,"renderAppPassword");function dv(e){return ce`<p data-gateway-error-code="${e.code}">${e.body}</p>`}o(dv,"renderBrowserResult");var SM="text/html; charset=utf-8",_M="none";function lv(e){let t=pn(e.host);return rr({title:e.title,iconHref:t,styles:tr,headerIcon:mn({iconHref:t,fallbackIconHref:ln}),heading:e.title,subhead:"",body:dv({body:e.body,code:e.code??_M}),footer:""})}o(lv,"browserResultHtml");function pv(e,t=200){return new Response(Tr(e),{status:t,headers:{"content-type":SM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(pv,"browserResultResponse");function Qs(e){return pv(lv(e))}o(Qs,"browserConnectionSuccessResponse");function lo(e,t){let r=om(t);return pv(lv({host:e,title:r.title,body:r.body,code:t}),400)}o(lo,"browserConnectionFailureResponse");function Up(e){try{return new URL(e).host}catch{return""}}o(Up,"safeHostFromUrl");var wM="text/html; charset=utf-8",vM=16*1024;function bM(e,t=200){return new Response(Tr(e),{status:t,headers:{"content-type":wM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(bM,"htmlResponse");function RM(e,t){return Response.redirect(new URL(t,e).toString(),302)}o(RM,"safeRedirect");function CM(e){if(!e)throw g("oauth_state_invalid","App password capture requires a signed browser ticket.");return e}o(CM,"requireBrowserTicket");function IM(e,t){return[e.ownerMode!=="user"||e.upstreamServerId!==t.upstreamServerId||t.virtualServerId!==void 0&&e.virtualServerId!==t.virtualServerId].every(n=>!n)}o(IM,"appPasswordTicketMatchesTarget");async function mv(e){let t=CM(e.browserTicket),r=await $i(t);if(!IM(r,e))throw g("oauth_callback_mismatch","App password capture ticket did not match the requested upstream flow.");return{upstreamServerId:e.upstreamServerId,authProfileId:r.authProfileId,virtualServerId:r.virtualServerId,browserTicket:t,ticket:r}}o(mv,"readAppPasswordTarget");function PM(e,t){let r=Ku(e.upstreamServerId,e.authProfileId),n=`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`,a=pn(t),i=r.kind==="basic_auth_app_password"?ce`<label class="form__label" for="username">${r.usernameLabel}</label><input class="form__input" id="username" name="username" required autocomplete="username"><label class="form__label" for="appPassword">${r.passwordLabel}</label><input class="form__input" id="appPassword" name="appPassword" type="password" required autocomplete="current-password">`:ce`<label class="form__label" for="token">${r.label}</label><input class="form__input" id="token" name="token" type="password" required autocomplete="off">`;return bM(rr({title:"Connect upstream",iconHref:a,styles:tr,headerIcon:mn({iconHref:a,fallbackIconHref:ln}),heading:"Connect upstream",subhead:ce`<p class="card__subtitle">Enter the per-user credential for this approved upstream.</p>`,body:uv({action:n,browserTicket:e.browserTicket,fields:i}),footer:""}))}o(PM,"renderCaptureForm");function Xs(e,t){let r=e.get(t);if(typeof r!="string"||r.length===0)throw g("invalid_request",`Missing form field: ${t}`);return r}o(Xs,"readRequiredFormValue");function xM(e){return{upstreamServerId:e.upstreamServerId,...e.virtualServerId===void 0?{}:{virtualServerId:e.virtualServerId},...e.browserTicket===void 0?{}:{browserTicket:e.browserTicket}}}o(xM,"readCaptureFormTargetInput");async function AM(e,t){return PM(await mv(xM(e)),t)}o(AM,"handleCaptureFormRequest");async function kM(e){let t=await Ls(e.request,{maxBytes:vM,label:"App password request body"});return{form:t,target:await mv({upstreamServerId:e.upstreamServerId,browserTicket:Xs(t,"browserTicket")})}}o(kM,"readSubmittedAppPasswordTarget");async function TM(e){let t=xn(e.target.ticket);if(await zi(e.target.ticket),Ku(e.target.upstreamServerId,e.target.authProfileId).kind==="bearer_token"){await Mi({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,token:Xs(e.form,"token")});return}await Lh({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,username:Xs(e.form,"username"),appPassword:Xs(e.form,"appPassword")})}o(TM,"saveSubmittedAppPasswordCredential");function EM(e,t){return t.ticket.returnTo?RM(e,t.ticket.returnTo):Qs({host:Up(e),title:"Connection complete",body:"The upstream credential was saved. Return to your MCP client and retry the request."})}o(EM,"appPasswordSuccessResponse");async function UM(e){let t=await kM({request:e.request,upstreamServerId:e.appPasswordRequest.upstreamServerId});return await TM(t),EM(e.request.url,t.target)}o(UM,"handleAppPasswordSubmission");function OM(){return new Response(null,{status:405,headers:{Allow:"GET, POST"}})}o(OM,"methodNotAllowedResponse");function $M(e,t){let r=ge(t);return lo(e,Fa(r)?r:"oauth_state_invalid")}o($M,"appPasswordFailureResponse");async function zM(e){let t=Up(e.request.url);switch(e.request.method){case"GET":return AM(e.appPasswordRequest,t);case"POST":return UM(e);default:return OM()}}o(zM,"handleAppPasswordMethod");async function Op(e,t){let r=yn(t,"app_password");try{return await zM({request:e,appPasswordRequest:r})}catch(n){return $M(Up(e.url),n)}}o(Op,"appPasswordHandler");var MM=["callback_authorization_code","callback_provider_error","callback_invalid"];function qM(e){return"cause"in e?e.cause:void 0}o(qM,"readErrorCause");function NM(e){return e.stack?.split(`
63
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}o(NM,"readFirstStackFrame");function fv(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=NM(r))}o(fv,"addErrorAttributes");function hv(e){try{return new URL(e).host}catch{return""}}o(hv,"safeHostFromUrl");function jM(e,t,r){switch(t.kind){case"callback_provider_error":return e.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:t.upstreamServerId,providerError:t.error,...t.errorDescription===void 0?{}:{providerErrorDescription:t.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),Qe(e,{eventType:Z.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),lo(r,"provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),lo(r,"oauth_state_invalid");case"callback_authorization_code":return t}}o(jM,"requireAuthorizationCallbackRequest");function DM(e,t){Qe(e,{eventType:Z.MCP_GATEWAY_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(DM,"emitCallbackReceivedAnalyticsEvent");function HM(e,t){Qe(e,{eventType:Z.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(HM,"emitTokenExchangeSucceededAnalyticsEvent");function LM(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Qs({host:hv(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(LM,"buildSuccessfulCallbackResponse");function BM(e){let t={detail:e instanceof Error?e.message:void 0};return fv(t,"error",e),e instanceof Error&&fv(t,"cause",qM(e)),t}o(BM,"buildTokenExchangeFailureAttributes");function GM(e){Qe(e.context,{eventType:Z.MCP_GATEWAY_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:ge(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:BM(e.error)})}o(GM,"emitTokenExchangeFailedAnalyticsEvent");function VM(e,t){let r=ge(t);return lo(e,Fa(r)?r:"upstream_token_exchange_failed")}o(VM,"tokenExchangeFailureResponse");async function $p(e,t){let r=yn(t,MM),n=hv(e.url),a=jM(t,r,n);if(a instanceof Response)return a;DM(t,a);try{let i=await yg({request:e,callbackRequest:a});return HM(t,i),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:i.upstreamServerId,virtualServerId:i.virtualServerId,authProfileId:i.authProfileId,ownerMode:i.ownerMode},"Upstream OAuth token exchange completed; user connection established"),LM(e,i)}catch(i){let s={event:"upstream_oauth_token_exchange_failed",code:ge(i)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return Ye(s,"error",i),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),GM({context:t,callbackRequest:a,error:i}),VM(n,i)}}o($p,"callbackHandler");function FM(e){let t=ge(e);return t==="unknown_upstream_server"?t:"not_found"}o(FM,"clientMetadataProblemCode");function ZM(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(ZM,"clientMetadataProblemDetail");async function gv(e,t){let r=yn(t,"connect"),n=await gg({request:e,connectRequest:r});if(Qe(t,{eventType:Z.MCP_GATEWAY_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:n.virtualServerId,upstreamServerTitle:n.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:n.authProfileId,virtualServerId:n.virtualServerId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(n.authUrl,302);let a=await Nn({requestUrl:e.url,owner:n.owner,initiatedBySubjectId:n.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:n.authProfileId,upstreamDisplayName:n.upstreamDisplayName,virtualServerId:n.virtualServerId,subject:"virtual server",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(a,{status:428})}o(gv,"connectHandler");async function yv(e,t){let r=yn(t,"client_metadata");try{let n=rg(e.url),a=ng(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){let a=FM(n),i=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",code:a,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),st(e,t,{code:a,detail:ZM(n)})}}o(yv,"oauthClientMetadataHandler");function nr(e){if(typeof e=="string"&&e.length!==0)return e}o(nr,"readOptionalQueryString");function KM(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw g("internal_server_error",`Validated path parameter ${t} is missing`);return r}o(KM,"requirePathString");function Sv(e){let t=nr(e);return t?xe.parse(t):void 0}o(Sv,"readOptionalVirtualServerId");function JM(e,t){let r=nr(e);return r?We.parse(r):zn(t,"user_oauth")}o(JM,"readOptionalAuthProfileId");function WM(e){let t=Sv(e);if(!t)throw g("invalid_request","virtualServerId query parameter is required.");return t}o(WM,"readRequiredVirtualServerId");function YM(e){let t=nr(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(YM,"readOptionalBrowserTicket");function QM(e){let t=ni(nr(e));return t===void 0?{}:{returnTo:t}}o(QM,"readOptionalReturnTo");function XM(e){let t=Sv(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(XM,"readOptionalVirtualServerIdContext");function eq(e){let t=nr(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o(eq,"readOptionalProviderErrorDescription");function tq(e){let t=xt(e.authMode);if(t.connectSupport!=="none")return e;throw g("invalid_request",t.connectUnsupportedDetail??"This upstream does not support browser connection flows.")}o(tq,"requireConnectableRouteAuth");function rq(e,t,r,n){let a=Hs(e,t);if(a.ownerMode==="none"||a.authMode==="shared-secret")throw g("invalid_request","Static-secret upstreams do not support browser connection flows.");return{kind:"connect",...a,...n===void 0?{}:{returnTo:n},redirect:r}}o(rq,"buildConnectContextForPrincipal");function nq(e,t,r){let n=xn(t),a=xt(e.authMode);if(n.mode!==a.ownerMode)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:n,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}o(nq,"buildConnectContextForTicket");async function oq(e,t){let r=tq(B_(t,WM(e.query.virtualServerId))),n=e.query.redirect==="true",a=nr(e.query.browserTicket);if(e.user){if(a)throw g("invalid_request","Use either an authenticated gateway request or a browser connect ticket, not both.");let s=Cn(e.user,e.url);return rq(r,s,n,QM(e.query.returnTo).returnTo)}if(!a)throw g("authentication_required","Authentication is required to start the upstream connection flow.");let i=await $i(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.virtualServerId!==r.virtualServerId)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return await zi(i),nq(r,i,n)}o(oq,"resolveConnectContext");async function aq(e,t,r){let n=Je.parse(KM(e,"connection"));switch(r){case"connect":gn(t,await oq(e,n));return;case"app_password":gn(t,{kind:"app_password",upstreamServerId:n,...XM(e),...YM(e)});return;case"callback":{let a=nr(e.query.error);if(a){gn(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...eq(e)});return}let i=nr(e.query.code),s=nr(e.query.state);if(i&&s){gn(t,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:s});return}gn(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":gn(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:JM(e.query.authProfileId,n)});return}}o(aq,"resolveUpstreamRequestInbound");async function iq(e,t,r){try{await aq(e,t,r);return}catch(n){let a=ge(n);if(!a)throw n;let i=n instanceof Error?n.message:void 0;return st(e,t,{code:a,...i===void 0?{}:{detail:i}})}}o(iq,"applyUpstreamRequestContext");function ja(e,t){return o(async(n,a)=>{let i=await iq(n,a,e);return i||t(n,a)},"wrapped")}o(ja,"withUpstreamRequestContext");var sq={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function cq(){return new Response(null,{status:204,headers:sq})}o(cq,"buildWellKnownPreflightResponse");function uq(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(uq,"withWellKnownCorsHeaders");function zp(e){return async(t,r)=>t.method==="OPTIONS"?cq():uq(await e(t,r))}o(zp,"wrapWellKnownHandler");var dq=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:zp(Yw),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:zp(Qw),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:zp(_m),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:Xw},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:ev},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:tv},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:rv},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:nv},{routeName:"oauth_api_key_login",path:"/oauth/api-key-login",methods:["GET","POST"],handler:ov},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:av},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:iv},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:sv},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:ja("client_metadata",yv)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:ja("connect",gv)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:ja("callback",$p)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:ja("app_password",Op)}];function _v(e){return e?.some(t=>Ao(t.policyType))??!1}o(_v,"shouldRegisterMcpGatewayInternalRoutes");function lq(e){let t=Uf(e.policies);if(!t){let r=[...Wc].map(n=>`\`${n}\``).join(", ");throw new ue(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return ah(zu({routes:e.routes,policies:e.policies})),t.config}o(lq,"initializeMcpGatewayState");function pq(e,t,r){return async(n,a)=>{let i=a;Rn(i,r());let s=n.method==="OPTIONS",c=Date.now();s||i.log.info({event:`${e}_received`,method:n.method},`MCP gateway: ${e} received`);let d=await t(n,a);return s||i.log.info({event:`${e}_responded`,status:d.status,durationMs:Date.now()-c},`MCP gateway: ${e} responded`),d}}o(pq,"wrapInternalHandler");function wv(e,t){let r,n=o(()=>(r===void 0&&(r=lq(t)),r),"readOAuthConfig");for(let a of dq){let i=pq(a.routeName,a.handler,n),s=o((c,d)=>i(c,d),"handler");e.addPluginRoute({path:a.path,methods:a.methods,handler:s,processors:[sc],corsPolicy:a.corsPolicy??"none"})}}o(wv,"registerMcpGatewayInternalRoutes");function vv(e){oh(e)}o(vv,"configureLazyMcpGatewayState");var Mp=class extends Fp{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!_v(r.policies))return;let n={routes:r.routes,policies:r.policies};vv(n),wv(t.router,n)}};export{Zc as McpAuth0OAuthInboundPolicy,Mp as McpGatewayPlugin,Kc as McpOAuthInboundPolicy,mp as McpUpstreamConnectionInboundPolicy,g$ as McpVirtualServerHandler,Fx as mcpUpstreamHandler};
58
64
  //# sourceMappingURL=index.js.map