@zuplo/runtime 6.70.31 → 6.70.33

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,20 +22,20 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as ot,A as Sc,B as Ot,J as um,K as _c,L as Zw,M as dm,N as f,O as lm,P as ne,Q as ce,R as pm,S as mm,T as Re,U as R,V as C,W as Pe,X as ye,Y as vc,Z as wc,_ as pe,a as Ut,aa as O,b as sm,ba as be,ca as fm,da as bc,ea as hm,fa as gm,ga as u,ha as me,ia as ym,j as pt,k as cm,q as gc,s as kn,x as yc}from"../chunk-TEXCCTJT.js";import{d as ti}from"../chunk-W6JQ5D4W.js";import{a as F}from"../chunk-F7DJMBWH.js";import{W as te,X as A,Y as $,Z as xo,a as o,c as x,e as im}from"../chunk-JAEQKE5H.js";var la=x(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.regexpCode=ae.getEsmExportName=ae.getProperty=ae.safeStringify=ae.stringify=ae.strConcat=ae.addCodeArg=ae.str=ae._=ae.nil=ae._Code=ae.Name=ae.IDENTIFIER=ae._CodeOrName=void 0;var ua=class{static{o(this,"_CodeOrName")}};ae._CodeOrName=ua;ae.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var sn=class extends ua{static{o(this,"Name")}constructor(t){if(super(),!ae.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}}};ae.Name=sn;var yt=class extends ua{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 sn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ae._Code=yt;ae.nil=new yt("");function Lg(e,...t){let r=[e[0]],n=0;for(;n<t.length;)bd(r,t[n]),r.push(e[++n]);return new yt(r)}o(Lg,"_");ae._=Lg;var wd=new yt("+");function Bg(e,...t){let r=[da(e[0])],n=0;for(;n<t.length;)r.push(wd),bd(r,t[n]),r.push(wd,da(e[++n]));return uA(r),new yt(r)}o(Bg,"str");ae.str=Bg;function bd(e,t){t instanceof yt?e.push(...t._items):t instanceof sn?e.push(t):e.push(pA(t))}o(bd,"addCodeArg");ae.addCodeArg=bd;function uA(e){let t=1;for(;t<e.length-1;){if(e[t]===wd){let r=dA(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(uA,"optimize");function dA(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof sn||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 sn))return`"${e}${t.slice(1)}`}o(dA,"mergeExprItems");function lA(e,t){return t.emptyStr()?e:e.emptyStr()?t:Bg`${e}${t}`}o(lA,"strConcat");ae.strConcat=lA;function pA(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:da(Array.isArray(e)?e.join(","):e)}o(pA,"interpolate");function mA(e){return new yt(da(e))}o(mA,"stringify");ae.stringify=mA;function da(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(da,"safeStringify");ae.safeStringify=da;function fA(e){return typeof e=="string"&&ae.IDENTIFIER.test(e)?new yt(`.${e}`):Lg`[${e}]`}o(fA,"getProperty");ae.getProperty=fA;function hA(e){if(typeof e=="string"&&ae.IDENTIFIER.test(e))return new yt(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(hA,"getEsmExportName");ae.getEsmExportName=hA;function gA(e){return new yt(e.toString())}o(gA,"regexpCode");ae.regexpCode=gA});var Id=x(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.ValueScope=tt.ValueScopeName=tt.Scope=tt.varKinds=tt.UsedValueState=void 0;var et=la(),Rd=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Yi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Yi||(tt.UsedValueState=Yi={}));tt.varKinds={const:new et.Name("const"),let:new et.Name("let"),var:new et.Name("var")};var Xi=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof et.Name?t:this.name(t)}name(t){return new et.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}}};tt.Scope=Xi;var Qi=class extends et.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,et._)`.${new et.Name(r)}[${n}]`}};tt.ValueScopeName=Qi;var yA=(0,et._)`\n`,Cd=class extends Xi{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?yA:et.nil}}get(){return this._scope}name(t){return new Qi(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,et._)`${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=et.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,Yi.Started);let l=r(p);if(l){let m=this.opts.es5?tt.varKinds.var:tt.varKinds.const;i=(0,et._)`${i}${m} ${p} = ${l};${this.opts._n}`}else if(l=a?.(p))i=(0,et._)`${i}${l}${this.opts._n}`;else throw new Rd(p);d.set(p,Yi.Completed)})}return i}};tt.ValueScope=Cd});var J=x(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.or=Y.and=Y.not=Y.CodeGen=Y.operators=Y.varKinds=Y.ValueScopeName=Y.ValueScope=Y.Scope=Y.Name=Y.regexpCode=Y.stringify=Y.getProperty=Y.nil=Y.strConcat=Y.str=Y._=void 0;var ee=la(),xt=Id(),Er=la();Object.defineProperty(Y,"_",{enumerable:!0,get:o(function(){return Er._},"get")});Object.defineProperty(Y,"str",{enumerable:!0,get:o(function(){return Er.str},"get")});Object.defineProperty(Y,"strConcat",{enumerable:!0,get:o(function(){return Er.strConcat},"get")});Object.defineProperty(Y,"nil",{enumerable:!0,get:o(function(){return Er.nil},"get")});Object.defineProperty(Y,"getProperty",{enumerable:!0,get:o(function(){return Er.getProperty},"get")});Object.defineProperty(Y,"stringify",{enumerable:!0,get:o(function(){return Er.stringify},"get")});Object.defineProperty(Y,"regexpCode",{enumerable:!0,get:o(function(){return Er.regexpCode},"get")});Object.defineProperty(Y,"Name",{enumerable:!0,get:o(function(){return Er.Name},"get")});var ns=Id();Object.defineProperty(Y,"Scope",{enumerable:!0,get:o(function(){return ns.Scope},"get")});Object.defineProperty(Y,"ValueScope",{enumerable:!0,get:o(function(){return ns.ValueScope},"get")});Object.defineProperty(Y,"ValueScopeName",{enumerable:!0,get:o(function(){return ns.ValueScopeName},"get")});Object.defineProperty(Y,"varKinds",{enumerable:!0,get:o(function(){return ns.varKinds},"get")});Y.operators={GT:new ee._Code(">"),GTE:new ee._Code(">="),LT:new ee._Code("<"),LTE:new ee._Code("<="),EQ:new ee._Code("==="),NEQ:new ee._Code("!=="),NOT:new ee._Code("!"),OR:new ee._Code("||"),AND:new ee._Code("&&"),ADD:new ee._Code("+")};var or=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},Pd=class extends or{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?xt.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=Xn(this.rhs,t,r)),this}get names(){return this.rhs instanceof ee._CodeOrName?this.rhs.names:{}}},es=class extends or{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 ee.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Xn(this.rhs,t,r),this}get names(){let t=this.lhs instanceof ee.Name?{}:{...this.lhs.names};return rs(t,this.rhs)}},xd=class extends es{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}},Ad=class extends or{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},kd=class extends or{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Td=class extends or{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Ed=class extends or{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=Xn(this.code,t,r),this}get names(){return this.code instanceof ee._CodeOrName?this.code.names:{}}},pa=class extends or{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)||(SA(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>dn(t,r.names),{})}},ar=class extends pa{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Ud=class extends pa{static{o(this,"Root")}},Yn=class extends ar{static{o(this,"Else")}};Yn.kind="else";var cn=class e extends ar{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 Yn(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Gg(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=Xn(this.condition,t,r),this}get names(){let t=super.names;return rs(t,this.condition),this.else&&dn(t,this.else.names),t}};cn.kind="if";var un=class extends ar{static{o(this,"For")}};un.kind="for";var Od=class extends un{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=Xn(this.iteration,t,r),this}get names(){return dn(super.names,this.iteration.names)}},Md=class extends un{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?xt.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=rs(super.names,this.from);return rs(t,this.to)}},ts=class extends un{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=Xn(this.iterable,t,r),this}get names(){return dn(super.names,this.iterable.names)}},ma=class extends ar{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)}};ma.kind="func";var fa=class extends pa{static{o(this,"Return")}render(t){return"return "+super.render(t)}};fa.kind="return";var zd=class extends ar{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&&dn(t,this.catch.names),this.finally&&dn(t,this.finally.names),t}},ha=class extends ar{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};ha.kind="catch";var ga=class extends ar{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};ga.kind="finally";var $d=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 xt.Scope({parent:t}),this._nodes=[new Ud]}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 Pd(t,i,n)),i}const(t,r,n){return this._def(xt.varKinds.const,t,r,n)}let(t,r,n){return this._def(xt.varKinds.let,t,r,n)}var(t,r,n){return this._def(xt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new es(t,r,n))}add(t,r){return this._leafNode(new xd(t,Y.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==ee.nil&&this._leafNode(new Ed(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,ee.addCodeArg)(r,a));return r.push("}"),new ee._Code(r)}if(t,r,n){if(this._blockNode(new cn(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 cn(t))}else(){return this._elseNode(new Yn)}endIf(){return this._endBlockNode(cn,Yn)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Od(t),r)}forRange(t,r,n,a,i=this.opts.es5?xt.varKinds.var:xt.varKinds.let){let s=this._scope.toName(t);return this._for(new Md(i,s,r,n),()=>a(s))}forOf(t,r,n,a=xt.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof ee.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ee._)`${s}.length`,c=>{this.var(i,(0,ee._)`${s}[${c}]`),n(i)})}return this._for(new ts("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?xt.varKinds.var:xt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,ee._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new ts("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(un)}label(t){return this._leafNode(new Ad(t))}break(t){return this._leafNode(new kd(t))}return(t){let r=new fa;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fa)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new zd;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new ha(i),r(i)}return n&&(this._currNode=a.finally=new ga,this.code(n)),this._endBlockNode(ha,ga)}throw(t){return this._leafNode(new Td(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=ee.nil,n,a){return this._blockNode(new ma(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(ma)}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 cn))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}};Y.CodeGen=$d;function dn(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(dn,"addNames");function rs(e,t){return t instanceof ee._CodeOrName?dn(e,t.names):e}o(rs,"addExprNames");function Xn(e,t,r){if(e instanceof ee.Name)return n(e);if(!a(e))return e;return new ee._Code(e._items.reduce((i,s)=>(s instanceof ee.Name&&(s=n(s)),s instanceof ee._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 ee._Code&&i._items.some(s=>s instanceof ee.Name&&t[s.str]===1&&r[s.str]!==void 0)}}o(Xn,"optimizeExpr");function SA(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(SA,"subtractNames");function Gg(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,ee._)`!${qd(e)}`}o(Gg,"not");Y.not=Gg;var _A=Vg(Y.operators.AND);function vA(...e){return e.reduce(_A)}o(vA,"and");Y.and=vA;var wA=Vg(Y.operators.OR);function bA(...e){return e.reduce(wA)}o(bA,"or");Y.or=bA;function Vg(e){return(t,r)=>t===ee.nil?r:r===ee.nil?t:(0,ee._)`${qd(t)} ${e} ${qd(r)}`}o(Vg,"mappend");function qd(e){return e instanceof ee.Name?e:(0,ee._)`(${e})`}o(qd,"par")});var ie=x(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.checkStrictMode=Q.getErrorPath=Q.Type=Q.useFunc=Q.setEvaluated=Q.evaluatedPropsToName=Q.mergeEvaluated=Q.eachItem=Q.unescapeJsonPointer=Q.escapeJsonPointer=Q.escapeFragment=Q.unescapeFragment=Q.schemaRefOrVal=Q.schemaHasRulesButRef=Q.schemaHasRules=Q.checkUnknownRules=Q.alwaysValidSchema=Q.toHash=void 0;var de=J(),RA=la();function CA(e){let t={};for(let r of e)t[r]=!0;return t}o(CA,"toHash");Q.toHash=CA;function IA(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Kg(e,t),!Jg(t,e.self.RULES.all))}o(IA,"alwaysValidSchema");Q.alwaysValidSchema=IA;function Kg(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]||Xg(e,`unknown keyword: "${i}"`)}o(Kg,"checkUnknownRules");Q.checkUnknownRules=Kg;function Jg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(Jg,"schemaHasRules");Q.schemaHasRules=Jg;function PA(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(PA,"schemaHasRulesButRef");Q.schemaHasRulesButRef=PA;function xA({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,de._)`${r}`}return(0,de._)`${e}${t}${(0,de.getProperty)(n)}`}o(xA,"schemaRefOrVal");Q.schemaRefOrVal=xA;function AA(e){return Wg(decodeURIComponent(e))}o(AA,"unescapeFragment");Q.unescapeFragment=AA;function kA(e){return encodeURIComponent(Dd(e))}o(kA,"escapeFragment");Q.escapeFragment=kA;function Dd(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(Dd,"escapeJsonPointer");Q.escapeJsonPointer=Dd;function Wg(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(Wg,"unescapeJsonPointer");Q.unescapeJsonPointer=Wg;function TA(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o(TA,"eachItem");Q.eachItem=TA;function Fg({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,s,c)=>{let d=s===void 0?i:s instanceof de.Name?(i instanceof de.Name?e(a,i,s):t(a,i,s),s):i instanceof de.Name?(t(a,s,i),i):r(i,s);return c===de.Name&&!(d instanceof de.Name)?n(a,d):d}}o(Fg,"makeMergeEvaluated");Q.mergeEvaluated={props:Fg({mergeNames:o((e,t,r)=>e.if((0,de._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,de._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,de._)`${r} || {}`).code((0,de._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,de._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,de._)`${r} || {}`),jd(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:Yg}),items:Fg({mergeNames:o((e,t,r)=>e.if((0,de._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,de._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,de._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,de._)`${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 Yg(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,de._)`{}`);return t!==void 0&&jd(e,r,t),r}o(Yg,"evaluatedPropsToName");Q.evaluatedPropsToName=Yg;function jd(e,t,r){Object.keys(r).forEach(n=>e.assign((0,de._)`${t}${(0,de.getProperty)(n)}`,!0))}o(jd,"setEvaluated");Q.setEvaluated=jd;var Zg={};function EA(e,t){return e.scopeValue("func",{ref:t,code:Zg[t.code]||(Zg[t.code]=new RA._Code(t.code))})}o(EA,"useFunc");Q.useFunc=EA;var Nd;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Nd||(Q.Type=Nd={}));function UA(e,t,r){if(e instanceof de.Name){let n=t===Nd.Num;return r?n?(0,de._)`"[" + ${e} + "]"`:(0,de._)`"['" + ${e} + "']"`:n?(0,de._)`"/" + ${e}`:(0,de._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,de.getProperty)(e).toString():"/"+Dd(e)}o(UA,"getErrorPath");Q.getErrorPath=UA;function Xg(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(Xg,"checkStrictMode");Q.checkStrictMode=Xg});var ir=x(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Be=J(),OA={data:new Be.Name("data"),valCxt:new Be.Name("valCxt"),instancePath:new Be.Name("instancePath"),parentData:new Be.Name("parentData"),parentDataProperty:new Be.Name("parentDataProperty"),rootData:new Be.Name("rootData"),dynamicAnchors:new Be.Name("dynamicAnchors"),vErrors:new Be.Name("vErrors"),errors:new Be.Name("errors"),this:new Be.Name("this"),self:new Be.Name("self"),scope:new Be.Name("scope"),json:new Be.Name("json"),jsonPos:new Be.Name("jsonPos"),jsonLen:new Be.Name("jsonLen"),jsonPart:new Be.Name("jsonPart")};Hd.default=OA});var ya=x(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.extendErrors=Ge.resetErrorsCount=Ge.reportExtraError=Ge.reportError=Ge.keyword$DataError=Ge.keywordError=void 0;var re=J(),os=ie(),Ze=ir();Ge.keywordError={message:o(({keyword:e})=>(0,re.str)`must pass "${e}" keyword validation`,"message")};Ge.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,re.str)`"${e}" keyword must be ${t} ($data)`:(0,re.str)`"${e}" keyword is invalid ($data)`,"message")};function MA(e,t=Ge.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:s,allErrors:c}=a,d=ty(e,t,r);n??(s||c)?Qg(i,d):ey(a,(0,re._)`[${d}]`)}o(MA,"reportError");Ge.reportError=MA;function zA(e,t=Ge.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:s}=n,c=ty(e,t,r);Qg(a,c),i||s||ey(n,Ze.default.vErrors)}o(zA,"reportExtraError");Ge.reportExtraError=zA;function $A(e,t){e.assign(Ze.default.errors,t),e.if((0,re._)`${Ze.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,re._)`${Ze.default.vErrors}.length`,t),()=>e.assign(Ze.default.vErrors,null)))}o($A,"resetErrorsCount");Ge.resetErrorsCount=$A;function qA({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,Ze.default.errors,c=>{e.const(s,(0,re._)`${Ze.default.vErrors}[${c}]`),e.if((0,re._)`${s}.instancePath === undefined`,()=>e.assign((0,re._)`${s}.instancePath`,(0,re.strConcat)(Ze.default.instancePath,i.errorPath))),e.assign((0,re._)`${s}.schemaPath`,(0,re.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,re._)`${s}.schema`,r),e.assign((0,re._)`${s}.data`,n))})}o(qA,"extendErrors");Ge.extendErrors=qA;function Qg(e,t){let r=e.const("err",t);e.if((0,re._)`${Ze.default.vErrors} === null`,()=>e.assign(Ze.default.vErrors,(0,re._)`[${r}]`),(0,re._)`${Ze.default.vErrors}.push(${r})`),e.code((0,re._)`${Ze.default.errors}++`)}o(Qg,"addError");function ey(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,re._)`new ${e.ValidationError}(${t})`):(r.assign((0,re._)`${n}.errors`,t),r.return(!1))}o(ey,"returnErrors");var ln={keyword:new re.Name("keyword"),schemaPath:new re.Name("schemaPath"),params:new re.Name("params"),propertyName:new re.Name("propertyName"),message:new re.Name("message"),schema:new re.Name("schema"),parentSchema:new re.Name("parentSchema")};function ty(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,re._)`{}`:NA(e,t,r)}o(ty,"errorObjectCode");function NA(e,t,r={}){let{gen:n,it:a}=e,i=[DA(a,r),jA(e,r)];return HA(e,t,i),n.object(...i)}o(NA,"errorObject");function DA({errorPath:e},{instancePath:t}){let r=t?(0,re.str)`${e}${(0,os.getErrorPath)(t,os.Type.Str)}`:e;return[Ze.default.instancePath,(0,re.strConcat)(Ze.default.instancePath,r)]}o(DA,"errorInstancePath");function jA({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,re.str)`${t}/${e}`;return r&&(a=(0,re.str)`${a}${(0,os.getErrorPath)(r,os.Type.Str)}`),[ln.schemaPath,a]}o(jA,"errorSchemaPath");function HA(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([ln.keyword,a],[ln.params,typeof t=="function"?t(e):t||(0,re._)`{}`]),d.messages&&n.push([ln.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([ln.schema,s],[ln.parentSchema,(0,re._)`${l}${m}`],[Ze.default.data,i]),p&&n.push([ln.propertyName,p])}o(HA,"extraErrorProps")});var ny=x(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.boolOrEmptySchema=Qn.topBoolOrEmptySchema=void 0;var LA=ya(),BA=J(),GA=ir(),VA={message:"boolean schema is false"};function FA(e){let{gen:t,schema:r,validateName:n}=e;r===!1?ry(e,!1):typeof r=="object"&&r.$async===!0?t.return(GA.default.data):(t.assign((0,BA._)`${n}.errors`,null),t.return(!0))}o(FA,"topBoolOrEmptySchema");Qn.topBoolOrEmptySchema=FA;function ZA(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),ry(e)):r.var(t,!0)}o(ZA,"boolOrEmptySchema");Qn.boolOrEmptySchema=ZA;function ry(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,LA.reportError)(a,VA,void 0,t)}o(ry,"falseSchemaError")});var Ld=x(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.getRules=eo.isJSONType=void 0;var KA=["string","number","integer","boolean","null","object","array"],JA=new Set(KA);function WA(e){return typeof e=="string"&&JA.has(e)}o(WA,"isJSONType");eo.isJSONType=WA;function YA(){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(YA,"getRules");eo.getRules=YA});var Bd=x(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.shouldUseRule=Ur.shouldUseGroup=Ur.schemaHasRulesForType=void 0;function XA({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&oy(e,n)}o(XA,"schemaHasRulesForType");Ur.schemaHasRulesForType=XA;function oy(e,t){return t.rules.some(r=>ay(e,r))}o(oy,"shouldUseGroup");Ur.shouldUseGroup=oy;function ay(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(ay,"shouldUseRule");Ur.shouldUseRule=ay});var Sa=x(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.reportTypeError=Ve.checkDataTypes=Ve.checkDataType=Ve.coerceAndCheckDataType=Ve.getJSONTypes=Ve.getSchemaTypes=Ve.DataType=void 0;var QA=Ld(),ek=Bd(),tk=ya(),Z=J(),iy=ie(),to;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(to||(Ve.DataType=to={}));function rk(e){let t=sy(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(rk,"getSchemaTypes");Ve.getSchemaTypes=rk;function sy(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(QA.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(sy,"getJSONTypes");Ve.getJSONTypes=sy;function nk(e,t){let{gen:r,data:n,opts:a}=e,i=ok(t,a.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,ek.schemaHasRulesForType)(e,t[0]));if(s){let c=Vd(t,n,a.strictNumbers,to.Wrong);r.if(c,()=>{i.length?ak(e,t,i):Fd(e)})}return s}o(nk,"coerceAndCheckDataType");Ve.coerceAndCheckDataType=nk;var cy=new Set(["string","number","integer","boolean","null"]);function ok(e,t){return t?e.filter(r=>cy.has(r)||t==="array"&&r==="array"):[]}o(ok,"coerceToTypes");function ak(e,t,r){let{gen:n,data:a,opts:i}=e,s=n.let("dataType",(0,Z._)`typeof ${a}`),c=n.let("coerced",(0,Z._)`undefined`);i.coerceTypes==="array"&&n.if((0,Z._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,Z._)`${a}[0]`).assign(s,(0,Z._)`typeof ${a}`).if(Vd(t,a,i.strictNumbers),()=>n.assign(c,a))),n.if((0,Z._)`${c} !== undefined`);for(let p of r)(cy.has(p)||p==="array"&&i.coerceTypes==="array")&&d(p);n.else(),Fd(e),n.endIf(),n.if((0,Z._)`${c} !== undefined`,()=>{n.assign(a,c),ik(e,c)});function d(p){switch(p){case"string":n.elseIf((0,Z._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,Z._)`"" + ${a}`).elseIf((0,Z._)`${a} === null`).assign(c,(0,Z._)`""`);return;case"number":n.elseIf((0,Z._)`${s} == "boolean" || ${a} === null
25
+ import{$ as ct,A as vc,B as $t,J as lm,K as wc,L as rb,M as pm,N as f,O as mm,P as ne,Q as ue,R as fm,S as hm,T as Re,U as R,V as C,W as Pe,X as ye,Y as bc,Z as Rc,_ as me,a as zt,aa as O,b as um,ba as be,ca as gm,da as Cc,ea as ym,fa as Sm,ga as u,ha as de,ia as _m,j as Ae,k as dm,q as Sc,s as Un,x as _c}from"../chunk-SFFHEDT5.js";import{d as ni}from"../chunk-TOF2KNST.js";import{a as F}from"../chunk-A2CSR4RF.js";import{$ as K,a as o,aa as E,ba as q,c as x,ca as Eo,e as cm}from"../chunk-2VLXJLVI.js";var ha=x(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.regexpCode=ae.getEsmExportName=ae.getProperty=ae.safeStringify=ae.stringify=ae.strConcat=ae.addCodeArg=ae.str=ae._=ae.nil=ae._Code=ae.Name=ae.IDENTIFIER=ae._CodeOrName=void 0;var ma=class{static{o(this,"_CodeOrName")}};ae._CodeOrName=ma;ae.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var mn=class extends ma{static{o(this,"Name")}constructor(t){if(super(),!ae.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}}};ae.Name=mn;var _t=class extends ma{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 mn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ae._Code=_t;ae.nil=new _t("");function Jg(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Rd(r,t[n]),r.push(e[++n]);return new _t(r)}o(Jg,"_");ae._=Jg;var bd=new _t("+");function Wg(e,...t){let r=[fa(e[0])],n=0;for(;n<t.length;)r.push(bd),Rd(r,t[n]),r.push(bd,fa(e[++n]));return Ik(r),new _t(r)}o(Wg,"str");ae.str=Wg;function Rd(e,t){t instanceof _t?e.push(...t._items):t instanceof mn?e.push(t):e.push(kk(t))}o(Rd,"addCodeArg");ae.addCodeArg=Rd;function Ik(e){let t=1;for(;t<e.length-1;){if(e[t]===bd){let r=Pk(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(Ik,"optimize");function Pk(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof mn||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 mn))return`"${e}${t.slice(1)}`}o(Pk,"mergeExprItems");function xk(e,t){return t.emptyStr()?e:e.emptyStr()?t:Wg`${e}${t}`}o(xk,"strConcat");ae.strConcat=xk;function kk(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:fa(Array.isArray(e)?e.join(","):e)}o(kk,"interpolate");function Ak(e){return new _t(fa(e))}o(Ak,"stringify");ae.stringify=Ak;function fa(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(fa,"safeStringify");ae.safeStringify=fa;function Tk(e){return typeof e=="string"&&ae.IDENTIFIER.test(e)?new _t(`.${e}`):Jg`[${e}]`}o(Tk,"getProperty");ae.getProperty=Tk;function Ek(e){if(typeof e=="string"&&ae.IDENTIFIER.test(e))return new _t(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(Ek,"getEsmExportName");ae.getEsmExportName=Ek;function Uk(e){return new _t(e.toString())}o(Uk,"regexpCode");ae.regexpCode=Uk});var Pd=x(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.ValueScope=at.ValueScopeName=at.Scope=at.varKinds=at.UsedValueState=void 0;var ot=ha(),Cd=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Qi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Qi||(at.UsedValueState=Qi={}));at.varKinds={const:new ot.Name("const"),let:new ot.Name("let"),var:new ot.Name("var")};var es=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof ot.Name?t:this.name(t)}name(t){return new ot.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}}};at.Scope=es;var ts=class extends ot.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,ot._)`.${new ot.Name(r)}[${n}]`}};at.ValueScopeName=ts;var Ok=(0,ot._)`\n`,Id=class extends es{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Ok:ot.nil}}get(){return this._scope}name(t){return new ts(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,ot._)`${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=ot.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,Qi.Started);let l=r(p);if(l){let m=this.opts.es5?at.varKinds.var:at.varKinds.const;i=(0,ot._)`${i}${m} ${p} = ${l};${this.opts._n}`}else if(l=a?.(p))i=(0,ot._)`${i}${l}${this.opts._n}`;else throw new Cd(p);d.set(p,Qi.Completed)})}return i}};at.ValueScope=Id});var W=x(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.or=X.and=X.not=X.CodeGen=X.operators=X.varKinds=X.ValueScopeName=X.ValueScope=X.Scope=X.Name=X.regexpCode=X.stringify=X.getProperty=X.nil=X.strConcat=X.str=X._=void 0;var te=ha(),kt=Pd(),Nr=ha();Object.defineProperty(X,"_",{enumerable:!0,get:o(function(){return Nr._},"get")});Object.defineProperty(X,"str",{enumerable:!0,get:o(function(){return Nr.str},"get")});Object.defineProperty(X,"strConcat",{enumerable:!0,get:o(function(){return Nr.strConcat},"get")});Object.defineProperty(X,"nil",{enumerable:!0,get:o(function(){return Nr.nil},"get")});Object.defineProperty(X,"getProperty",{enumerable:!0,get:o(function(){return Nr.getProperty},"get")});Object.defineProperty(X,"stringify",{enumerable:!0,get:o(function(){return Nr.stringify},"get")});Object.defineProperty(X,"regexpCode",{enumerable:!0,get:o(function(){return Nr.regexpCode},"get")});Object.defineProperty(X,"Name",{enumerable:!0,get:o(function(){return Nr.Name},"get")});var as=Pd();Object.defineProperty(X,"Scope",{enumerable:!0,get:o(function(){return as.Scope},"get")});Object.defineProperty(X,"ValueScope",{enumerable:!0,get:o(function(){return as.ValueScope},"get")});Object.defineProperty(X,"ValueScopeName",{enumerable:!0,get:o(function(){return as.ValueScopeName},"get")});Object.defineProperty(X,"varKinds",{enumerable:!0,get:o(function(){return as.varKinds},"get")});X.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var dr=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},xd=class extends dr{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?kt.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=ro(this.rhs,t,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},rs=class extends dr{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 te.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=ro(this.rhs,t,r),this}get names(){let t=this.lhs instanceof te.Name?{}:{...this.lhs.names};return os(t,this.rhs)}},kd=class extends rs{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}},Ad=class extends dr{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},Td=class extends dr{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},Ed=class extends dr{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},Ud=class extends dr{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=ro(this.code,t,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},ga=class extends dr{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)||(Mk(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>gn(t,r.names),{})}},lr=class extends ga{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},Od=class extends ga{static{o(this,"Root")}},to=class extends lr{static{o(this,"Else")}};to.kind="else";var fn=class e extends lr{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 to(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Yg(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=ro(this.condition,t,r),this}get names(){let t=super.names;return os(t,this.condition),this.else&&gn(t,this.else.names),t}};fn.kind="if";var hn=class extends lr{static{o(this,"For")}};hn.kind="for";var Md=class extends hn{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=ro(this.iteration,t,r),this}get names(){return gn(super.names,this.iteration.names)}},zd=class extends hn{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?kt.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=os(super.names,this.from);return os(t,this.to)}},ns=class extends hn{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=ro(this.iterable,t,r),this}get names(){return gn(super.names,this.iterable.names)}},ya=class extends lr{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)}};ya.kind="func";var Sa=class extends ga{static{o(this,"Return")}render(t){return"return "+super.render(t)}};Sa.kind="return";var $d=class extends lr{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&&gn(t,this.catch.names),this.finally&&gn(t,this.finally.names),t}},_a=class extends lr{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};_a.kind="catch";var va=class extends lr{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};va.kind="finally";var qd=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 kt.Scope({parent:t}),this._nodes=[new Od]}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 xd(t,i,n)),i}const(t,r,n){return this._def(kt.varKinds.const,t,r,n)}let(t,r,n){return this._def(kt.varKinds.let,t,r,n)}var(t,r,n){return this._def(kt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new rs(t,r,n))}add(t,r){return this._leafNode(new kd(t,X.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==te.nil&&this._leafNode(new Ud(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,te.addCodeArg)(r,a));return r.push("}"),new te._Code(r)}if(t,r,n){if(this._blockNode(new fn(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 fn(t))}else(){return this._elseNode(new to)}endIf(){return this._endBlockNode(fn,to)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Md(t),r)}forRange(t,r,n,a,i=this.opts.es5?kt.varKinds.var:kt.varKinds.let){let s=this._scope.toName(t);return this._for(new zd(i,s,r,n),()=>a(s))}forOf(t,r,n,a=kt.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${s}.length`,c=>{this.var(i,(0,te._)`${s}[${c}]`),n(i)})}return this._for(new ns("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?kt.varKinds.var:kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,te._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new ns("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(hn)}label(t){return this._leafNode(new Ad(t))}break(t){return this._leafNode(new Td(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 $d;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new _a(i),r(i)}return n&&(this._currNode=a.finally=new va,this.code(n)),this._endBlockNode(_a,va)}throw(t){return this._leafNode(new Ed(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=te.nil,n,a){return this._blockNode(new ya(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(ya)}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 fn))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}};X.CodeGen=qd;function gn(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(gn,"addNames");function os(e,t){return t instanceof te._CodeOrName?gn(e,t.names):e}o(os,"addExprNames");function ro(e,t,r){if(e instanceof te.Name)return n(e);if(!a(e))return e;return new te._Code(e._items.reduce((i,s)=>(s instanceof te.Name&&(s=n(s)),s instanceof te._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 te._Code&&i._items.some(s=>s instanceof te.Name&&t[s.str]===1&&r[s.str]!==void 0)}}o(ro,"optimizeExpr");function Mk(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(Mk,"subtractNames");function Yg(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,te._)`!${Nd(e)}`}o(Yg,"not");X.not=Yg;var zk=Xg(X.operators.AND);function $k(...e){return e.reduce(zk)}o($k,"and");X.and=$k;var qk=Xg(X.operators.OR);function Nk(...e){return e.reduce(qk)}o(Nk,"or");X.or=Nk;function Xg(e){return(t,r)=>t===te.nil?r:r===te.nil?t:(0,te._)`${Nd(t)} ${e} ${Nd(r)}`}o(Xg,"mappend");function Nd(e){return e instanceof te.Name?e:(0,te._)`(${e})`}o(Nd,"par")});var ie=x(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.checkStrictMode=ee.getErrorPath=ee.Type=ee.useFunc=ee.setEvaluated=ee.evaluatedPropsToName=ee.mergeEvaluated=ee.eachItem=ee.unescapeJsonPointer=ee.escapeJsonPointer=ee.escapeFragment=ee.unescapeFragment=ee.schemaRefOrVal=ee.schemaHasRulesButRef=ee.schemaHasRules=ee.checkUnknownRules=ee.alwaysValidSchema=ee.toHash=void 0;var pe=W(),Dk=ha();function jk(e){let t={};for(let r of e)t[r]=!0;return t}o(jk,"toHash");ee.toHash=jk;function Hk(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(ty(e,t),!ry(t,e.self.RULES.all))}o(Hk,"alwaysValidSchema");ee.alwaysValidSchema=Hk;function ty(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]||ay(e,`unknown keyword: "${i}"`)}o(ty,"checkUnknownRules");ee.checkUnknownRules=ty;function ry(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(ry,"schemaHasRules");ee.schemaHasRules=ry;function Lk(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(Lk,"schemaHasRulesButRef");ee.schemaHasRulesButRef=Lk;function Bk({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,pe._)`${r}`}return(0,pe._)`${e}${t}${(0,pe.getProperty)(n)}`}o(Bk,"schemaRefOrVal");ee.schemaRefOrVal=Bk;function Gk(e){return ny(decodeURIComponent(e))}o(Gk,"unescapeFragment");ee.unescapeFragment=Gk;function Vk(e){return encodeURIComponent(jd(e))}o(Vk,"escapeFragment");ee.escapeFragment=Vk;function jd(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(jd,"escapeJsonPointer");ee.escapeJsonPointer=jd;function ny(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(ny,"unescapeJsonPointer");ee.unescapeJsonPointer=ny;function Fk(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o(Fk,"eachItem");ee.eachItem=Fk;function Qg({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,s,c)=>{let d=s===void 0?i:s instanceof pe.Name?(i instanceof pe.Name?e(a,i,s):t(a,i,s),s):i instanceof pe.Name?(t(a,s,i),i):r(i,s);return c===pe.Name&&!(d instanceof pe.Name)?n(a,d):d}}o(Qg,"makeMergeEvaluated");ee.mergeEvaluated={props:Qg({mergeNames:o((e,t,r)=>e.if((0,pe._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,pe._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,pe._)`${r} || {}`).code((0,pe._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,pe._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,pe._)`${r} || {}`),Hd(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:oy}),items:Qg({mergeNames:o((e,t,r)=>e.if((0,pe._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,pe._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,pe._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,pe._)`${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 oy(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,pe._)`{}`);return t!==void 0&&Hd(e,r,t),r}o(oy,"evaluatedPropsToName");ee.evaluatedPropsToName=oy;function Hd(e,t,r){Object.keys(r).forEach(n=>e.assign((0,pe._)`${t}${(0,pe.getProperty)(n)}`,!0))}o(Hd,"setEvaluated");ee.setEvaluated=Hd;var ey={};function Zk(e,t){return e.scopeValue("func",{ref:t,code:ey[t.code]||(ey[t.code]=new Dk._Code(t.code))})}o(Zk,"useFunc");ee.useFunc=Zk;var Dd;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Dd||(ee.Type=Dd={}));function Kk(e,t,r){if(e instanceof pe.Name){let n=t===Dd.Num;return r?n?(0,pe._)`"[" + ${e} + "]"`:(0,pe._)`"['" + ${e} + "']"`:n?(0,pe._)`"/" + ${e}`:(0,pe._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,pe.getProperty)(e).toString():"/"+jd(e)}o(Kk,"getErrorPath");ee.getErrorPath=Kk;function ay(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(ay,"checkStrictMode");ee.checkStrictMode=ay});var pr=x(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Ve=W(),Jk={data:new Ve.Name("data"),valCxt:new Ve.Name("valCxt"),instancePath:new Ve.Name("instancePath"),parentData:new Ve.Name("parentData"),parentDataProperty:new Ve.Name("parentDataProperty"),rootData:new Ve.Name("rootData"),dynamicAnchors:new Ve.Name("dynamicAnchors"),vErrors:new Ve.Name("vErrors"),errors:new Ve.Name("errors"),this:new Ve.Name("this"),self:new Ve.Name("self"),scope:new Ve.Name("scope"),json:new Ve.Name("json"),jsonPos:new Ve.Name("jsonPos"),jsonLen:new Ve.Name("jsonLen"),jsonPart:new Ve.Name("jsonPart")};Ld.default=Jk});var wa=x(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.extendErrors=Fe.resetErrorsCount=Fe.reportExtraError=Fe.reportError=Fe.keyword$DataError=Fe.keywordError=void 0;var re=W(),is=ie(),Je=pr();Fe.keywordError={message:o(({keyword:e})=>(0,re.str)`must pass "${e}" keyword validation`,"message")};Fe.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,re.str)`"${e}" keyword must be ${t} ($data)`:(0,re.str)`"${e}" keyword is invalid ($data)`,"message")};function Wk(e,t=Fe.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:s,allErrors:c}=a,d=cy(e,t,r);n??(s||c)?iy(i,d):sy(a,(0,re._)`[${d}]`)}o(Wk,"reportError");Fe.reportError=Wk;function Yk(e,t=Fe.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:s}=n,c=cy(e,t,r);iy(a,c),i||s||sy(n,Je.default.vErrors)}o(Yk,"reportExtraError");Fe.reportExtraError=Yk;function Xk(e,t){e.assign(Je.default.errors,t),e.if((0,re._)`${Je.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,re._)`${Je.default.vErrors}.length`,t),()=>e.assign(Je.default.vErrors,null)))}o(Xk,"resetErrorsCount");Fe.resetErrorsCount=Xk;function Qk({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,Je.default.errors,c=>{e.const(s,(0,re._)`${Je.default.vErrors}[${c}]`),e.if((0,re._)`${s}.instancePath === undefined`,()=>e.assign((0,re._)`${s}.instancePath`,(0,re.strConcat)(Je.default.instancePath,i.errorPath))),e.assign((0,re._)`${s}.schemaPath`,(0,re.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,re._)`${s}.schema`,r),e.assign((0,re._)`${s}.data`,n))})}o(Qk,"extendErrors");Fe.extendErrors=Qk;function iy(e,t){let r=e.const("err",t);e.if((0,re._)`${Je.default.vErrors} === null`,()=>e.assign(Je.default.vErrors,(0,re._)`[${r}]`),(0,re._)`${Je.default.vErrors}.push(${r})`),e.code((0,re._)`${Je.default.errors}++`)}o(iy,"addError");function sy(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,re._)`new ${e.ValidationError}(${t})`):(r.assign((0,re._)`${n}.errors`,t),r.return(!1))}o(sy,"returnErrors");var yn={keyword:new re.Name("keyword"),schemaPath:new re.Name("schemaPath"),params:new re.Name("params"),propertyName:new re.Name("propertyName"),message:new re.Name("message"),schema:new re.Name("schema"),parentSchema:new re.Name("parentSchema")};function cy(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,re._)`{}`:eA(e,t,r)}o(cy,"errorObjectCode");function eA(e,t,r={}){let{gen:n,it:a}=e,i=[tA(a,r),rA(e,r)];return nA(e,t,i),n.object(...i)}o(eA,"errorObject");function tA({errorPath:e},{instancePath:t}){let r=t?(0,re.str)`${e}${(0,is.getErrorPath)(t,is.Type.Str)}`:e;return[Je.default.instancePath,(0,re.strConcat)(Je.default.instancePath,r)]}o(tA,"errorInstancePath");function rA({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,re.str)`${t}/${e}`;return r&&(a=(0,re.str)`${a}${(0,is.getErrorPath)(r,is.Type.Str)}`),[yn.schemaPath,a]}o(rA,"errorSchemaPath");function nA(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([yn.keyword,a],[yn.params,typeof t=="function"?t(e):t||(0,re._)`{}`]),d.messages&&n.push([yn.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([yn.schema,s],[yn.parentSchema,(0,re._)`${l}${m}`],[Je.default.data,i]),p&&n.push([yn.propertyName,p])}o(nA,"extraErrorProps")});var dy=x(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.boolOrEmptySchema=no.topBoolOrEmptySchema=void 0;var oA=wa(),aA=W(),iA=pr(),sA={message:"boolean schema is false"};function cA(e){let{gen:t,schema:r,validateName:n}=e;r===!1?uy(e,!1):typeof r=="object"&&r.$async===!0?t.return(iA.default.data):(t.assign((0,aA._)`${n}.errors`,null),t.return(!0))}o(cA,"topBoolOrEmptySchema");no.topBoolOrEmptySchema=cA;function uA(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),uy(e)):r.var(t,!0)}o(uA,"boolOrEmptySchema");no.boolOrEmptySchema=uA;function uy(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,oA.reportError)(a,sA,void 0,t)}o(uy,"falseSchemaError")});var Bd=x(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.getRules=oo.isJSONType=void 0;var dA=["string","number","integer","boolean","null","object","array"],lA=new Set(dA);function pA(e){return typeof e=="string"&&lA.has(e)}o(pA,"isJSONType");oo.isJSONType=pA;function mA(){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(mA,"getRules");oo.getRules=mA});var Gd=x(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.shouldUseRule=Dr.shouldUseGroup=Dr.schemaHasRulesForType=void 0;function fA({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&ly(e,n)}o(fA,"schemaHasRulesForType");Dr.schemaHasRulesForType=fA;function ly(e,t){return t.rules.some(r=>py(e,r))}o(ly,"shouldUseGroup");Dr.shouldUseGroup=ly;function py(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(py,"shouldUseRule");Dr.shouldUseRule=py});var ba=x(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.reportTypeError=Ze.checkDataTypes=Ze.checkDataType=Ze.coerceAndCheckDataType=Ze.getJSONTypes=Ze.getSchemaTypes=Ze.DataType=void 0;var hA=Bd(),gA=Gd(),yA=wa(),Z=W(),my=ie(),ao;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(ao||(Ze.DataType=ao={}));function SA(e){let t=fy(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(SA,"getSchemaTypes");Ze.getSchemaTypes=SA;function fy(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(hA.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(fy,"getJSONTypes");Ze.getJSONTypes=fy;function _A(e,t){let{gen:r,data:n,opts:a}=e,i=vA(t,a.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,gA.schemaHasRulesForType)(e,t[0]));if(s){let c=Fd(t,n,a.strictNumbers,ao.Wrong);r.if(c,()=>{i.length?wA(e,t,i):Zd(e)})}return s}o(_A,"coerceAndCheckDataType");Ze.coerceAndCheckDataType=_A;var hy=new Set(["string","number","integer","boolean","null"]);function vA(e,t){return t?e.filter(r=>hy.has(r)||t==="array"&&r==="array"):[]}o(vA,"coerceToTypes");function wA(e,t,r){let{gen:n,data:a,opts:i}=e,s=n.let("dataType",(0,Z._)`typeof ${a}`),c=n.let("coerced",(0,Z._)`undefined`);i.coerceTypes==="array"&&n.if((0,Z._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,Z._)`${a}[0]`).assign(s,(0,Z._)`typeof ${a}`).if(Fd(t,a,i.strictNumbers),()=>n.assign(c,a))),n.if((0,Z._)`${c} !== undefined`);for(let p of r)(hy.has(p)||p==="array"&&i.coerceTypes==="array")&&d(p);n.else(),Zd(e),n.endIf(),n.if((0,Z._)`${c} !== undefined`,()=>{n.assign(a,c),bA(e,c)});function d(p){switch(p){case"string":n.elseIf((0,Z._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,Z._)`"" + ${a}`).elseIf((0,Z._)`${a} === null`).assign(c,(0,Z._)`""`);return;case"number":n.elseIf((0,Z._)`${s} == "boolean" || ${a} === null
27
27
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,Z._)`+${a}`);return;case"integer":n.elseIf((0,Z._)`${s} === "boolean" || ${a} === null
28
28
  || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,Z._)`+${a}`);return;case"boolean":n.elseIf((0,Z._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,Z._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case"null":n.elseIf((0,Z._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(c,null);return;case"array":n.elseIf((0,Z._)`${s} === "string" || ${s} === "number"
29
- || ${s} === "boolean" || ${a} === null`).assign(c,(0,Z._)`[${a}]`)}}o(d,"coerceSpecificType")}o(ak,"coerceData");function ik({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,Z._)`${t} !== undefined`,()=>e.assign((0,Z._)`${t}[${r}]`,n))}o(ik,"assignParentData");function Gd(e,t,r,n=to.Correct){let a=n===to.Correct?Z.operators.EQ:Z.operators.NEQ,i;switch(e){case"null":return(0,Z._)`${t} ${a} null`;case"array":i=(0,Z._)`Array.isArray(${t})`;break;case"object":i=(0,Z._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,Z._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,Z._)`typeof ${t} ${a} ${e}`}return n===to.Correct?i:(0,Z.not)(i);function s(c=Z.nil){return(0,Z.and)((0,Z._)`typeof ${t} == "number"`,c,r?(0,Z._)`isFinite(${t})`:Z.nil)}}o(Gd,"checkDataType");Ve.checkDataType=Gd;function Vd(e,t,r,n){if(e.length===1)return Gd(e[0],t,r,n);let a,i=(0,iy.toHash)(e);if(i.array&&i.object){let s=(0,Z._)`typeof ${t} != "object"`;a=i.null?s:(0,Z._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else a=Z.nil;i.number&&delete i.integer;for(let s in i)a=(0,Z.and)(a,Gd(s,t,r,n));return a}o(Vd,"checkDataTypes");Ve.checkDataTypes=Vd;var sk={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,Z._)`{type: ${e}}`:(0,Z._)`{type: ${t}}`,"params")};function Fd(e){let t=ck(e);(0,tk.reportError)(t,sk)}o(Fd,"reportTypeError");Ve.reportTypeError=Fd;function ck(e){let{gen:t,data:r,schema:n}=e,a=(0,iy.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o(ck,"getTypeErrorContext")});var dy=x(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.assignDefaults=void 0;var ro=J(),uk=ie();function dk(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)uy(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>uy(e,i,a.default))}o(dk,"assignDefaults");as.assignDefaults=dk;function uy(e,t,r){let{gen:n,compositeRule:a,data:i,opts:s}=e;if(r===void 0)return;let c=(0,ro._)`${i}${(0,ro.getProperty)(t)}`;if(a){(0,uk.checkStrictMode)(e,`default is ignored for: ${c}`);return}let d=(0,ro._)`${c} === undefined`;s.useDefaults==="empty"&&(d=(0,ro._)`${d} || ${c} === null || ${c} === ""`),n.if(d,(0,ro._)`${c} = ${(0,ro.stringify)(r)}`)}o(uy,"assignDefault")});var St=x(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.validateUnion=se.validateArray=se.usePattern=se.callValidateCode=se.schemaProperties=se.allSchemaProperties=se.noPropertyInData=se.propertyInData=se.isOwnProperty=se.hasPropFunc=se.reportMissingProp=se.checkMissingProp=se.checkReportMissingProp=void 0;var he=J(),Zd=ie(),Or=ir(),lk=ie();function pk(e,t){let{gen:r,data:n,it:a}=e;r.if(Jd(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,he._)`${t}`},!0),e.error()})}o(pk,"checkReportMissingProp");se.checkReportMissingProp=pk;function mk({gen:e,data:t,it:{opts:r}},n,a){return(0,he.or)(...n.map(i=>(0,he.and)(Jd(e,t,i,r.ownProperties),(0,he._)`${a} = ${i}`)))}o(mk,"checkMissingProp");se.checkMissingProp=mk;function fk(e,t){e.setParams({missingProperty:t},!0),e.error()}o(fk,"reportMissingProp");se.reportMissingProp=fk;function ly(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,he._)`Object.prototype.hasOwnProperty`})}o(ly,"hasPropFunc");se.hasPropFunc=ly;function Kd(e,t,r){return(0,he._)`${ly(e)}.call(${t}, ${r})`}o(Kd,"isOwnProperty");se.isOwnProperty=Kd;function hk(e,t,r,n){let a=(0,he._)`${t}${(0,he.getProperty)(r)} !== undefined`;return n?(0,he._)`${a} && ${Kd(e,t,r)}`:a}o(hk,"propertyInData");se.propertyInData=hk;function Jd(e,t,r,n){let a=(0,he._)`${t}${(0,he.getProperty)(r)} === undefined`;return n?(0,he.or)(a,(0,he.not)(Kd(e,t,r))):a}o(Jd,"noPropertyInData");se.noPropertyInData=Jd;function py(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o(py,"allSchemaProperties");se.allSchemaProperties=py;function gk(e,t){return py(t).filter(r=>!(0,Zd.alwaysValidSchema)(e,t[r]))}o(gk,"schemaProperties");se.schemaProperties=gk;function yk({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:s},c,d,p){let l=p?(0,he._)`${e}, ${t}, ${n}${a}`:t,m=[[Or.default.instancePath,(0,he.strConcat)(Or.default.instancePath,i)],[Or.default.parentData,s.parentData],[Or.default.parentDataProperty,s.parentDataProperty],[Or.default.rootData,Or.default.rootData]];s.opts.dynamicRef&&m.push([Or.default.dynamicAnchors,Or.default.dynamicAnchors]);let h=(0,he._)`${l}, ${r.object(...m)}`;return d!==he.nil?(0,he._)`${c}.call(${d}, ${h})`:(0,he._)`${c}(${h})`}o(yk,"callValidateCode");se.callValidateCode=yk;var Sk=(0,he._)`new RegExp`;function _k({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,he._)`${a.code==="new RegExp"?Sk:(0,lk.useFunc)(e,a)}(${r}, ${n})`})}o(_k,"usePattern");se.usePattern=_k;function vk(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,he._)`${r}.length`);t.forRange("i",0,d,p=>{e.subschema({keyword:n,dataProp:p,dataPropType:Zd.Type.Num},i),t.if((0,he.not)(i),c)})}o(s,"validateItems")}o(vk,"validateArray");se.validateArray=vk;function wk(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,Zd.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,he._)`${s} || ${c}`),e.mergeValidEvaluated(l,c)||t.if((0,he.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}o(wk,"validateUnion");se.validateUnion=wk});var hy=x(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.validateKeywordUsage=Nt.validSchemaType=Nt.funcKeywordCode=Nt.macroKeywordCode=void 0;var Ke=J(),pn=ir(),bk=St(),Rk=ya();function Ck(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:s}=e,c=t.macro.call(s.self,a,i,s),d=fy(r,n,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let p=r.name("valid");e.subschema({schema:c,schemaPath:Ke.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},p),e.pass(p,()=>e.error(!0))}o(Ck,"macroKeywordCode");Nt.macroKeywordCode=Ck;function Ik(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:s,$data:c,it:d}=e;xk(d,t);let p=!c&&t.compile?t.compile.call(d.self,i,s,d):t.validate,l=fy(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)y(),t.modifying&&my(e),_(()=>e.error());else{let v=t.async?g():S();t.modifying&&my(e),_(()=>Pk(e,v))}}o(h,"validateKeyword");function g(){let v=n.let("ruleErrs",null);return n.try(()=>y((0,Ke._)`await `),w=>n.assign(m,!1).if((0,Ke._)`${w} instanceof ${d.ValidationError}`,()=>n.assign(v,(0,Ke._)`${w}.errors`),()=>n.throw(w))),v}o(g,"validateAsync");function S(){let v=(0,Ke._)`${l}.errors`;return n.assign(v,null),y(Ke.nil),v}o(S,"validateSync");function y(v=t.async?(0,Ke._)`await `:Ke.nil){let w=d.opts.passContext?pn.default.this:pn.default.self,b=!("compile"in t&&!c||t.schema===!1);n.assign(m,(0,Ke._)`${v}${(0,bk.callValidateCode)(e,l,w,b)}`,t.modifying)}o(y,"assignValid");function _(v){var w;n.if((0,Ke.not)((w=t.valid)!==null&&w!==void 0?w:m),v)}o(_,"reportErrs")}o(Ik,"funcKeywordCode");Nt.funcKeywordCode=Ik;function my(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ke._)`${n.parentData}[${n.parentDataProperty}]`))}o(my,"modifyData");function Pk(e,t){let{gen:r}=e;r.if((0,Ke._)`Array.isArray(${t})`,()=>{r.assign(pn.default.vErrors,(0,Ke._)`${pn.default.vErrors} === null ? ${t} : ${pn.default.vErrors}.concat(${t})`).assign(pn.default.errors,(0,Ke._)`${pn.default.vErrors}.length`),(0,Rk.extendErrors)(e)},()=>e.error())}o(Pk,"addErrs");function xk({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o(xk,"checkAsyncKeyword");function fy(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,Ke.stringify)(r)})}o(fy,"useKeyword");function Ak(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(Ak,"validSchemaType");Nt.validSchemaType=Ak;function kk({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(kk,"validateKeywordUsage");Nt.validateKeywordUsage=kk});var yy=x(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.extendSubschemaMode=Mr.extendSubschemaData=Mr.getSubschema=void 0;var Dt=J(),gy=ie();function Tk(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,Dt._)`${e.schemaPath}${(0,Dt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,Dt._)`${e.schemaPath}${(0,Dt.getProperty)(t)}${(0,Dt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,gy.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(Tk,"getSubschema");Mr.getSubschema=Tk;function Ek(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,Dt._)`${t.data}${(0,Dt.getProperty)(r)}`,!0);d(h),e.errorPath=(0,Dt.str)`${p}${(0,gy.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,Dt._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let p=a instanceof Dt.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(Ek,"extendSubschemaData");Mr.extendSubschemaData=Ek;function Uk(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(Uk,"extendSubschemaMode");Mr.extendSubschemaMode=Uk});var Wd=x((G9,Sy)=>{"use strict";Sy.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 vy=x((F9,_y)=>{"use strict";var zr=_y.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(){};is(t,n,a,e,"",e)};zr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};zr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};zr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};zr.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 is(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 zr.arrayKeywords)for(var h=0;h<m.length;h++)is(e,t,r,m[h],a+"/"+l+"/"+h,i,a,l,n,h)}else if(l in zr.propsKeywords){if(m&&typeof m=="object")for(var g in m)is(e,t,r,m[g],a+"/"+l+"/"+Ok(g),i,a,l,n,g)}else(l in zr.keywords||e.allKeys&&!(l in zr.skipKeywords))&&is(e,t,r,m,a+"/"+l,i,a,l,n)}r(n,a,i,s,c,d,p)}}o(is,"_traverse");function Ok(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(Ok,"escapeJsonPtr")});var _a=x(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getSchemaRefs=rt.resolveUrl=rt.normalizeId=rt._getFullPath=rt.getFullPath=rt.inlineRef=void 0;var Mk=ie(),zk=Wd(),$k=vy(),qk=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Nk(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Yd(e):t?wy(e)<=t:!1}o(Nk,"inlineRef");rt.inlineRef=Nk;var Dk=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Yd(e){for(let t in e){if(Dk.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Yd)||typeof r=="object"&&Yd(r))return!0}return!1}o(Yd,"hasRef");function wy(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!qk.has(r)&&(typeof e[r]=="object"&&(0,Mk.eachItem)(e[r],n=>t+=wy(n)),t===1/0))return 1/0}return t}o(wy,"countKeys");function by(e,t="",r){r!==!1&&(t=no(t));let n=e.parse(t);return Ry(e,n)}o(by,"getFullPath");rt.getFullPath=by;function Ry(e,t){return e.serialize(t).split("#")[0]+"#"}o(Ry,"_getFullPath");rt._getFullPath=Ry;var jk=/#\/?$/;function no(e){return e?e.replace(jk,""):""}o(no,"normalizeId");rt.normalizeId=no;function Hk(e,t,r){return r=no(r),e.resolve(t,r)}o(Hk,"resolveUrl");rt.resolveUrl=Hk;var Lk=/^[a-z_][-a-z0-9._]*$/i;function Bk(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=no(e[r]||t),i={"":a},s=by(n,a,!1),c={},d=new Set;return $k(e,{allKeys:!0},(m,h,g,S)=>{if(S===void 0)return;let y=s+h,_=i[S];typeof m[r]=="string"&&(_=v.call(this,m[r])),w.call(this,m.$anchor),w.call(this,m.$dynamicAnchor),i[h]=_;function v(b){let N=this.opts.uriResolver.resolve;if(b=no(_?N(_,b):b),d.has(b))throw l(b);d.add(b);let j=this.refs[b];return typeof j=="string"&&(j=this.refs[j]),typeof j=="object"?p(m,j.schema,b):b!==no(y)&&(b[0]==="#"?(p(m,c[b],b),c[b]=m):this.refs[b]=y),b}o(v,"addRef");function w(b){if(typeof b=="string"){if(!Lk.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}o(w,"addAnchor")}),c;function p(m,h,g){if(h!==void 0&&!zk(m,h))throw l(g)}o(p,"checkAmbiguosRef");function l(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(l,"ambiguos")}o(Bk,"getSchemaRefs");rt.getSchemaRefs=Bk});var ba=x($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.getData=$r.KeywordCxt=$r.validateFunctionCode=void 0;var Ay=ny(),Cy=Sa(),Qd=Bd(),ss=Sa(),Gk=dy(),wa=hy(),Xd=yy(),M=J(),G=ir(),Vk=_a(),sr=ie(),va=ya();function Fk(e){if(Ey(e)&&(Uy(e),Ty(e))){Jk(e);return}ky(e,()=>(0,Ay.topBoolOrEmptySchema)(e))}o(Fk,"validateFunctionCode");$r.validateFunctionCode=Fk;function ky({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,M._)`${G.default.data}, ${G.default.valCxt}`,n.$async,()=>{e.code((0,M._)`"use strict"; ${Iy(r,a)}`),Kk(e,a),e.code(i)}):e.func(t,(0,M._)`${G.default.data}, ${Zk(a)}`,n.$async,()=>e.code(Iy(r,a)).code(i))}o(ky,"validateFunction");function Zk(e){return(0,M._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${e.dynamicRef?(0,M._)`, ${G.default.dynamicAnchors}={}`:M.nil}}={}`}o(Zk,"destructureValCxt");function Kk(e,t){e.if(G.default.valCxt,()=>{e.var(G.default.instancePath,(0,M._)`${G.default.valCxt}.${G.default.instancePath}`),e.var(G.default.parentData,(0,M._)`${G.default.valCxt}.${G.default.parentData}`),e.var(G.default.parentDataProperty,(0,M._)`${G.default.valCxt}.${G.default.parentDataProperty}`),e.var(G.default.rootData,(0,M._)`${G.default.valCxt}.${G.default.rootData}`),t.dynamicRef&&e.var(G.default.dynamicAnchors,(0,M._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{e.var(G.default.instancePath,(0,M._)`""`),e.var(G.default.parentData,(0,M._)`undefined`),e.var(G.default.parentDataProperty,(0,M._)`undefined`),e.var(G.default.rootData,G.default.data),t.dynamicRef&&e.var(G.default.dynamicAnchors,(0,M._)`{}`)})}o(Kk,"destructureValCxtES5");function Jk(e){let{schema:t,opts:r,gen:n}=e;ky(e,()=>{r.$comment&&t.$comment&&My(e),eT(e),n.let(G.default.vErrors,null),n.let(G.default.errors,0),r.unevaluated&&Wk(e),Oy(e),nT(e)})}o(Jk,"topSchemaObjCode");function Wk(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,M._)`${r}.evaluated`),t.if((0,M._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,M._)`${e.evaluated}.props`,(0,M._)`undefined`)),t.if((0,M._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,M._)`${e.evaluated}.items`,(0,M._)`undefined`))}o(Wk,"resetEvaluated");function Iy(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,M._)`/*# sourceURL=${r} */`:M.nil}o(Iy,"funcSourceUrl");function Yk(e,t){if(Ey(e)&&(Uy(e),Ty(e))){Xk(e,t);return}(0,Ay.boolOrEmptySchema)(e,t)}o(Yk,"subschemaCode");function Ty({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(Ty,"schemaCxtHasRules");function Ey(e){return typeof e.schema!="boolean"}o(Ey,"isSchemaObj");function Xk(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&My(e),tT(e),rT(e);let i=n.const("_errs",G.default.errors);Oy(e,i),n.var(t,(0,M._)`${i} === ${G.default.errors}`)}o(Xk,"subSchemaObjCode");function Uy(e){(0,sr.checkUnknownRules)(e),Qk(e)}o(Uy,"checkKeywords");function Oy(e,t){if(e.opts.jtd)return Py(e,[],!1,t);let r=(0,Cy.getSchemaTypes)(e.schema),n=(0,Cy.coerceAndCheckDataType)(e,r);Py(e,r,!n,t)}o(Oy,"typeAndKeywords");function Qk(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,sr.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(Qk,"checkRefsAndKeywords");function eT(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,sr.checkStrictMode)(e,"default is ignored in the schema root")}o(eT,"checkNoDefault");function tT(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Vk.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o(tT,"updateContext");function rT(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(rT,"checkAsyncSchema");function My({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,M._)`${G.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let s=(0,M.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,M._)`${G.default.self}.opts.$comment(${i}, ${s}, ${c}.schema)`)}}o(My,"commentKeyword");function nT(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,M._)`${G.default.errors} === 0`,()=>t.return(G.default.data),()=>t.throw((0,M._)`new ${a}(${G.default.vErrors})`)):(t.assign((0,M._)`${n}.errors`,G.default.vErrors),i.unevaluated&&oT(e),t.return((0,M._)`${G.default.errors} === 0`))}o(nT,"returnResults");function oT({gen:e,evaluated:t,props:r,items:n}){r instanceof M.Name&&e.assign((0,M._)`${t}.props`,r),n instanceof M.Name&&e.assign((0,M._)`${t}.items`,n)}o(oT,"assignEvaluated");function Py(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,sr.schemaHasRulesButRef)(i,l))){a.block(()=>$y(e,"$ref",l.all.$ref.definition));return}d.jtd||aT(e,t),a.block(()=>{for(let h of l.rules)m(h);m(l.post)});function m(h){(0,Qd.shouldUseGroup)(i,h)&&(h.type?(a.if((0,ss.checkDataType)(h.type,s,d.strictNumbers)),xy(e,h),t.length===1&&t[0]===h.type&&r&&(a.else(),(0,ss.reportTypeError)(e)),a.endIf()):xy(e,h),c||a.if((0,M._)`${G.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(Py,"schemaKeywords");function xy(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,Gk.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Qd.shouldUseRule)(n,i)&&$y(e,i.keyword,i.definition,t.type)})}o(xy,"iterateKeywords");function aT(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(iT(e,t),e.opts.allowUnionTypes||sT(e,t),cT(e,e.dataTypes))}o(aT,"checkStrictTypes");function iT(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{zy(e.dataTypes,r)||el(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),dT(e,t)}}o(iT,"checkContextTypes");function sT(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&el(e,"use allowUnionTypes to allow union type keyword")}o(sT,"checkMultipleTypes");function cT(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,Qd.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(s=>uT(t,s))&&el(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}o(cT,"checkKeywordTypes");function uT(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(uT,"hasApplicableType");function zy(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(zy,"includesType");function dT(e,t){let r=[];for(let n of e.dataTypes)zy(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(dT,"narrowSchemaTypes");function el(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,sr.checkStrictMode)(e,t,e.opts.strictTypes)}o(el,"strictTypesError");var cs=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,wa.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,sr.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",qy(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,wa.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",G.default.errors))}result(t,r,n){this.failResult((0,M.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,M.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,M._)`${r} !== undefined && (${(0,M.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?va.reportExtraError:va.reportError)(this,this.def.error,r)}$dataError(){(0,va.reportError)(this,this.def.$dataError||va.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,va.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=M.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=M.nil,r=M.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:s}=this;n.if((0,M.or)((0,M._)`${a} === undefined`,r)),t!==M.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==M.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,M.or)(s(),c());function s(){if(n.length){if(!(r instanceof M.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,M._)`${(0,ss.checkDataTypes)(d,r,i.opts.strictNumbers,ss.DataType.Wrong)}`}return M.nil}function c(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,M._)`!${d}(${r})`}return M.nil}}subschema(t,r){let n=(0,Xd.getSubschema)(this.it,t);(0,Xd.extendSubschemaData)(n,this.it,t),(0,Xd.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return Yk(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=sr.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=sr.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,M.Name)),!0}};$r.KeywordCxt=cs;function $y(e,t,r,n){let a=new cs(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,wa.funcKeywordCode)(a,r):"macro"in r?(0,wa.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,wa.funcKeywordCode)(a,r)}o($y,"keywordCode");var lT=/^\/(?:[^~]|~0|~1)*$/,pT=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function qy(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return G.default.rootData;if(e[0]==="/"){if(!lT.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=G.default.rootData}else{let p=pT.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,M._)`${i}${(0,M.getProperty)((0,sr.unescapeJsonPointer)(p))}`,s=(0,M._)`${s} && ${i}`);return s;function d(p,l){return`Cannot access ${p} ${l} levels up, current level is ${t}`}}o(qy,"getData");$r.getData=qy});var us=x(rl=>{"use strict";Object.defineProperty(rl,"__esModule",{value:!0});var tl=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};rl.default=tl});var Ra=x(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var nl=_a(),ol=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,nl.resolveUrl)(t,r,n),this.missingSchema=(0,nl.normalizeId)((0,nl.getFullPath)(t,this.missingRef))}};al.default=ol});var ls=x(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.resolveSchema=_t.getCompilingSchema=_t.resolveRef=_t.compileSchema=_t.SchemaEnv=void 0;var At=J(),mT=us(),mn=ir(),kt=_a(),Ny=ie(),fT=ba(),oo=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,kt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};_t.SchemaEnv=oo;function sl(e){let t=Dy.call(this,e);if(t)return t;let r=(0,kt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,s=new At.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),c;e.$async&&(c=s.scopeValue("Error",{ref:mT.default,code:(0,At._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");e.validateName=d;let p={gen:s,allErrors:this.opts.allErrors,data:mn.default.data,parentData:mn.default.parentData,parentDataProperty:mn.default.parentDataProperty,dataNames:[mn.default.data],dataPathArr:[At.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,At.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:At.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,At._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,fT.validateFunctionCode)(p),s.optimize(this.opts.code.optimize);let m=s.toString();l=`${s.scopeRefs(mn.default.scope)}return ${m}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let g=new Function(`${mn.default.self}`,`${mn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{ref:g}),g.errors=null,g.schema=e.schema,g.schemaEnv=e,e.$async&&(g.$async=!0),this.opts.code.source===!0&&(g.source={validateName:d,validateCode:m,scopeValues:s._values}),this.opts.unevaluated){let{props:S,items:y}=p;g.evaluated={props:S instanceof At.Name?void 0:S,items:y instanceof At.Name?void 0:y,dynamicProps:S instanceof At.Name,dynamicItems:y instanceof At.Name},g.source&&(g.source.evaluated=(0,At.stringify)(g.evaluated))}return e.validate=g,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(sl,"compileSchema");_t.compileSchema=sl;function hT(e,t,r){var n;r=(0,kt.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=ST.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 oo({schema:s,schemaId:c,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=gT.call(this,i)}o(hT,"resolveRef");_t.resolveRef=hT;function gT(e){return(0,kt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:sl.call(this,e)}o(gT,"inlineOrCompile");function Dy(e){for(let t of this._compilations)if(yT(t,e))return t}o(Dy,"getCompilingSchema");_t.getCompilingSchema=Dy;function yT(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(yT,"sameSchemaEnv");function ST(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||ds.call(this,e,t)}o(ST,"resolve");function ds(e,t){let r=this.opts.uriResolver.parse(t),n=(0,kt._getFullPath)(this.opts.uriResolver,r),a=(0,kt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return il.call(this,r,e);let i=(0,kt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let c=ds.call(this,e,s);return typeof c?.schema!="object"?void 0:il.call(this,r,c)}if(typeof s?.schema=="object"){if(s.validate||sl.call(this,s),i===(0,kt.normalizeId)(t)){let{schema:c}=s,{schemaId:d}=this.opts,p=c[d];return p&&(a=(0,kt.resolveUrl)(this.opts.uriResolver,a,p)),new oo({schema:c,schemaId:d,root:e,baseId:a})}return il.call(this,r,s)}}o(ds,"resolveSchema");_t.resolveSchema=ds;var _T=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function il(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,Ny.unescapeFragment)(c)];if(d===void 0)return;r=d;let p=typeof r=="object"&&r[this.opts.schemaId];!_T.has(c)&&p&&(t=(0,kt.resolveUrl)(this.opts.uriResolver,t,p))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Ny.schemaHasRulesButRef)(r,this.RULES)){let c=(0,kt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=ds.call(this,n,c)}let{schemaId:s}=this.opts;if(i=i||new oo({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}o(il,"getJsonPointer")});var jy=x((oF,vT)=>{vT.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 ul=x((aF,Gy)=>{"use strict";var wT=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ly=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 cl(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(cl,"stringArrayToHexStripped");var bT=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Hy(e){return e.length=0,!0}o(Hy,"consumeIsZone");function RT(e,t,r){if(e.length){let n=cl(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(RT,"consumeHextets");function CT(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,s=!1,c=RT;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=Hy}else{a.push(p);continue}}return a.length&&(c===Hy?r.zone=a.join(""):s?n.push(a.join("")):n.push(cl(a))),r.address=n.join(""),r}o(CT,"getIPV6");function By(e){if(IT(e,":")<2)return{host:e,isIPV6:!1};let t=CT(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 IT(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(IT,"findToken");function PT(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(PT,"removeDotSegments");function xT(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(xT,"normalizeComponentEncoding");function AT(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Ly(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(AT,"recomposeAuthority");Gy.exports={nonSimpleDomain:bT,recomposeAuthority:AT,normalizeComponentEncoding:xT,removeDotSegments:PT,isIPv4:Ly,isUUID:wT,normalizeIPv6:By,stringArrayToHexStripped:cl}});var Jy=x((sF,Ky)=>{"use strict";var{isUUID:kT}=ul(),TT=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ET=["http","https","ws","wss","urn","urn:uuid"];function UT(e){return ET.indexOf(e)!==-1}o(UT,"isValidSchemeName");function dl(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(dl,"wsIsSecure");function Vy(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(Vy,"httpParse");function Fy(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(Fy,"httpSerialize");function OT(e){return e.secure=dl(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(OT,"wsParse");function MT(e){if((e.port===(dl(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(MT,"wsSerialize");function zT(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(TT);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=ll(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(zT,"urnParse");function $T(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=ll(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($T,"urnSerialize");function qT(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!kT(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}o(qT,"urnuuidParse");function NT(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(NT,"urnuuidSerialize");var Zy={scheme:"http",domainHost:!0,parse:Vy,serialize:Fy},DT={scheme:"https",domainHost:Zy.domainHost,parse:Vy,serialize:Fy},ps={scheme:"ws",domainHost:!0,parse:OT,serialize:MT},jT={scheme:"wss",domainHost:ps.domainHost,parse:ps.parse,serialize:ps.serialize},HT={scheme:"urn",parse:zT,serialize:$T,skipNormalize:!0},LT={scheme:"urn:uuid",parse:qT,serialize:NT,skipNormalize:!0},ms={http:Zy,https:DT,ws:ps,wss:jT,urn:HT,"urn:uuid":LT};Object.setPrototypeOf(ms,null);function ll(e){return e&&(ms[e]||ms[e.toLowerCase()])||void 0}o(ll,"getSchemeHandler");Ky.exports={wsIsSecure:dl,SCHEMES:ms,isValidSchemeName:UT,getSchemeHandler:ll}});var Xy=x((uF,hs)=>{"use strict";var{normalizeIPv6:BT,removeDotSegments:Ca,recomposeAuthority:GT,normalizeComponentEncoding:fs,isIPv4:VT,nonSimpleDomain:FT}=ul(),{SCHEMES:ZT,getSchemeHandler:Wy}=Jy();function KT(e,t){return typeof e=="string"?e=jt(cr(e,t),t):typeof e=="object"&&(e=cr(jt(e,t),t)),e}o(KT,"normalize");function JT(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=Yy(cr(e,n),cr(t,n),n,!0);return n.skipEscape=!0,jt(a,n)}o(JT,"resolve");function Yy(e,t,r,n){let a={};return n||(e=cr(jt(e,r),r),t=cr(jt(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=Ca(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=Ca(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=Ca(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=Ca(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(Yy,"resolveComponent");function WT(e,t,r){return typeof e=="string"?(e=unescape(e),e=jt(fs(cr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=jt(fs(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=jt(fs(cr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=jt(fs(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(WT,"equal");function jt(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=Wy(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=GT(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=Ca(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(jt,"serialize");var YT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function cr(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(YT);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(VT(n.host)===!1){let d=BT(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=Wy(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&a===!1&&FT(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(cr,"parse");var pl={SCHEMES:ZT,normalize:KT,resolve:JT,resolveComponent:Yy,equal:WT,serialize:jt,parse:cr};hs.exports=pl;hs.exports.default=pl;hs.exports.fastUri=pl});var eS=x(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});var Qy=Xy();Qy.code='require("ajv/dist/runtime/uri").default';ml.default=Qy});var cS=x(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.CodeGen=Ne.Name=Ne.nil=Ne.stringify=Ne.str=Ne._=Ne.KeywordCxt=void 0;var XT=ba();Object.defineProperty(Ne,"KeywordCxt",{enumerable:!0,get:o(function(){return XT.KeywordCxt},"get")});var ao=J();Object.defineProperty(Ne,"_",{enumerable:!0,get:o(function(){return ao._},"get")});Object.defineProperty(Ne,"str",{enumerable:!0,get:o(function(){return ao.str},"get")});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:o(function(){return ao.stringify},"get")});Object.defineProperty(Ne,"nil",{enumerable:!0,get:o(function(){return ao.nil},"get")});Object.defineProperty(Ne,"Name",{enumerable:!0,get:o(function(){return ao.Name},"get")});Object.defineProperty(Ne,"CodeGen",{enumerable:!0,get:o(function(){return ao.CodeGen},"get")});var QT=us(),aS=Ra(),e0=Ld(),Ia=ls(),t0=J(),Pa=_a(),gs=Sa(),hl=ie(),tS=jy(),r0=eS(),iS=o((e,t)=>new RegExp(e,t),"defaultRegExp");iS.code="new RegExp";var n0=["removeAdditional","useDefaults","coerceTypes"],o0=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),a0={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."},i0={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},rS=200;function s0(e){var t,r,n,a,i,s,c,d,p,l,m,h,g,S,y,_,v,w,b,N,j,He,lt,An,fr;let Ft=e.strict,Gr=(t=e.code)===null||t===void 0?void 0:t.optimize,wo=Gr===!0||Gr===void 0?1:Gr||0,bo=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:iS,Ro=(a=e.uriResolver)!==null&&a!==void 0?a:r0.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Ft)!==null&&s!==void 0?s:!0,strictNumbers:(d=(c=e.strictNumbers)!==null&&c!==void 0?c:Ft)!==null&&d!==void 0?d:!0,strictTypes:(l=(p=e.strictTypes)!==null&&p!==void 0?p:Ft)!==null&&l!==void 0?l:"log",strictTuples:(h=(m=e.strictTuples)!==null&&m!==void 0?m:Ft)!==null&&h!==void 0?h:"log",strictRequired:(S=(g=e.strictRequired)!==null&&g!==void 0?g:Ft)!==null&&S!==void 0?S:!1,code:e.code?{...e.code,optimize:wo,regExp:bo}:{optimize:wo,regExp:bo},loopRequired:(y=e.loopRequired)!==null&&y!==void 0?y:rS,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:rS,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(w=e.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(N=e.schemaId)!==null&&N!==void 0?N:"$id",addUsedSchema:(j=e.addUsedSchema)!==null&&j!==void 0?j:!0,validateSchema:(He=e.validateSchema)!==null&&He!==void 0?He:!0,validateFormats:(lt=e.validateFormats)!==null&&lt!==void 0?lt:!0,unicodeRegExp:(An=e.unicodeRegExp)!==null&&An!==void 0?An:!0,int32range:(fr=e.int32range)!==null&&fr!==void 0?fr:!0,uriResolver:Ro}}o(s0,"requiredOptions");var xa=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,...s0(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new t0.ValueScope({scope:{},prefixes:o0,es5:r,lines:n}),this.logger=m0(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,e0.getRules)(),nS.call(this,a0,t,"NOT SUPPORTED"),nS.call(this,i0,t,"DEPRECATED","warn"),this._metaOpts=l0.call(this),t.formats&&u0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&d0.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),c0.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=tS;n==="id"&&(a={...tS},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 aS.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,Pa.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=oS.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new Ia.SchemaEnv({schema:{},schemaId:n});if(r=Ia.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=oS.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,Pa.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(h0.call(this,n,r),!r)return(0,hl.eachItem)(n,i=>fl.call(this,i)),this;y0.call(this,r);let a={...r,type:(0,gs.getJSONTypes)(r.type),schemaType:(0,gs.getJSONTypes)(r.schemaType)};return(0,hl.eachItem)(n,a.type.length===0?i=>fl.call(this,i,a):i=>a.type.forEach(s=>fl.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]=sS(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,Pa.normalizeId)(s||n);let p=Pa.getSchemaRefs.call(this,t,n);return d=new Ia.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):Ia.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{Ia.compileSchema.call(this,t)}finally{this.opts=r}}};xa.ValidationError=QT.default;xa.MissingRefError=aS.default;Ne.default=xa;function nS(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(nS,"checkOptions");function oS(e){return e=(0,Pa.normalizeId)(e),this.schemas[e]||this.refs[e]}o(oS,"getSchEnv");function c0(){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(c0,"addInitialSchemas");function u0(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(u0,"addInitialFormats");function d0(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(d0,"addInitialKeywords");function l0(){let e={...this.opts};for(let t of n0)delete e[t];return e}o(l0,"getMetaSchemaOptions");var p0={log(){},warn(){},error(){}};function m0(e){if(e===!1)return p0;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(m0,"getLogger");var f0=/^[a-z_$][a-z0-9_$:-]*$/i;function h0(e,t){let{RULES:r}=this;if((0,hl.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!f0.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(h0,"checkKeyword");function fl(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,gs.getJSONTypes)(t.type),schemaType:(0,gs.getJSONTypes)(t.schemaType)}};t.before?g0.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(fl,"addRule");function g0(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(g0,"addBeforeRule");function y0(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=sS(t)),e.validateSchema=this.compile(t,!0))}o(y0,"keywordMetaschema");var S0={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function sS(e){return{anyOf:[e,S0]}}o(sS,"schemaOrData")});var uS=x(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});var _0={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};gl.default=_0});var mS=x(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.callRef=fn.getValidate=void 0;var v0=Ra(),dS=St(),nt=J(),io=ir(),lS=ls(),ys=ie(),w0={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=lS.resolveRef.call(d,p,a,r);if(l===void 0)throw new v0.default(n.opts.uriResolver,a,r);if(l instanceof lS.SchemaEnv)return h(l);return g(l);function m(){if(i===p)return Ss(e,s,i,i.$async);let S=t.scopeValue("root",{ref:p});return Ss(e,(0,nt._)`${S}.validate`,p,p.$async)}function h(S){let y=pS(e,S);Ss(e,y,S,S.$async)}function g(S){let y=t.scopeValue("schema",c.code.source===!0?{ref:S,code:(0,nt.stringify)(S)}:{ref:S}),_=t.name("valid"),v=e.subschema({schema:S,dataTypes:[],schemaPath:nt.nil,topSchemaRef:y,errSchemaPath:r},_);e.mergeEvaluated(v),e.ok(_)}}};function pS(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,nt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(pS,"getValidate");fn.getValidate=pS;function Ss(e,t,r,n){let{gen:a,it:i}=e,{allErrors:s,schemaEnv:c,opts:d}=i,p=d.passContext?io.default.this:nt.nil;n?l():m();function l(){if(!c.$async)throw new Error("async schema referenced by sync schema");let S=a.let("valid");a.try(()=>{a.code((0,nt._)`await ${(0,dS.callValidateCode)(e,t,p)}`),g(t),s||a.assign(S,!0)},y=>{a.if((0,nt._)`!(${y} instanceof ${i.ValidationError})`,()=>a.throw(y)),h(y),s||a.assign(S,!1)}),e.ok(S)}o(l,"callAsyncRef");function m(){e.result((0,dS.callValidateCode)(e,t,p),()=>g(t),()=>h(t))}o(m,"callSyncRef");function h(S){let y=(0,nt._)`${S}.errors`;a.assign(io.default.vErrors,(0,nt._)`${io.default.vErrors} === null ? ${y} : ${io.default.vErrors}.concat(${y})`),a.assign(io.default.errors,(0,nt._)`${io.default.vErrors}.length`)}o(h,"addErrorsFrom");function g(S){var y;if(!i.opts.unevaluated)return;let _=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=ys.mergeEvaluated.props(a,_.props,i.props));else{let v=a.var("props",(0,nt._)`${S}.evaluated.props`);i.props=ys.mergeEvaluated.props(a,v,i.props,nt.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=ys.mergeEvaluated.items(a,_.items,i.items));else{let v=a.var("items",(0,nt._)`${S}.evaluated.items`);i.items=ys.mergeEvaluated.items(a,v,i.items,nt.Name)}}o(g,"addEvaluatedFrom")}o(Ss,"callRef");fn.callRef=Ss;fn.default=w0});var fS=x(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var b0=uS(),R0=mS(),C0=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",b0.default,R0.default];yl.default=C0});var hS=x(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var _s=J(),qr=_s.operators,vs={maximum:{okStr:"<=",ok:qr.LTE,fail:qr.GT},minimum:{okStr:">=",ok:qr.GTE,fail:qr.LT},exclusiveMaximum:{okStr:"<",ok:qr.LT,fail:qr.GTE},exclusiveMinimum:{okStr:">",ok:qr.GT,fail:qr.LTE}},I0={message:o(({keyword:e,schemaCode:t})=>(0,_s.str)`must be ${vs[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,_s._)`{comparison: ${vs[e].okStr}, limit: ${t}}`,"params")},P0={keyword:Object.keys(vs),type:"number",schemaType:"number",$data:!0,error:I0,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,_s._)`${r} ${vs[t].fail} ${n} || isNaN(${r})`)}};Sl.default=P0});var gS=x(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});var Aa=J(),x0={message:o(({schemaCode:e})=>(0,Aa.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,Aa._)`{multipleOf: ${e}}`,"params")},A0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:x0,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,s=t.let("res"),c=i?(0,Aa._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Aa._)`${s} !== parseInt(${s})`;e.fail$data((0,Aa._)`(${n} === 0 || (${s} = ${r}/${n}, ${c}))`)}};_l.default=A0});var SS=x(vl=>{"use strict";Object.defineProperty(vl,"__esModule",{value:!0});function yS(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(yS,"ucs2length");vl.default=yS;yS.code='require("ajv/dist/runtime/ucs2length").default'});var _S=x(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});var hn=J(),k0=ie(),T0=SS(),E0={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,hn.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,hn._)`{limit: ${e}}`,"params")},U0={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:E0,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?hn.operators.GT:hn.operators.LT,s=a.opts.unicode===!1?(0,hn._)`${r}.length`:(0,hn._)`${(0,k0.useFunc)(e.gen,T0.default)}(${r})`;e.fail$data((0,hn._)`${s} ${i} ${n}`)}};wl.default=U0});var vS=x(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var O0=St(),ws=J(),M0={message:o(({schemaCode:e})=>(0,ws.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,ws._)`{pattern: ${e}}`,"params")},z0={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:M0,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:i}=e,s=i.opts.unicodeRegExp?"u":"",c=r?(0,ws._)`(new RegExp(${a}, ${s}))`:(0,O0.usePattern)(e,n);e.fail$data((0,ws._)`!${c}.test(${t})`)}};bl.default=z0});var wS=x(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});var ka=J(),$0={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,ka.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,ka._)`{limit: ${e}}`,"params")},q0={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:$0,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?ka.operators.GT:ka.operators.LT;e.fail$data((0,ka._)`Object.keys(${r}).length ${a} ${n}`)}};Rl.default=q0});var bS=x(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});var Ta=St(),Ea=J(),N0=ie(),D0={message:o(({params:{missingProperty:e}})=>(0,Ea.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,Ea._)`{missingProperty: ${e}}`,"params")},j0={keyword:"required",type:"object",schemaType:"array",$data:!0,error:D0,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 g=e.parentSchema.properties,{definedProperties:S}=e.it;for(let y of r)if(g?.[y]===void 0&&!S.has(y)){let _=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${y}" is not defined at "${_}" (strictRequired)`;(0,N0.checkStrictMode)(s,v,s.opts.strictRequired)}}function p(){if(d||i)e.block$data(Ea.nil,m);else for(let g of r)(0,Ta.checkReportMissingProp)(e,g)}o(p,"allErrorsMode");function l(){let g=t.let("missing");if(d||i){let S=t.let("valid",!0);e.block$data(S,()=>h(g,S)),e.ok(S)}else t.if((0,Ta.checkMissingProp)(e,r,g)),(0,Ta.reportMissingProp)(e,g),t.else()}o(l,"exitOnErrorMode");function m(){t.forOf("prop",n,g=>{e.setParams({missingProperty:g}),t.if((0,Ta.noPropertyInData)(t,a,g,c.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function h(g,S){e.setParams({missingProperty:g}),t.forOf(g,n,()=>{t.assign(S,(0,Ta.propertyInData)(t,a,g,c.ownProperties)),t.if((0,Ea.not)(S),()=>{e.error(),t.break()})},Ea.nil)}o(h,"loopUntilMissing")}};Cl.default=j0});var RS=x(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var Ua=J(),H0={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Ua.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,Ua._)`{limit: ${e}}`,"params")},L0={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:H0,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?Ua.operators.GT:Ua.operators.LT;e.fail$data((0,Ua._)`${r}.length ${a} ${n}`)}};Il.default=L0});var bs=x(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var CS=Wd();CS.code='require("ajv/dist/runtime/equal").default';Pl.default=CS});var IS=x(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var xl=Sa(),De=J(),B0=ie(),G0=bs(),V0={message:o(({params:{i:e,j:t}})=>(0,De.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,De._)`{i: ${e}, j: ${t}}`,"params")},F0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:V0,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,xl.getSchemaTypes)(i.items):[];e.block$data(d,l,(0,De._)`${s} === false`),e.ok(d);function l(){let S=t.let("i",(0,De._)`${r}.length`),y=t.let("j");e.setParams({i:S,j:y}),t.assign(d,!0),t.if((0,De._)`${S} > 1`,()=>(m()?h:g)(S,y))}o(l,"validateUniqueItems");function m(){return p.length>0&&!p.some(S=>S==="object"||S==="array")}o(m,"canOptimize");function h(S,y){let _=t.name("item"),v=(0,xl.checkDataTypes)(p,_,c.opts.strictNumbers,xl.DataType.Wrong),w=t.const("indices",(0,De._)`{}`);t.for((0,De._)`;${S}--;`,()=>{t.let(_,(0,De._)`${r}[${S}]`),t.if(v,(0,De._)`continue`),p.length>1&&t.if((0,De._)`typeof ${_} == "string"`,(0,De._)`${_} += "_"`),t.if((0,De._)`typeof ${w}[${_}] == "number"`,()=>{t.assign(y,(0,De._)`${w}[${_}]`),e.error(),t.assign(d,!1).break()}).code((0,De._)`${w}[${_}] = ${S}`)})}o(h,"loopN");function g(S,y){let _=(0,B0.useFunc)(t,G0.default),v=t.name("outer");t.label(v).for((0,De._)`;${S}--;`,()=>t.for((0,De._)`${y} = ${S}; ${y}--;`,()=>t.if((0,De._)`${_}(${r}[${S}], ${r}[${y}])`,()=>{e.error(),t.assign(d,!1).break(v)})))}o(g,"loopN2")}};Al.default=F0});var PS=x(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var kl=J(),Z0=ie(),K0=bs(),J0={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,kl._)`{allowedValue: ${e}}`,"params")},W0={keyword:"const",$data:!0,error:J0,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,kl._)`!${(0,Z0.useFunc)(t,K0.default)}(${r}, ${a})`):e.fail((0,kl._)`${i} !== ${r}`)}};Tl.default=W0});var xS=x(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});var Oa=J(),Y0=ie(),X0=bs(),Q0={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,Oa._)`{allowedValues: ${e}}`,"params")},eE={keyword:"enum",schemaType:"array",$data:!0,error:Q0,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,Y0.useFunc)(t,X0.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 g=t.const("vSchema",i);l=(0,Oa.or)(...a.map((S,y)=>h(g,y)))}e.pass(l);function m(){t.assign(l,!1),t.forOf("v",i,g=>t.if((0,Oa._)`${p()}(${r}, ${g})`,()=>t.assign(l,!0).break()))}o(m,"loopEnum");function h(g,S){let y=a[S];return typeof y=="object"&&y!==null?(0,Oa._)`${p()}(${r}, ${g}[${S}])`:(0,Oa._)`${r} === ${y}`}o(h,"equalCode")}};El.default=eE});var AS=x(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var tE=hS(),rE=gS(),nE=_S(),oE=vS(),aE=wS(),iE=bS(),sE=RS(),cE=IS(),uE=PS(),dE=xS(),lE=[tE.default,rE.default,nE.default,oE.default,aE.default,iE.default,sE.default,cE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},uE.default,dE.default];Ul.default=lE});var Ml=x(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.validateAdditionalItems=void 0;var gn=J(),Ol=ie(),pE={message:o(({params:{len:e}})=>(0,gn.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,gn._)`{limit: ${e}}`,"params")},mE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:pE,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Ol.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}kS(e,n)}};function kS(e,t){let{gen:r,schema:n,data:a,keyword:i,it:s}=e;s.items=!0;let c=r.const("len",(0,gn._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,gn._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,Ol.alwaysValidSchema)(s,n)){let p=r.var("valid",(0,gn._)`${c} <= ${t.length}`);r.if((0,gn.not)(p),()=>d(p)),e.ok(p)}function d(p){r.forRange("i",t.length,c,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:Ol.Type.Num},p),s.allErrors||r.if((0,gn.not)(p),()=>r.break())})}o(d,"validateItems")}o(kS,"validateAdditionalItems");Ma.validateAdditionalItems=kS;Ma.default=mE});var zl=x(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.validateTuple=void 0;var TS=J(),Rs=ie(),fE=St(),hE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return ES(e,"additionalItems",t);r.items=!0,!(0,Rs.alwaysValidSchema)(r,t)&&e.ok((0,fE.validateArray)(e))}};function ES(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=Rs.mergeEvaluated.items(n,r.length,c.items));let d=n.name("valid"),p=n.const("len",(0,TS._)`${i}.length`);r.forEach((m,h)=>{(0,Rs.alwaysValidSchema)(c,m)||(n.if((0,TS._)`${p} > ${h}`,()=>e.subschema({keyword:s,schemaProp:h,dataProp:h},d)),e.ok(d))});function l(m){let{opts:h,errSchemaPath:g}=c,S=r.length,y=S===m.minItems&&(S===m.maxItems||m[t]===!1);if(h.strictTuples&&!y){let _=`"${s}" is ${S}-tuple, but minItems or maxItems/${t} are not specified or different at path "${g}"`;(0,Rs.checkStrictMode)(c,_,h.strictTuples)}}o(l,"checkStrictTuple")}o(ES,"validateTuple");za.validateTuple=ES;za.default=hE});var US=x($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var gE=zl(),yE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,gE.validateTuple)(e,"items"),"code")};$l.default=yE});var MS=x(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var OS=J(),SE=ie(),_E=St(),vE=Ml(),wE={message:o(({params:{len:e}})=>(0,OS.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,OS._)`{limit: ${e}}`,"params")},bE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:wE,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,SE.alwaysValidSchema)(n,t)&&(a?(0,vE.validateAdditionalItems)(e,a):e.ok((0,_E.validateArray)(e)))}};ql.default=bE});var zS=x(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var vt=J(),Cs=ie(),RE={message:o(({params:{min:e,max:t}})=>t===void 0?(0,vt.str)`must contain at least ${e} valid item(s)`:(0,vt.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,vt._)`{minContains: ${e}}`:(0,vt._)`{minContains: ${e}, maxContains: ${t}}`,"params")},CE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:RE,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,vt._)`${a}.length`);if(e.setParams({min:s,max:c}),c===void 0&&s===0){(0,Cs.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&s>c){(0,Cs.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Cs.alwaysValidSchema)(i,r)){let y=(0,vt._)`${l} >= ${s}`;c!==void 0&&(y=(0,vt._)`${y} && ${l} <= ${c}`),e.pass(y);return}i.items=!0;let m=t.name("valid");c===void 0&&s===1?g(m,()=>t.if(m,()=>t.break())):s===0?(t.let(m,!0),c!==void 0&&t.if((0,vt._)`${a}.length > 0`,h)):(t.let(m,!1),h()),e.result(m,()=>e.reset());function h(){let y=t.name("_valid"),_=t.let("count",0);g(y,()=>t.if(y,()=>S(_)))}o(h,"validateItemsWithCount");function g(y,_){t.forRange("i",0,l,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:Cs.Type.Num,compositeRule:!0},y),_()})}o(g,"validateItems");function S(y){t.code((0,vt._)`${y}++`),c===void 0?t.if((0,vt._)`${y} >= ${s}`,()=>t.assign(m,!0).break()):(t.if((0,vt._)`${y} > ${c}`,()=>t.assign(m,!1).break()),s===1?t.assign(m,!0):t.if((0,vt._)`${y} >= ${s}`,()=>t.assign(m,!0)))}o(S,"checkLimits")}};Nl.default=CE});var NS=x(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.validateSchemaDeps=Ht.validatePropertyDeps=Ht.error=void 0;var Dl=J(),IE=ie(),$a=St();Ht.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Dl.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Dl._)`{property: ${e},
29
+ || ${s} === "boolean" || ${a} === null`).assign(c,(0,Z._)`[${a}]`)}}o(d,"coerceSpecificType")}o(wA,"coerceData");function bA({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,Z._)`${t} !== undefined`,()=>e.assign((0,Z._)`${t}[${r}]`,n))}o(bA,"assignParentData");function Vd(e,t,r,n=ao.Correct){let a=n===ao.Correct?Z.operators.EQ:Z.operators.NEQ,i;switch(e){case"null":return(0,Z._)`${t} ${a} null`;case"array":i=(0,Z._)`Array.isArray(${t})`;break;case"object":i=(0,Z._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,Z._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,Z._)`typeof ${t} ${a} ${e}`}return n===ao.Correct?i:(0,Z.not)(i);function s(c=Z.nil){return(0,Z.and)((0,Z._)`typeof ${t} == "number"`,c,r?(0,Z._)`isFinite(${t})`:Z.nil)}}o(Vd,"checkDataType");Ze.checkDataType=Vd;function Fd(e,t,r,n){if(e.length===1)return Vd(e[0],t,r,n);let a,i=(0,my.toHash)(e);if(i.array&&i.object){let s=(0,Z._)`typeof ${t} != "object"`;a=i.null?s:(0,Z._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else a=Z.nil;i.number&&delete i.integer;for(let s in i)a=(0,Z.and)(a,Vd(s,t,r,n));return a}o(Fd,"checkDataTypes");Ze.checkDataTypes=Fd;var RA={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,Z._)`{type: ${e}}`:(0,Z._)`{type: ${t}}`,"params")};function Zd(e){let t=CA(e);(0,yA.reportError)(t,RA)}o(Zd,"reportTypeError");Ze.reportTypeError=Zd;function CA(e){let{gen:t,data:r,schema:n}=e,a=(0,my.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o(CA,"getTypeErrorContext")});var yy=x(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.assignDefaults=void 0;var io=W(),IA=ie();function PA(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)gy(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>gy(e,i,a.default))}o(PA,"assignDefaults");ss.assignDefaults=PA;function gy(e,t,r){let{gen:n,compositeRule:a,data:i,opts:s}=e;if(r===void 0)return;let c=(0,io._)`${i}${(0,io.getProperty)(t)}`;if(a){(0,IA.checkStrictMode)(e,`default is ignored for: ${c}`);return}let d=(0,io._)`${c} === undefined`;s.useDefaults==="empty"&&(d=(0,io._)`${d} || ${c} === null || ${c} === ""`),n.if(d,(0,io._)`${c} = ${(0,io.stringify)(r)}`)}o(gy,"assignDefault")});var vt=x(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.validateUnion=ce.validateArray=ce.usePattern=ce.callValidateCode=ce.schemaProperties=ce.allSchemaProperties=ce.noPropertyInData=ce.propertyInData=ce.isOwnProperty=ce.hasPropFunc=ce.reportMissingProp=ce.checkMissingProp=ce.checkReportMissingProp=void 0;var he=W(),Kd=ie(),jr=pr(),xA=ie();function kA(e,t){let{gen:r,data:n,it:a}=e;r.if(Wd(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,he._)`${t}`},!0),e.error()})}o(kA,"checkReportMissingProp");ce.checkReportMissingProp=kA;function AA({gen:e,data:t,it:{opts:r}},n,a){return(0,he.or)(...n.map(i=>(0,he.and)(Wd(e,t,i,r.ownProperties),(0,he._)`${a} = ${i}`)))}o(AA,"checkMissingProp");ce.checkMissingProp=AA;function TA(e,t){e.setParams({missingProperty:t},!0),e.error()}o(TA,"reportMissingProp");ce.reportMissingProp=TA;function Sy(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,he._)`Object.prototype.hasOwnProperty`})}o(Sy,"hasPropFunc");ce.hasPropFunc=Sy;function Jd(e,t,r){return(0,he._)`${Sy(e)}.call(${t}, ${r})`}o(Jd,"isOwnProperty");ce.isOwnProperty=Jd;function EA(e,t,r,n){let a=(0,he._)`${t}${(0,he.getProperty)(r)} !== undefined`;return n?(0,he._)`${a} && ${Jd(e,t,r)}`:a}o(EA,"propertyInData");ce.propertyInData=EA;function Wd(e,t,r,n){let a=(0,he._)`${t}${(0,he.getProperty)(r)} === undefined`;return n?(0,he.or)(a,(0,he.not)(Jd(e,t,r))):a}o(Wd,"noPropertyInData");ce.noPropertyInData=Wd;function _y(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o(_y,"allSchemaProperties");ce.allSchemaProperties=_y;function UA(e,t){return _y(t).filter(r=>!(0,Kd.alwaysValidSchema)(e,t[r]))}o(UA,"schemaProperties");ce.schemaProperties=UA;function OA({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:s},c,d,p){let l=p?(0,he._)`${e}, ${t}, ${n}${a}`:t,m=[[jr.default.instancePath,(0,he.strConcat)(jr.default.instancePath,i)],[jr.default.parentData,s.parentData],[jr.default.parentDataProperty,s.parentDataProperty],[jr.default.rootData,jr.default.rootData]];s.opts.dynamicRef&&m.push([jr.default.dynamicAnchors,jr.default.dynamicAnchors]);let h=(0,he._)`${l}, ${r.object(...m)}`;return d!==he.nil?(0,he._)`${c}.call(${d}, ${h})`:(0,he._)`${c}(${h})`}o(OA,"callValidateCode");ce.callValidateCode=OA;var MA=(0,he._)`new RegExp`;function zA({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,he._)`${a.code==="new RegExp"?MA:(0,xA.useFunc)(e,a)}(${r}, ${n})`})}o(zA,"usePattern");ce.usePattern=zA;function $A(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,he._)`${r}.length`);t.forRange("i",0,d,p=>{e.subschema({keyword:n,dataProp:p,dataPropType:Kd.Type.Num},i),t.if((0,he.not)(i),c)})}o(s,"validateItems")}o($A,"validateArray");ce.validateArray=$A;function qA(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,Kd.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,he._)`${s} || ${c}`),e.mergeValidEvaluated(l,c)||t.if((0,he.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}o(qA,"validateUnion");ce.validateUnion=qA});var by=x(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.validateKeywordUsage=Bt.validSchemaType=Bt.funcKeywordCode=Bt.macroKeywordCode=void 0;var We=W(),Sn=pr(),NA=vt(),DA=wa();function jA(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:s}=e,c=t.macro.call(s.self,a,i,s),d=wy(r,n,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let p=r.name("valid");e.subschema({schema:c,schemaPath:We.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},p),e.pass(p,()=>e.error(!0))}o(jA,"macroKeywordCode");Bt.macroKeywordCode=jA;function HA(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:s,$data:c,it:d}=e;BA(d,t);let p=!c&&t.compile?t.compile.call(d.self,i,s,d):t.validate,l=wy(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)y(),t.modifying&&vy(e),_(()=>e.error());else{let v=t.async?g():S();t.modifying&&vy(e),_(()=>LA(e,v))}}o(h,"validateKeyword");function g(){let v=n.let("ruleErrs",null);return n.try(()=>y((0,We._)`await `),w=>n.assign(m,!1).if((0,We._)`${w} instanceof ${d.ValidationError}`,()=>n.assign(v,(0,We._)`${w}.errors`),()=>n.throw(w))),v}o(g,"validateAsync");function S(){let v=(0,We._)`${l}.errors`;return n.assign(v,null),y(We.nil),v}o(S,"validateSync");function y(v=t.async?(0,We._)`await `:We.nil){let w=d.opts.passContext?Sn.default.this:Sn.default.self,b=!("compile"in t&&!c||t.schema===!1);n.assign(m,(0,We._)`${v}${(0,NA.callValidateCode)(e,l,w,b)}`,t.modifying)}o(y,"assignValid");function _(v){var w;n.if((0,We.not)((w=t.valid)!==null&&w!==void 0?w:m),v)}o(_,"reportErrs")}o(HA,"funcKeywordCode");Bt.funcKeywordCode=HA;function vy(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}o(vy,"modifyData");function LA(e,t){let{gen:r}=e;r.if((0,We._)`Array.isArray(${t})`,()=>{r.assign(Sn.default.vErrors,(0,We._)`${Sn.default.vErrors} === null ? ${t} : ${Sn.default.vErrors}.concat(${t})`).assign(Sn.default.errors,(0,We._)`${Sn.default.vErrors}.length`),(0,DA.extendErrors)(e)},()=>e.error())}o(LA,"addErrs");function BA({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o(BA,"checkAsyncKeyword");function wy(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,We.stringify)(r)})}o(wy,"useKeyword");function GA(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(GA,"validSchemaType");Bt.validSchemaType=GA;function VA({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(VA,"validateKeywordUsage");Bt.validateKeywordUsage=VA});var Cy=x(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.extendSubschemaMode=Hr.extendSubschemaData=Hr.getSubschema=void 0;var Gt=W(),Ry=ie();function FA(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,Gt._)`${e.schemaPath}${(0,Gt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,Gt._)`${e.schemaPath}${(0,Gt.getProperty)(t)}${(0,Gt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Ry.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(FA,"getSubschema");Hr.getSubschema=FA;function ZA(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,Gt._)`${t.data}${(0,Gt.getProperty)(r)}`,!0);d(h),e.errorPath=(0,Gt.str)`${p}${(0,Ry.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,Gt._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let p=a instanceof Gt.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(ZA,"extendSubschemaData");Hr.extendSubschemaData=ZA;function KA(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(KA,"extendSubschemaMode");Hr.extendSubschemaMode=KA});var Yd=x((_F,Iy)=>{"use strict";Iy.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 xy=x((wF,Py)=>{"use strict";var Lr=Py.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(){};cs(t,n,a,e,"",e)};Lr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Lr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Lr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Lr.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 cs(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 Lr.arrayKeywords)for(var h=0;h<m.length;h++)cs(e,t,r,m[h],a+"/"+l+"/"+h,i,a,l,n,h)}else if(l in Lr.propsKeywords){if(m&&typeof m=="object")for(var g in m)cs(e,t,r,m[g],a+"/"+l+"/"+JA(g),i,a,l,n,g)}else(l in Lr.keywords||e.allKeys&&!(l in Lr.skipKeywords))&&cs(e,t,r,m,a+"/"+l,i,a,l,n)}r(n,a,i,s,c,d,p)}}o(cs,"_traverse");function JA(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(JA,"escapeJsonPtr")});var Ra=x(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.getSchemaRefs=it.resolveUrl=it.normalizeId=it._getFullPath=it.getFullPath=it.inlineRef=void 0;var WA=ie(),YA=Yd(),XA=xy(),QA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function eT(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Xd(e):t?ky(e)<=t:!1}o(eT,"inlineRef");it.inlineRef=eT;var tT=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Xd(e){for(let t in e){if(tT.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Xd)||typeof r=="object"&&Xd(r))return!0}return!1}o(Xd,"hasRef");function ky(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!QA.has(r)&&(typeof e[r]=="object"&&(0,WA.eachItem)(e[r],n=>t+=ky(n)),t===1/0))return 1/0}return t}o(ky,"countKeys");function Ay(e,t="",r){r!==!1&&(t=so(t));let n=e.parse(t);return Ty(e,n)}o(Ay,"getFullPath");it.getFullPath=Ay;function Ty(e,t){return e.serialize(t).split("#")[0]+"#"}o(Ty,"_getFullPath");it._getFullPath=Ty;var rT=/#\/?$/;function so(e){return e?e.replace(rT,""):""}o(so,"normalizeId");it.normalizeId=so;function nT(e,t,r){return r=so(r),e.resolve(t,r)}o(nT,"resolveUrl");it.resolveUrl=nT;var oT=/^[a-z_][-a-z0-9._]*$/i;function aT(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=so(e[r]||t),i={"":a},s=Ay(n,a,!1),c={},d=new Set;return XA(e,{allKeys:!0},(m,h,g,S)=>{if(S===void 0)return;let y=s+h,_=i[S];typeof m[r]=="string"&&(_=v.call(this,m[r])),w.call(this,m.$anchor),w.call(this,m.$dynamicAnchor),i[h]=_;function v(b){let N=this.opts.uriResolver.resolve;if(b=so(_?N(_,b):b),d.has(b))throw l(b);d.add(b);let j=this.refs[b];return typeof j=="string"&&(j=this.refs[j]),typeof j=="object"?p(m,j.schema,b):b!==so(y)&&(b[0]==="#"?(p(m,c[b],b),c[b]=m):this.refs[b]=y),b}o(v,"addRef");function w(b){if(typeof b=="string"){if(!oT.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}o(w,"addAnchor")}),c;function p(m,h,g){if(h!==void 0&&!YA(m,h))throw l(g)}o(p,"checkAmbiguosRef");function l(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(l,"ambiguos")}o(aT,"getSchemaRefs");it.getSchemaRefs=aT});var Pa=x(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.getData=Br.KeywordCxt=Br.validateFunctionCode=void 0;var zy=dy(),Ey=ba(),el=Gd(),us=ba(),iT=yy(),Ia=by(),Qd=Cy(),M=W(),G=pr(),sT=Ra(),mr=ie(),Ca=wa();function cT(e){if(Ny(e)&&(Dy(e),qy(e))){lT(e);return}$y(e,()=>(0,zy.topBoolOrEmptySchema)(e))}o(cT,"validateFunctionCode");Br.validateFunctionCode=cT;function $y({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,M._)`${G.default.data}, ${G.default.valCxt}`,n.$async,()=>{e.code((0,M._)`"use strict"; ${Uy(r,a)}`),dT(e,a),e.code(i)}):e.func(t,(0,M._)`${G.default.data}, ${uT(a)}`,n.$async,()=>e.code(Uy(r,a)).code(i))}o($y,"validateFunction");function uT(e){return(0,M._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${e.dynamicRef?(0,M._)`, ${G.default.dynamicAnchors}={}`:M.nil}}={}`}o(uT,"destructureValCxt");function dT(e,t){e.if(G.default.valCxt,()=>{e.var(G.default.instancePath,(0,M._)`${G.default.valCxt}.${G.default.instancePath}`),e.var(G.default.parentData,(0,M._)`${G.default.valCxt}.${G.default.parentData}`),e.var(G.default.parentDataProperty,(0,M._)`${G.default.valCxt}.${G.default.parentDataProperty}`),e.var(G.default.rootData,(0,M._)`${G.default.valCxt}.${G.default.rootData}`),t.dynamicRef&&e.var(G.default.dynamicAnchors,(0,M._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{e.var(G.default.instancePath,(0,M._)`""`),e.var(G.default.parentData,(0,M._)`undefined`),e.var(G.default.parentDataProperty,(0,M._)`undefined`),e.var(G.default.rootData,G.default.data),t.dynamicRef&&e.var(G.default.dynamicAnchors,(0,M._)`{}`)})}o(dT,"destructureValCxtES5");function lT(e){let{schema:t,opts:r,gen:n}=e;$y(e,()=>{r.$comment&&t.$comment&&Hy(e),gT(e),n.let(G.default.vErrors,null),n.let(G.default.errors,0),r.unevaluated&&pT(e),jy(e),_T(e)})}o(lT,"topSchemaObjCode");function pT(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,M._)`${r}.evaluated`),t.if((0,M._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,M._)`${e.evaluated}.props`,(0,M._)`undefined`)),t.if((0,M._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,M._)`${e.evaluated}.items`,(0,M._)`undefined`))}o(pT,"resetEvaluated");function Uy(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,M._)`/*# sourceURL=${r} */`:M.nil}o(Uy,"funcSourceUrl");function mT(e,t){if(Ny(e)&&(Dy(e),qy(e))){fT(e,t);return}(0,zy.boolOrEmptySchema)(e,t)}o(mT,"subschemaCode");function qy({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(qy,"schemaCxtHasRules");function Ny(e){return typeof e.schema!="boolean"}o(Ny,"isSchemaObj");function fT(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&Hy(e),yT(e),ST(e);let i=n.const("_errs",G.default.errors);jy(e,i),n.var(t,(0,M._)`${i} === ${G.default.errors}`)}o(fT,"subSchemaObjCode");function Dy(e){(0,mr.checkUnknownRules)(e),hT(e)}o(Dy,"checkKeywords");function jy(e,t){if(e.opts.jtd)return Oy(e,[],!1,t);let r=(0,Ey.getSchemaTypes)(e.schema),n=(0,Ey.coerceAndCheckDataType)(e,r);Oy(e,r,!n,t)}o(jy,"typeAndKeywords");function hT(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,mr.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(hT,"checkRefsAndKeywords");function gT(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,mr.checkStrictMode)(e,"default is ignored in the schema root")}o(gT,"checkNoDefault");function yT(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,sT.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o(yT,"updateContext");function ST(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(ST,"checkAsyncSchema");function Hy({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,M._)`${G.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let s=(0,M.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,M._)`${G.default.self}.opts.$comment(${i}, ${s}, ${c}.schema)`)}}o(Hy,"commentKeyword");function _T(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,M._)`${G.default.errors} === 0`,()=>t.return(G.default.data),()=>t.throw((0,M._)`new ${a}(${G.default.vErrors})`)):(t.assign((0,M._)`${n}.errors`,G.default.vErrors),i.unevaluated&&vT(e),t.return((0,M._)`${G.default.errors} === 0`))}o(_T,"returnResults");function vT({gen:e,evaluated:t,props:r,items:n}){r instanceof M.Name&&e.assign((0,M._)`${t}.props`,r),n instanceof M.Name&&e.assign((0,M._)`${t}.items`,n)}o(vT,"assignEvaluated");function Oy(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,mr.schemaHasRulesButRef)(i,l))){a.block(()=>By(e,"$ref",l.all.$ref.definition));return}d.jtd||wT(e,t),a.block(()=>{for(let h of l.rules)m(h);m(l.post)});function m(h){(0,el.shouldUseGroup)(i,h)&&(h.type?(a.if((0,us.checkDataType)(h.type,s,d.strictNumbers)),My(e,h),t.length===1&&t[0]===h.type&&r&&(a.else(),(0,us.reportTypeError)(e)),a.endIf()):My(e,h),c||a.if((0,M._)`${G.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(Oy,"schemaKeywords");function My(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,iT.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,el.shouldUseRule)(n,i)&&By(e,i.keyword,i.definition,t.type)})}o(My,"iterateKeywords");function wT(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(bT(e,t),e.opts.allowUnionTypes||RT(e,t),CT(e,e.dataTypes))}o(wT,"checkStrictTypes");function bT(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Ly(e.dataTypes,r)||tl(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),PT(e,t)}}o(bT,"checkContextTypes");function RT(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&tl(e,"use allowUnionTypes to allow union type keyword")}o(RT,"checkMultipleTypes");function CT(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,el.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(s=>IT(t,s))&&tl(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}o(CT,"checkKeywordTypes");function IT(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(IT,"hasApplicableType");function Ly(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(Ly,"includesType");function PT(e,t){let r=[];for(let n of e.dataTypes)Ly(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(PT,"narrowSchemaTypes");function tl(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,mr.checkStrictMode)(e,t,e.opts.strictTypes)}o(tl,"strictTypesError");var ds=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,Ia.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,mr.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,Ia.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",G.default.errors))}result(t,r,n){this.failResult((0,M.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,M.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,M._)`${r} !== undefined && (${(0,M.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?Ca.reportExtraError:Ca.reportError)(this,this.def.error,r)}$dataError(){(0,Ca.reportError)(this,this.def.$dataError||Ca.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ca.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=M.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=M.nil,r=M.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:s}=this;n.if((0,M.or)((0,M._)`${a} === undefined`,r)),t!==M.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==M.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,M.or)(s(),c());function s(){if(n.length){if(!(r instanceof M.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,M._)`${(0,us.checkDataTypes)(d,r,i.opts.strictNumbers,us.DataType.Wrong)}`}return M.nil}function c(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,M._)`!${d}(${r})`}return M.nil}}subschema(t,r){let n=(0,Qd.getSubschema)(this.it,t);(0,Qd.extendSubschemaData)(n,this.it,t),(0,Qd.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return mT(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=mr.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=mr.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,M.Name)),!0}};Br.KeywordCxt=ds;function By(e,t,r,n){let a=new ds(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,Ia.funcKeywordCode)(a,r):"macro"in r?(0,Ia.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,Ia.funcKeywordCode)(a,r)}o(By,"keywordCode");var xT=/^\/(?:[^~]|~0|~1)*$/,kT=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Gy(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return G.default.rootData;if(e[0]==="/"){if(!xT.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=G.default.rootData}else{let p=kT.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,M._)`${i}${(0,M.getProperty)((0,mr.unescapeJsonPointer)(p))}`,s=(0,M._)`${s} && ${i}`);return s;function d(p,l){return`Cannot access ${p} ${l} levels up, current level is ${t}`}}o(Gy,"getData");Br.getData=Gy});var ls=x(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});var rl=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};nl.default=rl});var xa=x(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var ol=Ra(),al=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,ol.resolveUrl)(t,r,n),this.missingSchema=(0,ol.normalizeId)((0,ol.getFullPath)(t,this.missingRef))}};il.default=al});var ms=x(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.resolveSchema=wt.getCompilingSchema=wt.resolveRef=wt.compileSchema=wt.SchemaEnv=void 0;var At=W(),AT=ls(),_n=pr(),Tt=Ra(),Vy=ie(),TT=Pa(),co=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,Tt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};wt.SchemaEnv=co;function cl(e){let t=Fy.call(this,e);if(t)return t;let r=(0,Tt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,s=new At.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),c;e.$async&&(c=s.scopeValue("Error",{ref:AT.default,code:(0,At._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");e.validateName=d;let p={gen:s,allErrors:this.opts.allErrors,data:_n.default.data,parentData:_n.default.parentData,parentDataProperty:_n.default.parentDataProperty,dataNames:[_n.default.data],dataPathArr:[At.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,At.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:At.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,At._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,TT.validateFunctionCode)(p),s.optimize(this.opts.code.optimize);let m=s.toString();l=`${s.scopeRefs(_n.default.scope)}return ${m}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let g=new Function(`${_n.default.self}`,`${_n.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{ref:g}),g.errors=null,g.schema=e.schema,g.schemaEnv=e,e.$async&&(g.$async=!0),this.opts.code.source===!0&&(g.source={validateName:d,validateCode:m,scopeValues:s._values}),this.opts.unevaluated){let{props:S,items:y}=p;g.evaluated={props:S instanceof At.Name?void 0:S,items:y instanceof At.Name?void 0:y,dynamicProps:S instanceof At.Name,dynamicItems:y instanceof At.Name},g.source&&(g.source.evaluated=(0,At.stringify)(g.evaluated))}return e.validate=g,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(cl,"compileSchema");wt.compileSchema=cl;function ET(e,t,r){var n;r=(0,Tt.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=MT.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 co({schema:s,schemaId:c,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=UT.call(this,i)}o(ET,"resolveRef");wt.resolveRef=ET;function UT(e){return(0,Tt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:cl.call(this,e)}o(UT,"inlineOrCompile");function Fy(e){for(let t of this._compilations)if(OT(t,e))return t}o(Fy,"getCompilingSchema");wt.getCompilingSchema=Fy;function OT(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(OT,"sameSchemaEnv");function MT(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||ps.call(this,e,t)}o(MT,"resolve");function ps(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Tt._getFullPath)(this.opts.uriResolver,r),a=(0,Tt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return sl.call(this,r,e);let i=(0,Tt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let c=ps.call(this,e,s);return typeof c?.schema!="object"?void 0:sl.call(this,r,c)}if(typeof s?.schema=="object"){if(s.validate||cl.call(this,s),i===(0,Tt.normalizeId)(t)){let{schema:c}=s,{schemaId:d}=this.opts,p=c[d];return p&&(a=(0,Tt.resolveUrl)(this.opts.uriResolver,a,p)),new co({schema:c,schemaId:d,root:e,baseId:a})}return sl.call(this,r,s)}}o(ps,"resolveSchema");wt.resolveSchema=ps;var zT=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function sl(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,Vy.unescapeFragment)(c)];if(d===void 0)return;r=d;let p=typeof r=="object"&&r[this.opts.schemaId];!zT.has(c)&&p&&(t=(0,Tt.resolveUrl)(this.opts.uriResolver,t,p))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Vy.schemaHasRulesButRef)(r,this.RULES)){let c=(0,Tt.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=ps.call(this,n,c)}let{schemaId:s}=this.opts;if(i=i||new co({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}o(sl,"getJsonPointer")});var Zy=x((OF,$T)=>{$T.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 dl=x((MF,Yy)=>{"use strict";var qT=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Jy=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 ul(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(ul,"stringArrayToHexStripped");var NT=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ky(e){return e.length=0,!0}o(Ky,"consumeIsZone");function DT(e,t,r){if(e.length){let n=ul(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(DT,"consumeHextets");function jT(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,s=!1,c=DT;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=Ky}else{a.push(p);continue}}return a.length&&(c===Ky?r.zone=a.join(""):s?n.push(a.join("")):n.push(ul(a))),r.address=n.join(""),r}o(jT,"getIPV6");function Wy(e){if(HT(e,":")<2)return{host:e,isIPV6:!1};let t=jT(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(Wy,"normalizeIPv6");function HT(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(HT,"findToken");function LT(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(LT,"removeDotSegments");function BT(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(BT,"normalizeComponentEncoding");function GT(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Jy(r)){let n=Wy(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(GT,"recomposeAuthority");Yy.exports={nonSimpleDomain:NT,recomposeAuthority:GT,normalizeComponentEncoding:BT,removeDotSegments:LT,isIPv4:Jy,isUUID:qT,normalizeIPv6:Wy,stringArrayToHexStripped:ul}});var rS=x(($F,tS)=>{"use strict";var{isUUID:VT}=dl(),FT=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ZT=["http","https","ws","wss","urn","urn:uuid"];function KT(e){return ZT.indexOf(e)!==-1}o(KT,"isValidSchemeName");function ll(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(ll,"wsIsSecure");function Xy(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(Xy,"httpParse");function Qy(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(Qy,"httpSerialize");function JT(e){return e.secure=ll(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(JT,"wsParse");function WT(e){if((e.port===(ll(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(WT,"wsSerialize");function YT(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(FT);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=pl(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(YT,"urnParse");function XT(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=pl(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(XT,"urnSerialize");function QT(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(QT,"urnuuidParse");function eE(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(eE,"urnuuidSerialize");var eS={scheme:"http",domainHost:!0,parse:Xy,serialize:Qy},tE={scheme:"https",domainHost:eS.domainHost,parse:Xy,serialize:Qy},fs={scheme:"ws",domainHost:!0,parse:JT,serialize:WT},rE={scheme:"wss",domainHost:fs.domainHost,parse:fs.parse,serialize:fs.serialize},nE={scheme:"urn",parse:YT,serialize:XT,skipNormalize:!0},oE={scheme:"urn:uuid",parse:QT,serialize:eE,skipNormalize:!0},hs={http:eS,https:tE,ws:fs,wss:rE,urn:nE,"urn:uuid":oE};Object.setPrototypeOf(hs,null);function pl(e){return e&&(hs[e]||hs[e.toLowerCase()])||void 0}o(pl,"getSchemeHandler");tS.exports={wsIsSecure:ll,SCHEMES:hs,isValidSchemeName:KT,getSchemeHandler:pl}});var aS=x((NF,ys)=>{"use strict";var{normalizeIPv6:aE,removeDotSegments:ka,recomposeAuthority:iE,normalizeComponentEncoding:gs,isIPv4:sE,nonSimpleDomain:cE}=dl(),{SCHEMES:uE,getSchemeHandler:nS}=rS();function dE(e,t){return typeof e=="string"?e=Vt(fr(e,t),t):typeof e=="object"&&(e=fr(Vt(e,t),t)),e}o(dE,"normalize");function lE(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=oS(fr(e,n),fr(t,n),n,!0);return n.skipEscape=!0,Vt(a,n)}o(lE,"resolve");function oS(e,t,r,n){let a={};return n||(e=fr(Vt(e,r),r),t=fr(Vt(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=ka(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=ka(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=ka(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=ka(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(oS,"resolveComponent");function pE(e,t,r){return typeof e=="string"?(e=unescape(e),e=Vt(gs(fr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Vt(gs(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=Vt(gs(fr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Vt(gs(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(pE,"equal");function Vt(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=nS(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=iE(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=ka(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(Vt,"serialize");var mE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function fr(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(mE);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(sE(n.host)===!1){let d=aE(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=nS(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&a===!1&&cE(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(fr,"parse");var ml={SCHEMES:uE,normalize:dE,resolve:lE,resolveComponent:oS,equal:pE,serialize:Vt,parse:fr};ys.exports=ml;ys.exports.default=ml;ys.exports.fastUri=ml});var sS=x(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});var iS=aS();iS.code='require("ajv/dist/runtime/uri").default';fl.default=iS});var hS=x(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.CodeGen=je.Name=je.nil=je.stringify=je.str=je._=je.KeywordCxt=void 0;var fE=Pa();Object.defineProperty(je,"KeywordCxt",{enumerable:!0,get:o(function(){return fE.KeywordCxt},"get")});var uo=W();Object.defineProperty(je,"_",{enumerable:!0,get:o(function(){return uo._},"get")});Object.defineProperty(je,"str",{enumerable:!0,get:o(function(){return uo.str},"get")});Object.defineProperty(je,"stringify",{enumerable:!0,get:o(function(){return uo.stringify},"get")});Object.defineProperty(je,"nil",{enumerable:!0,get:o(function(){return uo.nil},"get")});Object.defineProperty(je,"Name",{enumerable:!0,get:o(function(){return uo.Name},"get")});Object.defineProperty(je,"CodeGen",{enumerable:!0,get:o(function(){return uo.CodeGen},"get")});var hE=ls(),pS=xa(),gE=Bd(),Aa=ms(),yE=W(),Ta=Ra(),Ss=ba(),gl=ie(),cS=Zy(),SE=sS(),mS=o((e,t)=>new RegExp(e,t),"defaultRegExp");mS.code="new RegExp";var _E=["removeAdditional","useDefaults","coerceTypes"],vE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),wE={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."},bE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},uS=200;function RE(e){var t,r,n,a,i,s,c,d,p,l,m,h,g,S,y,_,v,w,b,N,j,Be,ht,En,wr;let Qt=e.strict,Yr=(t=e.code)===null||t===void 0?void 0:t.optimize,Io=Yr===!0||Yr===void 0?1:Yr||0,Po=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:mS,xo=(a=e.uriResolver)!==null&&a!==void 0?a:SE.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:(S=(g=e.strictRequired)!==null&&g!==void 0?g:Qt)!==null&&S!==void 0?S:!1,code:e.code?{...e.code,optimize:Io,regExp:Po}:{optimize:Io,regExp:Po},loopRequired:(y=e.loopRequired)!==null&&y!==void 0?y:uS,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:uS,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(w=e.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(N=e.schemaId)!==null&&N!==void 0?N:"$id",addUsedSchema:(j=e.addUsedSchema)!==null&&j!==void 0?j:!0,validateSchema:(Be=e.validateSchema)!==null&&Be!==void 0?Be:!0,validateFormats:(ht=e.validateFormats)!==null&&ht!==void 0?ht:!0,unicodeRegExp:(En=e.unicodeRegExp)!==null&&En!==void 0?En:!0,int32range:(wr=e.int32range)!==null&&wr!==void 0?wr:!0,uriResolver:xo}}o(RE,"requiredOptions");var Ea=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,...RE(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new yE.ValueScope({scope:{},prefixes:vE,es5:r,lines:n}),this.logger=AE(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,gE.getRules)(),dS.call(this,wE,t,"NOT SUPPORTED"),dS.call(this,bE,t,"DEPRECATED","warn"),this._metaOpts=xE.call(this),t.formats&&IE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&PE.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),CE.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=cS;n==="id"&&(a={...cS},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 pS.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,Ta.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=lS.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new Aa.SchemaEnv({schema:{},schemaId:n});if(r=Aa.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=lS.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,Ta.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(EE.call(this,n,r),!r)return(0,gl.eachItem)(n,i=>hl.call(this,i)),this;OE.call(this,r);let a={...r,type:(0,Ss.getJSONTypes)(r.type),schemaType:(0,Ss.getJSONTypes)(r.schemaType)};return(0,gl.eachItem)(n,a.type.length===0?i=>hl.call(this,i,a):i=>a.type.forEach(s=>hl.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]=fS(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,Ta.normalizeId)(s||n);let p=Ta.getSchemaRefs.call(this,t,n);return d=new Aa.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):Aa.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{Aa.compileSchema.call(this,t)}finally{this.opts=r}}};Ea.ValidationError=hE.default;Ea.MissingRefError=pS.default;je.default=Ea;function dS(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(dS,"checkOptions");function lS(e){return e=(0,Ta.normalizeId)(e),this.schemas[e]||this.refs[e]}o(lS,"getSchEnv");function CE(){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(CE,"addInitialSchemas");function IE(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(IE,"addInitialFormats");function PE(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(PE,"addInitialKeywords");function xE(){let e={...this.opts};for(let t of _E)delete e[t];return e}o(xE,"getMetaSchemaOptions");var kE={log(){},warn(){},error(){}};function AE(e){if(e===!1)return kE;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(AE,"getLogger");var TE=/^[a-z_$][a-z0-9_$:-]*$/i;function EE(e,t){let{RULES:r}=this;if((0,gl.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!TE.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(EE,"checkKeyword");function hl(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?UE.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(hl,"addRule");function UE(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(UE,"addBeforeRule");function OE(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=fS(t)),e.validateSchema=this.compile(t,!0))}o(OE,"keywordMetaschema");var ME={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function fS(e){return{anyOf:[e,ME]}}o(fS,"schemaOrData")});var gS=x(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var zE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};yl.default=zE});var vS=x(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.callRef=vn.getValidate=void 0;var $E=xa(),yS=vt(),st=W(),lo=pr(),SS=ms(),_s=ie(),qE={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=SS.resolveRef.call(d,p,a,r);if(l===void 0)throw new $E.default(n.opts.uriResolver,a,r);if(l instanceof SS.SchemaEnv)return h(l);return g(l);function m(){if(i===p)return vs(e,s,i,i.$async);let S=t.scopeValue("root",{ref:p});return vs(e,(0,st._)`${S}.validate`,p,p.$async)}function h(S){let y=_S(e,S);vs(e,y,S,S.$async)}function g(S){let y=t.scopeValue("schema",c.code.source===!0?{ref:S,code:(0,st.stringify)(S)}:{ref:S}),_=t.name("valid"),v=e.subschema({schema:S,dataTypes:[],schemaPath:st.nil,topSchemaRef:y,errSchemaPath:r},_);e.mergeEvaluated(v),e.ok(_)}}};function _S(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,st._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(_S,"getValidate");vn.getValidate=_S;function vs(e,t,r,n){let{gen:a,it:i}=e,{allErrors:s,schemaEnv:c,opts:d}=i,p=d.passContext?lo.default.this:st.nil;n?l():m();function l(){if(!c.$async)throw new Error("async schema referenced by sync schema");let S=a.let("valid");a.try(()=>{a.code((0,st._)`await ${(0,yS.callValidateCode)(e,t,p)}`),g(t),s||a.assign(S,!0)},y=>{a.if((0,st._)`!(${y} instanceof ${i.ValidationError})`,()=>a.throw(y)),h(y),s||a.assign(S,!1)}),e.ok(S)}o(l,"callAsyncRef");function m(){e.result((0,yS.callValidateCode)(e,t,p),()=>g(t),()=>h(t))}o(m,"callSyncRef");function h(S){let y=(0,st._)`${S}.errors`;a.assign(lo.default.vErrors,(0,st._)`${lo.default.vErrors} === null ? ${y} : ${lo.default.vErrors}.concat(${y})`),a.assign(lo.default.errors,(0,st._)`${lo.default.vErrors}.length`)}o(h,"addErrorsFrom");function g(S){var y;if(!i.opts.unevaluated)return;let _=(y=r?.validate)===null||y===void 0?void 0:y.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=_s.mergeEvaluated.props(a,_.props,i.props));else{let v=a.var("props",(0,st._)`${S}.evaluated.props`);i.props=_s.mergeEvaluated.props(a,v,i.props,st.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=_s.mergeEvaluated.items(a,_.items,i.items));else{let v=a.var("items",(0,st._)`${S}.evaluated.items`);i.items=_s.mergeEvaluated.items(a,v,i.items,st.Name)}}o(g,"addEvaluatedFrom")}o(vs,"callRef");vn.callRef=vs;vn.default=qE});var wS=x(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var NE=gS(),DE=vS(),jE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",NE.default,DE.default];Sl.default=jE});var bS=x(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});var ws=W(),Gr=ws.operators,bs={maximum:{okStr:"<=",ok:Gr.LTE,fail:Gr.GT},minimum:{okStr:">=",ok:Gr.GTE,fail:Gr.LT},exclusiveMaximum:{okStr:"<",ok:Gr.LT,fail:Gr.GTE},exclusiveMinimum:{okStr:">",ok:Gr.GT,fail:Gr.LTE}},HE={message:o(({keyword:e,schemaCode:t})=>(0,ws.str)`must be ${bs[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,ws._)`{comparison: ${bs[e].okStr}, limit: ${t}}`,"params")},LE={keyword:Object.keys(bs),type:"number",schemaType:"number",$data:!0,error:HE,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ws._)`${r} ${bs[t].fail} ${n} || isNaN(${r})`)}};_l.default=LE});var RS=x(vl=>{"use strict";Object.defineProperty(vl,"__esModule",{value:!0});var Ua=W(),BE={message:o(({schemaCode:e})=>(0,Ua.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,Ua._)`{multipleOf: ${e}}`,"params")},GE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:BE,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,s=t.let("res"),c=i?(0,Ua._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Ua._)`${s} !== parseInt(${s})`;e.fail$data((0,Ua._)`(${n} === 0 || (${s} = ${r}/${n}, ${c}))`)}};vl.default=GE});var IS=x(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});function CS(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(CS,"ucs2length");wl.default=CS;CS.code='require("ajv/dist/runtime/ucs2length").default'});var PS=x(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var wn=W(),VE=ie(),FE=IS(),ZE={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,wn.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,wn._)`{limit: ${e}}`,"params")},KE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ZE,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?wn.operators.GT:wn.operators.LT,s=a.opts.unicode===!1?(0,wn._)`${r}.length`:(0,wn._)`${(0,VE.useFunc)(e.gen,FE.default)}(${r})`;e.fail$data((0,wn._)`${s} ${i} ${n}`)}};bl.default=KE});var xS=x(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});var JE=vt(),Rs=W(),WE={message:o(({schemaCode:e})=>(0,Rs.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Rs._)`{pattern: ${e}}`,"params")},YE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:WE,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:i}=e,s=i.opts.unicodeRegExp?"u":"",c=r?(0,Rs._)`(new RegExp(${a}, ${s}))`:(0,JE.usePattern)(e,n);e.fail$data((0,Rs._)`!${c}.test(${t})`)}};Rl.default=YE});var kS=x(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});var Oa=W(),XE={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Oa.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,Oa._)`{limit: ${e}}`,"params")},QE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:XE,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?Oa.operators.GT:Oa.operators.LT;e.fail$data((0,Oa._)`Object.keys(${r}).length ${a} ${n}`)}};Cl.default=QE});var AS=x(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var Ma=vt(),za=W(),e0=ie(),t0={message:o(({params:{missingProperty:e}})=>(0,za.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,za._)`{missingProperty: ${e}}`,"params")},r0={keyword:"required",type:"object",schemaType:"array",$data:!0,error:t0,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 g=e.parentSchema.properties,{definedProperties:S}=e.it;for(let y of r)if(g?.[y]===void 0&&!S.has(y)){let _=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${y}" is not defined at "${_}" (strictRequired)`;(0,e0.checkStrictMode)(s,v,s.opts.strictRequired)}}function p(){if(d||i)e.block$data(za.nil,m);else for(let g of r)(0,Ma.checkReportMissingProp)(e,g)}o(p,"allErrorsMode");function l(){let g=t.let("missing");if(d||i){let S=t.let("valid",!0);e.block$data(S,()=>h(g,S)),e.ok(S)}else t.if((0,Ma.checkMissingProp)(e,r,g)),(0,Ma.reportMissingProp)(e,g),t.else()}o(l,"exitOnErrorMode");function m(){t.forOf("prop",n,g=>{e.setParams({missingProperty:g}),t.if((0,Ma.noPropertyInData)(t,a,g,c.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function h(g,S){e.setParams({missingProperty:g}),t.forOf(g,n,()=>{t.assign(S,(0,Ma.propertyInData)(t,a,g,c.ownProperties)),t.if((0,za.not)(S),()=>{e.error(),t.break()})},za.nil)}o(h,"loopUntilMissing")}};Il.default=r0});var TS=x(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var $a=W(),n0={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,$a.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,$a._)`{limit: ${e}}`,"params")},o0={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:n0,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?$a.operators.GT:$a.operators.LT;e.fail$data((0,$a._)`${r}.length ${a} ${n}`)}};Pl.default=o0});var Cs=x(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});var ES=Yd();ES.code='require("ajv/dist/runtime/equal").default';xl.default=ES});var US=x(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var kl=ba(),He=W(),a0=ie(),i0=Cs(),s0={message:o(({params:{i:e,j:t}})=>(0,He.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,He._)`{i: ${e}, j: ${t}}`,"params")},c0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:s0,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,kl.getSchemaTypes)(i.items):[];e.block$data(d,l,(0,He._)`${s} === false`),e.ok(d);function l(){let S=t.let("i",(0,He._)`${r}.length`),y=t.let("j");e.setParams({i:S,j:y}),t.assign(d,!0),t.if((0,He._)`${S} > 1`,()=>(m()?h:g)(S,y))}o(l,"validateUniqueItems");function m(){return p.length>0&&!p.some(S=>S==="object"||S==="array")}o(m,"canOptimize");function h(S,y){let _=t.name("item"),v=(0,kl.checkDataTypes)(p,_,c.opts.strictNumbers,kl.DataType.Wrong),w=t.const("indices",(0,He._)`{}`);t.for((0,He._)`;${S}--;`,()=>{t.let(_,(0,He._)`${r}[${S}]`),t.if(v,(0,He._)`continue`),p.length>1&&t.if((0,He._)`typeof ${_} == "string"`,(0,He._)`${_} += "_"`),t.if((0,He._)`typeof ${w}[${_}] == "number"`,()=>{t.assign(y,(0,He._)`${w}[${_}]`),e.error(),t.assign(d,!1).break()}).code((0,He._)`${w}[${_}] = ${S}`)})}o(h,"loopN");function g(S,y){let _=(0,a0.useFunc)(t,i0.default),v=t.name("outer");t.label(v).for((0,He._)`;${S}--;`,()=>t.for((0,He._)`${y} = ${S}; ${y}--;`,()=>t.if((0,He._)`${_}(${r}[${S}], ${r}[${y}])`,()=>{e.error(),t.assign(d,!1).break(v)})))}o(g,"loopN2")}};Al.default=c0});var OS=x(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});var Tl=W(),u0=ie(),d0=Cs(),l0={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,Tl._)`{allowedValue: ${e}}`,"params")},p0={keyword:"const",$data:!0,error:l0,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,Tl._)`!${(0,u0.useFunc)(t,d0.default)}(${r}, ${a})`):e.fail((0,Tl._)`${i} !== ${r}`)}};El.default=p0});var MS=x(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var qa=W(),m0=ie(),f0=Cs(),h0={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,qa._)`{allowedValues: ${e}}`,"params")},g0={keyword:"enum",schemaType:"array",$data:!0,error:h0,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,m0.useFunc)(t,f0.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 g=t.const("vSchema",i);l=(0,qa.or)(...a.map((S,y)=>h(g,y)))}e.pass(l);function m(){t.assign(l,!1),t.forOf("v",i,g=>t.if((0,qa._)`${p()}(${r}, ${g})`,()=>t.assign(l,!0).break()))}o(m,"loopEnum");function h(g,S){let y=a[S];return typeof y=="object"&&y!==null?(0,qa._)`${p()}(${r}, ${g}[${S}])`:(0,qa._)`${r} === ${y}`}o(h,"equalCode")}};Ul.default=g0});var zS=x(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});var y0=bS(),S0=RS(),_0=PS(),v0=xS(),w0=kS(),b0=AS(),R0=TS(),C0=US(),I0=OS(),P0=MS(),x0=[y0.default,S0.default,_0.default,v0.default,w0.default,b0.default,R0.default,C0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},I0.default,P0.default];Ol.default=x0});var zl=x(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.validateAdditionalItems=void 0;var bn=W(),Ml=ie(),k0={message:o(({params:{len:e}})=>(0,bn.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,bn._)`{limit: ${e}}`,"params")},A0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:k0,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Ml.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}$S(e,n)}};function $S(e,t){let{gen:r,schema:n,data:a,keyword:i,it:s}=e;s.items=!0;let c=r.const("len",(0,bn._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,bn._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,Ml.alwaysValidSchema)(s,n)){let p=r.var("valid",(0,bn._)`${c} <= ${t.length}`);r.if((0,bn.not)(p),()=>d(p)),e.ok(p)}function d(p){r.forRange("i",t.length,c,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:Ml.Type.Num},p),s.allErrors||r.if((0,bn.not)(p),()=>r.break())})}o(d,"validateItems")}o($S,"validateAdditionalItems");Na.validateAdditionalItems=$S;Na.default=A0});var $l=x(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.validateTuple=void 0;var qS=W(),Is=ie(),T0=vt(),E0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return NS(e,"additionalItems",t);r.items=!0,!(0,Is.alwaysValidSchema)(r,t)&&e.ok((0,T0.validateArray)(e))}};function NS(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=Is.mergeEvaluated.items(n,r.length,c.items));let d=n.name("valid"),p=n.const("len",(0,qS._)`${i}.length`);r.forEach((m,h)=>{(0,Is.alwaysValidSchema)(c,m)||(n.if((0,qS._)`${p} > ${h}`,()=>e.subschema({keyword:s,schemaProp:h,dataProp:h},d)),e.ok(d))});function l(m){let{opts:h,errSchemaPath:g}=c,S=r.length,y=S===m.minItems&&(S===m.maxItems||m[t]===!1);if(h.strictTuples&&!y){let _=`"${s}" is ${S}-tuple, but minItems or maxItems/${t} are not specified or different at path "${g}"`;(0,Is.checkStrictMode)(c,_,h.strictTuples)}}o(l,"checkStrictTuple")}o(NS,"validateTuple");Da.validateTuple=NS;Da.default=E0});var DS=x(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var U0=$l(),O0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,U0.validateTuple)(e,"items"),"code")};ql.default=O0});var HS=x(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var jS=W(),M0=ie(),z0=vt(),$0=zl(),q0={message:o(({params:{len:e}})=>(0,jS.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,jS._)`{limit: ${e}}`,"params")},N0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:q0,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,M0.alwaysValidSchema)(n,t)&&(a?(0,$0.validateAdditionalItems)(e,a):e.ok((0,z0.validateArray)(e)))}};Nl.default=N0});var LS=x(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var bt=W(),Ps=ie(),D0={message:o(({params:{min:e,max:t}})=>t===void 0?(0,bt.str)`must contain at least ${e} valid item(s)`:(0,bt.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,bt._)`{minContains: ${e}}`:(0,bt._)`{minContains: ${e}, maxContains: ${t}}`,"params")},j0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:D0,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,bt._)`${a}.length`);if(e.setParams({min:s,max:c}),c===void 0&&s===0){(0,Ps.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&s>c){(0,Ps.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ps.alwaysValidSchema)(i,r)){let y=(0,bt._)`${l} >= ${s}`;c!==void 0&&(y=(0,bt._)`${y} && ${l} <= ${c}`),e.pass(y);return}i.items=!0;let m=t.name("valid");c===void 0&&s===1?g(m,()=>t.if(m,()=>t.break())):s===0?(t.let(m,!0),c!==void 0&&t.if((0,bt._)`${a}.length > 0`,h)):(t.let(m,!1),h()),e.result(m,()=>e.reset());function h(){let y=t.name("_valid"),_=t.let("count",0);g(y,()=>t.if(y,()=>S(_)))}o(h,"validateItemsWithCount");function g(y,_){t.forRange("i",0,l,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:Ps.Type.Num,compositeRule:!0},y),_()})}o(g,"validateItems");function S(y){t.code((0,bt._)`${y}++`),c===void 0?t.if((0,bt._)`${y} >= ${s}`,()=>t.assign(m,!0).break()):(t.if((0,bt._)`${y} > ${c}`,()=>t.assign(m,!1).break()),s===1?t.assign(m,!0):t.if((0,bt._)`${y} >= ${s}`,()=>t.assign(m,!0)))}o(S,"checkLimits")}};Dl.default=j0});var VS=x(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.validateSchemaDeps=Ft.validatePropertyDeps=Ft.error=void 0;var jl=W(),H0=ie(),ja=vt();Ft.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,jl.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,jl._)`{property: ${e},
30
30
  missingProperty: ${n},
31
31
  depsCount: ${t},
32
- deps: ${r}}`,"params")};var PE={keyword:"dependencies",type:"object",schemaType:"object",error:Ht.error,code(e){let[t,r]=xE(e);$S(e,t),qS(e,r)}};function xE({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(xE,"splitDependencies");function $S(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,$a.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,$a.checkReportMissingProp)(e,p)}):(r.if((0,Dl._)`${d} && (${(0,$a.checkMissingProp)(e,c,i)})`),(0,$a.reportMissingProp)(e,i),r.else())}}o($S,"validatePropertyDeps");Ht.validatePropertyDeps=$S;function qS(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,s=r.name("valid");for(let c in t)(0,IE.alwaysValidSchema)(i,t[c])||(r.if((0,$a.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(qS,"validateSchemaDeps");Ht.validateSchemaDeps=qS;Ht.default=PE});var jS=x(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var DS=J(),AE=ie(),kE={message:"property name must be valid",params:o(({params:e})=>(0,DS._)`{propertyName: ${e.propertyName}}`,"params")},TE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kE,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,AE.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,DS.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};jl.default=TE});var Ll=x(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var Is=St(),Tt=J(),EE=ir(),Ps=ie(),UE={message:"must NOT have additional properties",params:o(({params:e})=>(0,Tt._)`{additionalProperty: ${e.additionalProperty}}`,"params")},OE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:UE,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,Ps.alwaysValidSchema)(s,r))return;let p=(0,Is.allSchemaProperties)(n.properties),l=(0,Is.allSchemaProperties)(n.patternProperties);m(),e.ok((0,Tt._)`${i} === ${EE.default.errors}`);function m(){t.forIn("key",a,_=>{!p.length&&!l.length?S(_):t.if(h(_),()=>S(_))})}o(m,"checkAdditionalProperties");function h(_){let v;if(p.length>8){let w=(0,Ps.schemaRefOrVal)(s,n.properties,"properties");v=(0,Is.isOwnProperty)(t,w,_)}else p.length?v=(0,Tt.or)(...p.map(w=>(0,Tt._)`${_} === ${w}`)):v=Tt.nil;return l.length&&(v=(0,Tt.or)(v,...l.map(w=>(0,Tt._)`${(0,Is.usePattern)(e,w)}.test(${_})`))),(0,Tt.not)(v)}o(h,"isAdditional");function g(_){t.code((0,Tt._)`delete ${a}[${_}]`)}o(g,"deleteAdditional");function S(_){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){g(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),c||t.break();return}if(typeof r=="object"&&!(0,Ps.alwaysValidSchema)(s,r)){let v=t.name("valid");d.removeAdditional==="failing"?(y(_,v,!1),t.if((0,Tt.not)(v),()=>{e.reset(),g(_)})):(y(_,v),c||t.if((0,Tt.not)(v),()=>t.break()))}}o(S,"additionalPropertyCode");function y(_,v,w){let b={keyword:"additionalProperties",dataProp:_,dataPropType:Ps.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,v)}o(y,"applyAdditionalSchema")}};Hl.default=OE});var BS=x(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var ME=ba(),HS=St(),Bl=ie(),LS=Ll(),zE={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&&LS.default.code(new ME.KeywordCxt(i,LS.default,"additionalProperties"));let s=(0,HS.allSchemaProperties)(r);for(let m of s)i.definedProperties.add(m);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Bl.mergeEvaluated.props(t,(0,Bl.toHash)(s),i.props));let c=s.filter(m=>!(0,Bl.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,HS.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")}};Gl.default=zE});var ZS=x(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var GS=St(),xs=J(),VS=ie(),FS=ie(),$E={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,GS.allSchemaProperties)(r),d=c.filter(y=>(0,VS.alwaysValidSchema)(i,r[y]));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 xs.Name)&&(i.props=(0,FS.evaluatedPropsToName)(t,i.props));let{props:m}=i;h();function h(){for(let y of c)p&&g(y),i.allErrors?S(y):(t.var(l,!0),S(y),t.if(l))}o(h,"validatePatternProperties");function g(y){for(let _ in p)new RegExp(y).test(_)&&(0,VS.checkStrictMode)(i,`property ${_} matches pattern ${y} (use allowMatchingProperties)`)}o(g,"checkMatchingProperties");function S(y){t.forIn("key",n,_=>{t.if((0,xs._)`${(0,GS.usePattern)(e,y)}.test(${_})`,()=>{let v=d.includes(y);v||e.subschema({keyword:"patternProperties",schemaProp:y,dataProp:_,dataPropType:FS.Type.Str},l),i.opts.unevaluated&&m!==!0?t.assign((0,xs._)`${m}[${_}]`,!0):!v&&!i.allErrors&&t.if((0,xs.not)(l),()=>t.break())})})}o(S,"validateProperties")}};Vl.default=$E});var KS=x(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var qE=ie(),NE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,qE.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"}};Fl.default=NE});var JS=x(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var DE=St(),jE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:DE.validateUnion,error:{message:"must match a schema in anyOf"}};Zl.default=jE});var WS=x(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var As=J(),HE=ie(),LE={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,As._)`{passingSchemas: ${e.passing}}`,"params")},BE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:LE,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,HE.alwaysValidSchema)(a,l)?t.var(d,!0):h=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,As._)`${d} && ${s}`).assign(s,!1).assign(c,(0,As._)`[${c}, ${m}]`).else(),t.if(d,()=>{t.assign(s,!0),t.assign(c,m),h&&e.mergeEvaluated(h,As.Name)})})}o(p,"validateOneOf")}};Kl.default=BE});var YS=x(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var GE=ie(),VE={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,GE.alwaysValidSchema)(n,i))return;let c=e.subschema({keyword:"allOf",schemaProp:s},a);e.ok(a),e.mergeEvaluated(c)})}};Jl.default=VE});var e_=x(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var ks=J(),QS=ie(),FE={message:o(({params:e})=>(0,ks.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,ks._)`{failingKeyword: ${e.ifClause}}`,"params")},ZE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:FE,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,QS.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=XS(n,"then"),i=XS(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,ks.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,ks._)`${l}`):e.setParams({ifClause:l})}}o(p,"validateClause")}};function XS(e,t){let r=e.schema[t];return r!==void 0&&!(0,QS.alwaysValidSchema)(e,r)}o(XS,"hasSchema");Wl.default=ZE});var t_=x(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var KE=ie(),JE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,KE.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Yl.default=JE});var r_=x(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var WE=Ml(),YE=US(),XE=zl(),QE=MS(),eU=zS(),tU=NS(),rU=jS(),nU=Ll(),oU=BS(),aU=ZS(),iU=KS(),sU=JS(),cU=WS(),uU=YS(),dU=e_(),lU=t_();function pU(e=!1){let t=[iU.default,sU.default,cU.default,uU.default,dU.default,lU.default,rU.default,nU.default,tU.default,oU.default,aU.default];return e?t.push(YE.default,QE.default):t.push(WE.default,XE.default),t.push(eU.default),t}o(pU,"getApplicator");Xl.default=pU});var n_=x(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var Ie=J(),mU={message:o(({schemaCode:e})=>(0,Ie.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Ie._)`{format: ${e}}`,"params")},fU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:mU,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():g();function h(){let S=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),y=r.const("fDef",(0,Ie._)`${S}[${s}]`),_=r.let("fType"),v=r.let("format");r.if((0,Ie._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(_,(0,Ie._)`${y}.type || "string"`).assign(v,(0,Ie._)`${y}.validate`),()=>r.assign(_,(0,Ie._)`"string"`).assign(v,y)),e.fail$data((0,Ie.or)(w(),b()));function w(){return d.strictSchema===!1?Ie.nil:(0,Ie._)`${s} && !${v}`}o(w,"unknownFmt");function b(){let N=l.$async?(0,Ie._)`(${y}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Ie._)`${v}(${n})`,j=(0,Ie._)`(typeof ${v} == "function" ? ${N} : ${v}.test(${n}))`;return(0,Ie._)`${v} && ${v} !== true && ${_} === ${t} && !${j}`}o(b,"invalidFmt")}o(h,"validate$DataFormat");function g(){let S=m.formats[i];if(!S){w();return}if(S===!0)return;let[y,_,v]=b(S);y===t&&e.pass(N());function w(){if(d.strictSchema===!1){m.logger.warn(j());return}throw new Error(j());function j(){return`unknown format "${i}" ignored in schema at path "${p}"`}}o(w,"unknownFormat");function b(j){let He=j instanceof RegExp?(0,Ie.regexpCode)(j):d.code.formats?(0,Ie._)`${d.code.formats}${(0,Ie.getProperty)(i)}`:void 0,lt=r.scopeValue("formats",{key:i,ref:j,code:He});return typeof j=="object"&&!(j instanceof RegExp)?[j.type||"string",j.validate,(0,Ie._)`${lt}.validate`]:["string",j,lt]}o(b,"getFormat");function N(){if(typeof S=="object"&&!(S instanceof RegExp)&&S.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ie._)`await ${v}(${n})`}return typeof _=="function"?(0,Ie._)`${v}(${n})`:(0,Ie._)`${v}.test(${n})`}o(N,"validCondition")}o(g,"validateFormat")}};Ql.default=fU});var o_=x(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var hU=n_(),gU=[hU.default];ep.default=gU});var a_=x(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.contentVocabulary=so.metadataVocabulary=void 0;so.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];so.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var s_=x(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var yU=fS(),SU=AS(),_U=r_(),vU=o_(),i_=a_(),wU=[yU.default,SU.default,(0,_U.default)(),vU.default,i_.metadataVocabulary,i_.contentVocabulary];tp.default=wU});var u_=x(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});Ts.DiscrError=void 0;var c_;(function(e){e.Tag="tag",e.Mapping="mapping"})(c_||(Ts.DiscrError=c_={}))});var l_=x(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});var co=J(),rp=u_(),d_=ls(),bU=Ra(),RU=ie(),CU={message:o(({params:{discrError:e,tagName:t}})=>e===rp.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,co._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},IU={keyword:"discriminator",type:"object",schemaType:"object",error:CU,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,co._)`${r}${(0,co.getProperty)(c)}`);t.if((0,co._)`typeof ${p} == "string"`,()=>l(),()=>e.error(!1,{discrError:rp.DiscrError.Tag,tag:p,tagName:c})),e.ok(d);function l(){let g=h();t.if(!1);for(let S in g)t.elseIf((0,co._)`${p} === ${S}`),t.assign(d,m(g[S]));t.else(),e.error(!1,{discrError:rp.DiscrError.Mapping,tag:p,tagName:c}),t.endIf()}o(l,"validateMapping");function m(g){let S=t.name("valid"),y=e.subschema({keyword:"oneOf",schemaProp:g},S);return e.mergeEvaluated(y,co.Name),S}o(m,"applyTagSchema");function h(){var g;let S={},y=v(a),_=!0;for(let N=0;N<s.length;N++){let j=s[N];if(j?.$ref&&!(0,RU.schemaHasRulesButRef)(j,i.self.RULES)){let lt=j.$ref;if(j=d_.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,lt),j instanceof d_.SchemaEnv&&(j=j.schema),j===void 0)throw new bU.default(i.opts.uriResolver,i.baseId,lt)}let He=(g=j?.properties)===null||g===void 0?void 0:g[c];if(typeof He!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);_=_&&(y||v(j)),w(He,N)}if(!_)throw new Error(`discriminator: "${c}" must be required`);return S;function v({required:N}){return Array.isArray(N)&&N.includes(c)}function w(N,j){if(N.const)b(N.const,j);else if(N.enum)for(let He of N.enum)b(He,j);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function b(N,j){if(typeof N!="string"||N in S)throw new Error(`discriminator: "${c}" values must be unique strings`);S[N]=j}}o(h,"getMapping")}};np.default=IU});var p_=x((PZ,PU)=>{PU.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 ap=x((ge,op)=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.MissingRefError=ge.ValidationError=ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=ge.Ajv=void 0;var xU=cS(),AU=s_(),kU=l_(),m_=p_(),TU=["/properties"],Es="http://json-schema.org/draft-07/schema",uo=class extends xU.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),AU.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(kU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(m_,TU):m_;this.addMetaSchema(t,Es,!1),this.refs["http://json-schema.org/schema"]=Es}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Es)?Es:void 0)}};ge.Ajv=uo;op.exports=ge=uo;op.exports.Ajv=uo;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=uo;var EU=ba();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:o(function(){return EU.KeywordCxt},"get")});var lo=J();Object.defineProperty(ge,"_",{enumerable:!0,get:o(function(){return lo._},"get")});Object.defineProperty(ge,"str",{enumerable:!0,get:o(function(){return lo.str},"get")});Object.defineProperty(ge,"stringify",{enumerable:!0,get:o(function(){return lo.stringify},"get")});Object.defineProperty(ge,"nil",{enumerable:!0,get:o(function(){return lo.nil},"get")});Object.defineProperty(ge,"Name",{enumerable:!0,get:o(function(){return lo.Name},"get")});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:o(function(){return lo.CodeGen},"get")});var UU=us();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:o(function(){return UU.default},"get")});var OU=Ra();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:o(function(){return OU.default},"get")})});var w_=x(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.formatNames=Bt.fastFormats=Bt.fullFormats=void 0;function Lt(e,t){return{validate:e,compare:t}}o(Lt,"fmtDef");Bt.fullFormats={date:Lt(y_,up),time:Lt(sp(!0),dp),"date-time":Lt(f_(!0),__),"iso-time":Lt(sp(),S_),"iso-date-time":Lt(f_(),v_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:DU,"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:FU,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:jU,int32:{type:"number",validate:BU},int64:{type:"number",validate:GU},float:{type:"number",validate:g_},double:{type:"number",validate:g_},password:!0,binary:!0};Bt.fastFormats={...Bt.fullFormats,date:Lt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,up),time:Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,dp),"date-time":Lt(/^\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,__),"iso-time":Lt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,S_),"iso-date-time":Lt(/^\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,v_),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};Bt.formatNames=Object.keys(Bt.fullFormats);function MU(e){return e%4===0&&(e%100!==0||e%400===0)}o(MU,"isLeapYear");var zU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,$U=[0,31,28,31,30,31,30,31,31,30,31,30,31];function y_(e){let t=zU.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&&MU(r)?29:$U[n])}o(y_,"date");function up(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(up,"compareDate");var ip=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function sp(e){return o(function(r){let n=ip.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(sp,"getTime");function dp(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(dp,"compareTime");function S_(e,t){if(!(e&&t))return;let r=ip.exec(e),n=ip.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(S_,"compareIsoTime");var cp=/t|\s/i;function f_(e){let t=sp(e);return o(function(n){let a=n.split(cp);return a.length===2&&y_(a[0])&&t(a[1])},"date_time")}o(f_,"getDateTime");function __(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(__,"compareDateTime");function v_(e,t){if(!(e&&t))return;let[r,n]=e.split(cp),[a,i]=t.split(cp),s=up(r,a);if(s!==void 0)return s||dp(n,i)}o(v_,"compareIsoDateTime");var qU=/\/|:/,NU=/^(?:[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 DU(e){return qU.test(e)&&NU.test(e)}o(DU,"uri");var h_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function jU(e){return h_.lastIndex=0,h_.test(e)}o(jU,"byte");var HU=-(2**31),LU=2**31-1;function BU(e){return Number.isInteger(e)&&e<=LU&&e>=HU}o(BU,"validateInt32");function GU(e){return Number.isInteger(e)}o(GU,"validateInt64");function g_(){return!0}o(g_,"validateNumber");var VU=/[^\\]\\Z/;function FU(e){if(VU.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(FU,"regex")});var b_=x(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.formatLimitDefinition=void 0;var ZU=ap(),Et=J(),Nr=Et.operators,Us={formatMaximum:{okStr:"<=",ok:Nr.LTE,fail:Nr.GT},formatMinimum:{okStr:">=",ok:Nr.GTE,fail:Nr.LT},formatExclusiveMaximum:{okStr:"<",ok:Nr.LT,fail:Nr.GTE},formatExclusiveMinimum:{okStr:">",ok:Nr.GT,fail:Nr.LTE}},KU={message:o(({keyword:e,schemaCode:t})=>(0,Et.str)`should be ${Us[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,Et._)`{comparison: ${Us[e].okStr}, limit: ${t}}`,"params")};po.formatLimitDefinition={keyword:Object.keys(Us),type:"string",schemaType:"string",$data:!0,error:KU,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 ZU.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}),g=t.const("fmt",(0,Et._)`${h}[${d.schemaCode}]`);e.fail$data((0,Et.or)((0,Et._)`typeof ${g} != "object"`,(0,Et._)`${g} instanceof RegExp`,(0,Et._)`typeof ${g}.compare != "function"`,m(g)))}o(p,"validate$DataFormat");function l(){let h=d.schema,g=c.formats[h];if(!g||g===!0)return;if(typeof g!="object"||g instanceof RegExp||typeof g.compare!="function")throw new Error(`"${a}": format "${h}" does not define "compare" function`);let S=t.scopeValue("formats",{key:h,ref:g,code:s.code.formats?(0,Et._)`${s.code.formats}${(0,Et.getProperty)(h)}`:void 0});e.fail$data(m(S))}o(l,"validateFormat");function m(h){return(0,Et._)`${h}.compare(${r}, ${n}) ${Us[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var JU=o(e=>(e.addKeyword(po.formatLimitDefinition),e),"formatLimitPlugin");po.default=JU});var P_=x((qa,I_)=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});var mo=w_(),WU=b_(),lp=J(),R_=new lp.Name("fullFormats"),YU=new lp.Name("fastFormats"),pp=o((e,t={keywords:!0})=>{if(Array.isArray(t))return C_(e,t,mo.fullFormats,R_),e;let[r,n]=t.mode==="fast"?[mo.fastFormats,YU]:[mo.fullFormats,R_],a=t.formats||mo.formatNames;return C_(e,a,r,n),t.keywords&&(0,WU.default)(e),e},"formatsPlugin");pp.get=(e,t="full")=>{let n=(t==="fast"?mo.fastFormats:mo.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function C_(e,t,r,n){var a,i;(a=(i=e.opts.code).formats)!==null&&a!==void 0||(i.formats=(0,lp._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}o(C_,"addFormats");I_.exports=qa=pp;Object.defineProperty(qa,"__esModule",{value:!0});qa.default=pp});me();me();var Jw=new Set(["localhost","::1"]);function Kt(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(Kt,"normalizeHostname");function ke(e){let t=Kt(e.hostname);return e.protocol==="http:"&&(Jw.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(ke,"isLoopbackHttpUrl");var Sm=new Ot("gateway-route");function _m(e,t){Sm.set(e,t)}o(_m,"setGatewayRouteContext");function Ao(e){return Sm.get(e)}o(Ao,"readGatewayRouteContext");function Tn(e){let t=Ao(e);if(!t)throw new te("Gateway route context has not been set");return t}o(Tn,"requireGatewayRouteContext");var vm=new Ot("mcp-oauth-runtime-config");function En(e,t){vm.set(e,t)}o(En,"setMcpOAuthRuntimeConfig");function wm(e){let t=vm.get(e);if(!t)throw new $("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(wm,"requireMcpOAuthRuntimeConfig");var ko=u.string().trim().min(1),Ww=60,Yw=24*60*60,Xw=15*Ww,Qw=10*365*Yw,To={accessTokenTtlSeconds:Xw,refreshTokenTtlSeconds:Qw,cimdEnabled:!0},eb=u.object({issuer:u.url(),jwksUrl:u.url(),audience:ko.optional()}),tb=u.object({url:u.url(),tokenUrl:u.url().optional(),clientId:ko.optional(),clientSecret:ko.optional(),scope:ko.default("openid profile email"),audience:ko.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().superRefine((e,t)=>{if(!Rm(e.url))for(let r of["tokenUrl","clientId","clientSecret"])e[r]||t.addIssue({code:u.ZodIssueCode.custom,message:`${r} is required for federated browser login`,path:[r]})}),rb=u.object({accessTokenTtlSeconds:u.coerce.number().int().positive().default(To.accessTokenTtlSeconds),refreshTokenTtlSeconds:u.coerce.number().int().positive().default(To.refreshTokenTtlSeconds),cimdEnabled:u.boolean().default(To.cimdEnabled)}).strict().default(To),Rc=u.object({oidc:eb,browserLogin:tb,gateway:rb.optional().default(To)}).strict();function bm(e){return Rm(e.browserLogin.url)?"local_dev":"federated_oidc"}o(bm,"readBrowserLoginKind");function Rm(e){let t;try{t=new URL(e)}catch{return!1}return ke(t)&&t.pathname==="/oauth/dev-login"}o(Rm,"isLoopbackDevLoginUrl");function Cm(e){return Rc.parse(e)}o(Cm,"parseMcpOAuthRuntimeConfig");function Te(){let e;try{e=yc()}catch(t){throw new te("MCP gateway OAuth config can only be read during a request. Wrap tests in `runWithRequestContext` and ensure MCP OAuth routes are registered through `McpGatewayPlugin`.",{cause:t})}return wm(e)}o(Te,"getGatewayOAuthConfig");me();var nb=["shared-oauth","user-oauth","static-secret","user-secret","shared-secret"],ob=["none","client_secret_basic","client_secret_post"],We=u.string().min(1).brand(),Ee=u.string().min(1).brand(),Ye=u.string().min(1).brand(),hr=u.string().min(1).brand(),ri=u.enum(nb),Cc=u.enum(ob),ni=u.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),Ic=u.object({name:ni,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict();me();var X=u.string().datetime({offset:!0}).brand();function oe(e){return X.parse(e.toISOString())}o(oe,"toIsoTimestamp");function Jt(e,t){return new Date(e.getTime()+t*1e3)}o(Jt,"addSeconds");me();function ue(e){return new URL(e).origin}o(ue,"readGatewayRequestOrigin");function wt(e){return ue(e)}o(wt,"readGatewayOAuthIssuer");function Pc(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(Pc,"truncate");function Im(e){return"cause"in e?e.cause:void 0}o(Im,"readCause");function Xe(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=Pc(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=Pc(r.message);let n=Im(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`]=Pc(n.message),n=Im(n)}}o(Xe,"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 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 xc(e,t){Pm(e,{subjectId:t.subjectId})}o(xc,"applyGatewayPrincipalLogProperties");function xm(e,t){Pm(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(xm,"applyGatewayRouteLogProperties");var T="gatewayCode",Un={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"},too_many_requests:{code:"too_many_requests",seam:"runtime",status:429,title:"Too Many Requests",publicDetail:"The request exceeded the allowed rate.",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_capability_unavailable:{code:"upstream_capability_unavailable",seam:"upstream_mcp",status:503,title:"Service Unavailable",publicDetail:"The upstream capability is unavailable. 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."}}},bt={...Un.runtime,...Un.config,...Un.downstream_auth,...Un.downstream_oauth,...Un.upstream_auth,...Un.upstream_mcp};function Wt(e){return typeof e=="string"&&Object.hasOwn(bt,e)}o(Wt,"isGatewayProblemCode");function oi(e){return Wt(e)&&ft(e).callbackFailure===!0}o(oi,"isGatewayCallbackFailureCode");function ft(e){return bt[e]}o(ft,"readGatewayProblemDefinition");function Am(e){switch(e){case 400:return"invalid_request";case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";case 429:return"too_many_requests";default:return"internal_server_error"}}o(Am,"readDefaultGatewayProblemCodeForStatus");function km(e){let t=ft(e);return{title:t.title,body:t.publicDetail}}o(km,"readGatewayCallbackFailureContent");function Rt(e){if(!(e instanceof A))return;let t=e.extensionMembers?.[T];return Wt(t)?t:void 0}o(Rt,"readGatewayProblemCode");function D(e,t,r){let n=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...r===void 0?{}:{cause:r}}:e,a=ft(n.code),i=n.privateDetail??(ai(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),s=ab(n);return new A({message:i,extensionMembers:{[T]:n.code}},s===void 0?void 0:{cause:s})}o(D,"createGatewayRuntimeError");async function Ct(e,t,r){let n=ft(r.code),a=ib(r.code,r.detail),i=ai(r.code)?r.title??n.title:n.title,c={problem:{...pt.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),pt.format(c,e,t)}o(Ct,"gatewayProblemResponse");function ai(e){return ft(e).status<500}o(ai,"canExposeGatewayProblemDetail");function ab(e){return!e.privateDetail||ai(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o(ab,"readRuntimeErrorCause");function ib(e,t){let r=ft(e);return ai(e)&&t||r.publicDetail}o(ib,"readSafeGatewayProblemDetail");me();var sb=43,cb=128,ub=/^[A-Za-z0-9._~-]+$/,Ac="S256",ii=u.literal(Ac),si=u.string().min(sb).max(cb).regex(ub);me();var Tm=["none","client_secret_post","client_secret_basic"],kc=[...Tm,"private_key_jwt"],db=["awaiting_login","awaiting_setup"],lb=u.string().min(1).brand(),Ue=u.string().min(1).brand(),Eo=u.uuid().brand(),at=u.uuid().brand(),ci=u.uuid().brand(),Em=u.enum(Tm),Um=u.enum(kc),MN=u.enum(db),Om=u.object({client_id:Ue,client_name:u.string().min(1),redirect_uris:u.array(u.string().min(1)).min(1),jwks_uri:u.string().min(1).optional(),token_endpoint_auth_method:Um.default("none")}).superRefine((e,t)=>{e.token_endpoint_auth_method==="private_key_jwt"&&e.jwks_uri===void 0&&t.addIssue({code:"custom",path:["jwks_uri"],message:"jwks_uri is required for private_key_jwt clients."})}),Tc=u.object({clientId:Ue,clientName:u.string().min(1),redirectUris:u.array(u.string().min(1)),tokenEndpointAuthMethod:Um,hashedClientSecret:u.string().optional(),clientSecretExpiresAt:X.optional(),clientExpiresAt:X,revokedAt:X.optional(),createdAt:X}),Ec=u.object({clientId:Ue,resource:u.string(),virtualServerId:Ee,subjectId:lb,scope:u.string(),roles:u.array(u.string()),createdAt:X,expiresAt:X}),zN=Ec.extend({id:at,redirectUri:u.string(),clientState:u.string().optional(),codeChallenge:u.string(),codeChallengeMethod:ii}),Uc=Ec.extend({id:Eo,currentRefreshTokenHash:u.string().optional(),previousRefreshTokenHash:u.string().optional(),previousRefreshTokenRotatedAt:X.optional(),revokedAt:X.optional(),revokedReason:u.string().optional()}),ui=Ec.extend({tokenHash:u.string(),grantId:Eo,revokedAt:X.optional()});function Oc(){return at.parse(crypto.randomUUID())}o(Oc,"createDownstreamAuthorizationTransactionId");function Mc(){return ci.parse(crypto.randomUUID())}o(Mc,"createDownstreamBrowserLoginStateId");function Mm(){return Eo.parse(crypto.randomUUID())}o(Mm,"createDownstreamGrantId");var _e="mcp:tools";function zm(e,t){if(e===t)return!0;let r=new URL(e),n=new URL(t);return ke(r)&&ke(n)&&r.pathname===n.pathname&&r.search===n.search}o(zm,"redirectUriMatchesRegistration");function $m(e){return ke(e)&&e.pathname==="/oauth/dev-login"}o($m,"isLoopbackDevLoginUrl");function di(e,t){return new URL(e,wt(t)).toString()}o(di,"buildGatewayOAuthUrl");function zc(e){return new URL(`/mcp/${encodeURIComponent(e.virtualServerId)}`,ue(e.requestUrl)).toString()}o(zc,"buildScopedAuthorizationServerIssuer");function pb(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,ue(e.requestUrl)).toString()}o(pb,"buildScopedAuthorizationEndpoint");function $c(e){let t=Te();return{issuer:wt(e),authorization_endpoint:di("/oauth/authorize",e),token_endpoint:di("/oauth/token",e),registration_endpoint:di("/oauth/register",e),revocation_endpoint:di("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[_e],code_challenge_methods_supported:[Ac],token_endpoint_auth_methods_supported:kc,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","private_key_jwt","none"],client_id_metadata_document_supported:t.gateway.cimdEnabled,"x-zuplo-browser-login-kind":bm(t)}}o($c,"buildAuthorizationServerMetadata");function qm(e){let t=zc(e);return{...$c(e.requestUrl),issuer:t,authorization_endpoint:pb(e)}}o(qm,"buildScopedAuthorizationServerMetadata");var Zr="2025-06-18";async function Nm(e,t){try{let r=Ee.parse(e.params.virtualServerId),n=Kr(r);return Response.json(mb(n.virtualServerId,e.url))}catch(r){let n=Rt(r);return Ct(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(Nm,"protectedResourceMetadataHandler");function mb(e,t){return{resource:gr(e,t),resource_name:e,authorization_servers:[zc({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[_e],mcp_protocol_version:Zr}}o(mb,"buildProtectedResourceMetadataResponseBody");function gr(e,t){return new URL(`/mcp/${encodeURIComponent(e)}`,ue(t)).toString()}o(gr,"buildCanonicalMcpResourceForVirtualServer");function Dm(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,ue(t)).toString()}o(Dm,"buildProtectedResourceMetadataUrlForVirtualServer");var fb=u.record(u.string(),u.unknown()),jm=u.string().min(1),hb=u.union([jm.transform(e=>[e]),u.array(jm)]),ve=u.string().min(1).brand(),gb=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],yb=["https://zuplo.com/roles","roles","role","permissions","groups"],Hm=new Ot("gateway-principal");function Sb(e){let t=fb.safeParse(e);return t.success?t.data:{}}o(Sb,"toClaimRecord");function _b(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(_b,"readValidationFailureDetail");function vb(e,t,r){for(let i of gb){let s=ve.safeParse(t[i]);if(s.success)return s.data}let n=ve.safeParse(e?.sub);if(!n.success)throw D("identity_context_missing",_b(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===wt(r)?n.data:ve.parse(`${a}|${n.data}`)}o(vb,"readNormalizedSubjectId");function wb(e){let t=new Set;for(let r of yb){let n=hb.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o(wb,"readRoles");function On(e,t){let r=Sb(e?.data),n={subjectId:vb(e,r,t)},a=wb(r);return a&&(n.roles=a),n}o(On,"parseGatewayPrincipal");function Lm(e){let t=Nc(e);if(!t)throw D("identity_context_missing","Gateway principal has not been hydrated");return t}o(Lm,"requireGatewayPrincipal");function Bm(e,t){Hm.set(e,t)}o(Bm,"setGatewayPrincipal");function Nc(e){return Hm.get(e)}o(Nc,"readGatewayPrincipal");function li(e){let r=['realm="OAuth"',`resource_metadata="${qc(Dm(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${qc(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${qc(e.scope)}"`),`Bearer ${r.join(", ")}`}o(li,"buildGatewayBearerChallenge");function qc(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(qc,"sanitizeQuotedHeaderParameter");me();me();function Gm(e){return new A({message:e,extensionMembers:{[T]:"invalid_request"}})}o(Gm,"invalidReturnTo");function pi(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw Gm("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 Gm("returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}o(pi,"parseSafeRelativeReturnTo");me();var bb=["user","shared"],Mn=u.enum(bb);function yr(e){return{mode:"user",subjectId:e}}o(yr,"buildUserUpstreamConnectionOwner");function mi(){return{mode:"shared"}}o(mi,"buildSharedUpstreamConnectionOwner");var Vm=u.object({ownerMode:Mn,initiatedBySubjectId:ve,ownerSubjectId:ve.optional(),upstreamServerId:We,authProfileId:Ye,virtualServerId:Ee,returnTo:u.string().min(1).transform(e=>pi(e)).optional()});function Fm(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(Fm,"validateUpstreamOwnerState");var zn=Vm.superRefine(Fm),Zm=Vm.omit({returnTo:!0}).superRefine(Fm);function Uo(e){return zn.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(Uo,"buildUpstreamOwnerState");function $n(e){if(e.ownerMode==="shared")return mi();if(!e.ownerSubjectId)throw new A({message:"User-owned upstream state is missing the owner subject.",extensionMembers:{[T]:"oauth_state_invalid"}});return yr(e.ownerSubjectId)}o($n,"resolveUpstreamConnectionOwnerFromState");var Rb=["active","not_connected","reconsent_required"],Cb=["basic_auth_app_password","bearer_token"],Km=u.string().trim().min(1).brand(),qn=u.uuid().brand(),Oo=u.uuid().brand(),Dc=u.enum(Rb),Ib=u.enum(Cb),Jm=u.object({encryptedClientInformation:u.string().optional(),encryptedDiscoveryState:u.string().optional(),connectedBySubjectId:ve.optional()}),Pb=Jm.extend({encryptedStaticSecret:u.string().optional(),staticSecretKind:Ib.optional(),staticSecretLabel:u.string().min(1).optional(),staticSecretUsername:u.string().min(1).optional()}).strict(),xb=u.object({id:Km,subjectId:ve.optional(),ownerMode:Mn,upstreamServerId:We,authProfileId:Ye,status:Dc,encryptedAccessToken:u.string().min(1).optional(),encryptedRefreshToken:u.string().min(1).optional(),scopes:u.array(u.string()),expiresAt:X.optional(),metadata:Pb.optional(),createdAt:X,updatedAt:X});function jc(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(jc,"validateUpstreamConnectionOwnerShape");var Nn=xb.superRefine(jc);function Sr(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}o(Sr,"readUpstreamConnectionLookupKey");var Hc=zn.extend({id:qn,callbackPath:u.string().min(1),expiresAt:X,codeVerifier:u.string().optional(),redirectUri:u.url(),returnOrigin:u.url().optional()}).extend(Jm.shape);function Wm(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o(Wm,"readUpstreamConnectionStatus");function fi(){return Km.parse(`mcpgw2uc_${crypto.randomUUID()}`)}o(fi,"createUpstreamConnectionId");function Ym(){return qn.parse(crypto.randomUUID())}o(Ym,"createOAuthStateId");function Xm(){return Oo.parse(crypto.randomUUID())}o(Xm,"createBrowserConnectTicketId");me();var Bc=u.discriminatedUnion("mode",[u.object({mode:u.literal("user"),subjectId:ve}).strict(),u.object({mode:u.literal("shared")}).strict()]),ef=u.object({owner:Bc,upstreamServerId:We,authProfileId:Ye}).strict(),tf=u.object({items:u.array(ef).min(1).max(100)}).strict(),Gc=u.object({items:u.array(u.object({key:u.object({ownerMode:Mn,subjectId:ve.optional(),upstreamServerId:We,authProfileId:Ye}).strict(),connection:Nn.strict().optional()}).strict())}).strict(),rf=Nn.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(jc),nf=Nn.strict(),of=u.object({owner:Bc,upstreamServerId:We,authProfileId:Ye}).strict(),af=u.object({owner:Bc,upstreamServerId:We,authProfileId:Ye,connection:Nn.strict().optional(),connectionStatus:u.object({connected:u.boolean(),status:Dc,updatedAt:Nn.shape.updatedAt.optional()}).strict()}).strict(),Ab=u.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]),Jr=u.object({clientId:Ue,clientName:u.string().min(1),tokenEndpointAuthMethod:Ab}).strict(),Vc=u.discriminatedUnion("method",[u.object({method:u.literal("none"),clientId:Ue}).strict(),u.object({method:u.enum(["client_secret_basic","client_secret_post"]),clientId:Ue,clientSecretHashInput:u.string().min(1)}).strict(),u.object({method:u.literal("private_key_jwt"),clientId:Ue}).strict()]),Fc=u.object({id:at,currentStateHash:u.string().min(1),clientId:Ue,redirectUri:u.string().min(1),resource:u.string().min(1),virtualServerId:Ee,clientState:u.string().optional(),scope:u.string(),codeChallenge:u.string().min(1),codeChallengeMethod:u.literal("S256"),setupApprovedAt:X.optional(),createdAt:X,expiresAt:X,consumedAt:X.optional()}).strict(),Qm=Fc.omit({id:!0,consumedAt:!0}).extend({transactionId:at,client:Jr.optional()}).strict(),Zc=u.object({subjectId:ve,roles:u.array(u.string()).optional()}).strict(),kb=Fc.extend({phase:u.literal("awaiting_login")}).strict(),Lc=Fc.extend({phase:u.literal("awaiting_setup"),principal:Zc}).strict(),Tb=u.discriminatedUnion("phase",[kb,Lc]),hi=u.object({transaction:Tb,client:Jr}).strict(),sf=Tc.omit({revokedAt:!0}).strict(),cf=u.discriminatedUnion("kind",[u.object({kind:u.literal("registered"),client:Jr}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),uf=u.object({clientId:Ue}).strict(),df=u.discriminatedUnion("kind",[u.object({kind:u.literal("found"),client:Tc.strict()}).strict(),u.object({kind:u.literal("missing")}).strict()]),lf=u.discriminatedUnion("phase",[Qm.extend({phase:u.literal("awaiting_login")}).strict(),Qm.extend({phase:u.literal("awaiting_setup"),principal:Zc}).strict()]),pf=u.discriminatedUnion("kind",[hi.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()]),mf=u.object({transactionId:at,currentStateHash:u.string().min(1),now:X}).strict(),ff=u.discriminatedUnion("kind",[hi.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()]),hf=u.object({transactionId:at,expectedPhase:u.literal("awaiting_login"),currentStateHash:u.string().min(1),nextStateHash:u.string().min(1),nextPhase:u.literal("awaiting_setup"),principal:Zc,now:X}).strict(),gf=u.discriminatedUnion("kind",[hi.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()]),yf=u.object({transactionId:at,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),now:X}).strict(),Sf=u.discriminatedUnion("kind",[hi.extend({kind:u.literal("marked")}).strict(),u.object({kind:u.literal("wrong_phase"),current:u.enum(["awaiting_login","awaiting_setup"])}).strict(),u.object({kind:u.literal("principal_mismatch")}).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()]),_f=u.discriminatedUnion("decision",[u.object({decision:u.literal("approve"),transactionId:at,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),authorizationCodeHash:u.string().min(1),authorizationCodeExpiresAt:X,grantId:Eo,now:X}).strict(),u.object({decision:u.literal("cancel"),transactionId:at,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),now:X}).strict()]),vf=u.discriminatedUnion("kind",[u.object({kind:u.literal("approved"),transaction:Lc,client:Jr}).strict(),u.object({kind:u.literal("cancelled"),transaction:Lc,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()]),wf=u.object({clientAuth:Vc,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:X,accessTokenExpiresAt:X,now:X}).strict(),bf=u.discriminatedUnion("kind",[u.object({kind:u.literal("exchanged"),client:Jr,grant:Uc.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()]),Rf=u.object({clientAuth:Vc,currentRefreshTokenHash:u.string().min(1),nextRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),resource:u.string().min(1).optional(),accessTokenExpiresAt:X,now:X}).strict(),Cf=u.discriminatedUnion("kind",[u.object({kind:u.literal("rotated"),client:Jr,grant:Uc.strict(),accessToken:ui.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("previous_token_grace")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),If=u.object({clientAuth:Vc,tokenHash:u.string().min(1),now:X}).strict(),Pf=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()]),xf=u.object({tokenHash:u.string().min(1),now:X}).strict(),Af=u.discriminatedUnion("kind",[u.object({kind:u.literal("valid"),record:ui.strict()}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),kf=u.object({accessTokenHash:u.string().min(1),resource:u.string().min(1),virtualServerId:Ee,upstreamConnectionKeys:u.array(ef).max(100),now:X}).strict(),Tf=u.discriminatedUnion("kind",[u.object({kind:u.literal("authorized"),principal:u.object({subjectId:ve,roles:u.array(u.string())}).strict(),accessToken:ui.strict(),upstreamConnections:Gc.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()]),Ef=u.object({record:Hc}).strict(),Uf=u.object({kind:u.literal("saved")}).strict(),Of=u.object({id:qn,now:X}).strict(),Mf=u.discriminatedUnion("kind",[u.object({kind:u.literal("available"),record:Hc}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict()]),zf=u.object({id:Oo,expiresAt:X,now:X}).strict(),$f=u.discriminatedUnion("kind",[u.object({kind:u.literal("available")}).strict(),u.object({kind:u.literal("consumed")}).strict()]);var qf=100,Eb=new Set(["undefined","null","nan"]);function Nf(e){return e!==null&&typeof e=="object"}o(Nf,"isProblemDetailsShape");var Ub="/zups/v2/mcp/storage";function Oe(e){return`${Ub}/${e}`}o(Oe,"buildStoragePath");function Ob(){return Oe("upstream-connections/batch-get")}o(Ob,"buildBatchGetUpstreamConnectionsPath");function Mb(){return Oe("upstream-connections/upsert")}o(Mb,"buildUpsertUpstreamConnectionPath");function zb(){return Oe("authorization/read-setup")}o(zb,"buildReadAuthorizationSetupPath");function $b(){return Oe("oauth/register-client")}o($b,"buildRegisterClientPath");function qb(){return Oe("oauth/read-client")}o(qb,"buildReadClientPath");function Nb(){return Oe("authorization/start")}o(Nb,"buildStartAuthorizationPath");function Db(){return Oe("authorization/read-pending")}o(Db,"buildReadPendingAuthorizationPath");function jb(){return Oe("authorization/advance-pending")}o(jb,"buildAdvancePendingAuthorizationPath");function Hb(){return Oe("authorization/mark-setup-approved")}o(Hb,"buildMarkAuthorizationSetupApprovedPath");function Lb(){return Oe("authorization/decide-setup")}o(Lb,"buildDecideAuthorizationSetupPath");function Bb(){return Oe("token/exchange-authorization-code")}o(Bb,"buildExchangeAuthorizationCodePath");function Gb(){return Oe("token/refresh")}o(Gb,"buildRefreshTokenPath");function Vb(){return Oe("token/revoke")}o(Vb,"buildRevokeOAuthTokenPath");function Fb(){return Oe("token/validate-access-token")}o(Fb,"buildValidateAccessTokenPath");function Zb(){return Oe("mcp/authorize-and-load-connections")}o(Zb,"buildAuthorizeAndLoadConnectionsPath");function Kb(){return Oe("upstream-oauth-state/save")}o(Kb,"buildSaveUpstreamOAuthStatePath");function Jb(){return Oe("upstream-oauth-state/consume")}o(Jb,"buildConsumeUpstreamOAuthStatePath");function Wb(){return Oe("browser-connect-ticket/consume")}o(Wb,"buildConsumeBrowserConnectTicketPath");function Yb(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(Yb,"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 Hf(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(Hf,"connectionMatchesLookup");function Qb(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??"")&&Wc(e.scopes,t.scopes)&&Jc(e.expiresAt,t.expiresAt)&&eR(e.metadata,t.metadata)}o(Qb,"connectionMatchesUpsertRecord");function Jc(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}o(Jc,"optionalTimestampInstantsMatch");function Df(e,t){return Date.parse(e)<=Date.parse(t)}o(Df,"timestampInstantIsAtOrBefore");function Wc(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}o(Wc,"stringArraysMatch");function eR(e,t){let r=jf(e),n=jf(t),a=Object.fromEntries(n);return r.length===n.length&&r.every(([i,s])=>a[i]===s)}o(eR,"metadataMatches");function jf(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}o(jf,"definedMetadataEntries");function we(e,t){throw Mo("internal_server_error",e,t)}o(we,"throwInvalidStorageResponse");function Mo(e,t,r){let n=bt[e],a=n.status<500,i=a?r:new Error(t,r===void 0?void 0:{cause:r});return new A({message:a?t:n.publicDetail,extensionMembers:{[T]:e}},i===void 0?void 0:{cause:i})}o(Mo,"storageRuntimeError");async function tR(e,t){try{let r=await e.json();return r&&typeof r=="object"&&!Array.isArray(r)&&delete r.$schema,t.parse(r)}catch(r){we("Gateway Service storage response did not match the runtime storage contract.",r)}}o(tR,"parseRuntimeHttpStorageResponse");function Lf(e,t){e.length!==t.length&&we("Gateway Service storage response item count did not match the request.");for(let[r,n]of e.entries()){let a=t[r];Yb(n.key,a)||we("Gateway Service storage response key did not match the request."),n.connection!==void 0&&!Hf(n.connection,a)&&we("Gateway Service storage response connection did not match the response key.")}}o(Lf,"validateUpstreamConnectionItemsMatchLookups");function rR(e,t){Xb(e,t)||we("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!Hf(e.connection,t)&&we("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||!Jc(e.connectionStatus.updatedAt,a))&&we("Gateway Service storage response authorization setup status did not match the connection.")}o(rR,"validateAuthorizationSetupResponseMatchesLookup");function nR(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&we("Gateway Service storage response registered client did not match the request.")}o(nR,"validateRegisterClientResponseMatchesRequest");function oR(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&we("Gateway Service storage response client did not match the request.")}o(oR,"validateReadClientResponseMatchesRequest");function aR(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)&&we("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)&&we("Gateway Service storage response started authorization principal did not match the request."))}o(aR,"validateStartAuthorizationResponseMatchesRequest");function Kc(e,t){e.kind!=="available"&&e.kind!=="advanced"&&e.kind!=="marked"||((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==("nextStateHash"in t?t.nextStateHash:t.currentStateHash))&&we("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)&&we("Gateway Service storage response advanced authorization did not match the request."),"currentPrincipal"in t&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&we("Gateway Service storage response marked authorization principal did not match the request."),e.kind==="marked"&&"currentPrincipal"in t&&e.transaction.setupApprovedAt!==t.now&&we("Gateway Service storage response marked authorization setup approval timestamp did not match the request."))}o(Kc,"validatePendingAuthorizationResponseMatchesRequest");function iR(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)&&we("Gateway Service storage response authorization setup transaction did not match the request.")}o(iR,"validateAuthorizationSetupDecisionResponseMatchesRequest");function sR(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||!Jc(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&we("Gateway Service storage response authorization-code exchange did not match the request.")}o(sR,"validateExchangeAuthorizationCodeResponseMatchesRequest");function cR(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)&&we("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!Df(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!Df(e.accessToken.expiresAt,e.grant.expiresAt)||!lR(e.accessToken,e.grant))&&we("Gateway Service storage response token refresh access token did not match the request."))}o(cR,"validateRefreshTokenResponseMatchesRequest");function uR(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&we("Gateway Service storage response access token did not match the request.")}o(uR,"validateAccessTokenValidationResponseMatchesRequest");function dR(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||!Wc(e.principal.roles,e.accessToken.roles))&&we("Gateway Service storage response MCP authorization did not match the request."),Lf(e.upstreamConnections,t.upstreamConnectionKeys))}o(dR,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function lR(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.virtualServerId===t.virtualServerId&&e.subjectId===t.subjectId&&e.scope===t.scope&&Wc(e.roles,t.roles)}o(lR,"accessTokenMatchesGrant");async function pR(e){try{return await e.clone().json()}catch{return}}o(pR,"readProblemDetails");async function mR(e){let t=await pR(e),r=Nf(t)&&typeof t.status=="number"?t.status:e.status,n=Nf(t)&&Wt(t.code)?t.code:Am(r);throw Mo(n,`Gateway Service storage request failed with HTTP ${r}.`)}o(mR,"throwRuntimeHttpStorageError");var gi=class{static{o(this,"RuntimeHttpStorageClient")}#t;#r;constructor(t){this.#t=t.baseUrl??xo.instance.zuploEdgeApiUrl,this.#r=t.fetch??fetch}#n(t){let r;try{r=new URL(t,this.#t)}catch(n){throw Mo("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 Mo("internal_server_error",`Gateway Service storage base URL must use http(s); got protocol "${r.protocol}" from ${JSON.stringify(this.#t)}.`);if(!r.hostname||Eb.has(r.hostname))throw Mo("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"});sm(a);let i=await this.#r(n,{method:"POST",headers:a,body:JSON.stringify(r)});return i.ok||await mR(i),{request:r,response:await tR(i,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],n=new Map,a=t.map(s=>{let c=Sr(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+=qf){let c=r.slice(s,s+qf);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:Mb(),requestSchema:rf,responseSchema:nf});return Qb(n,r)||we("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:zb(),requestSchema:of,responseSchema:af});return rR(n,r),n}async registerClient(t){let{request:r,response:n}=await this.#e({input:t,path:$b(),requestSchema:sf,responseSchema:cf});return nR(n,r),n}async readClient(t){let{request:r,response:n}=await this.#e({input:t,path:qb(),requestSchema:uf,responseSchema:df});return oR(n,r),n}async startAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:Nb(),requestSchema:lf,responseSchema:pf});return aR(n,r),n}async readPendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:Db(),requestSchema:mf,responseSchema:ff});return Kc(n,r),n}async advancePendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:jb(),requestSchema:hf,responseSchema:gf});return Kc(n,r),n}async markAuthorizationSetupApproved(t){let{request:r,response:n}=await this.#e({input:t,path:Hb(),requestSchema:yf,responseSchema:Sf});return Kc(n,r),n}async decideAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:Lb(),requestSchema:_f,responseSchema:vf});return iR(n,r),n}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:Kb(),requestSchema:Ef,responseSchema:Uf});return r}async consumeUpstreamOAuthState(t){let{request:r,response:n}=await this.#e({input:t,path:Jb(),requestSchema:Of,responseSchema:Mf});return n.kind==="available"&&n.record.id!==r.id&&we("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:Wb(),requestSchema:zf,responseSchema:$f});return r}async exchangeAuthorizationCode(t){let{request:r,response:n}=await this.#e({input:t,path:Bb(),requestSchema:wf,responseSchema:bf});return sR(n,r),n}async refreshToken(t){let{request:r,response:n}=await this.#e({input:t,path:Gb(),requestSchema:Rf,responseSchema:Cf});return cR(n,r),n}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:Vb(),requestSchema:If,responseSchema:Pf});return r}async validateAccessToken(t){let{request:r,response:n}=await this.#e({input:t,path:Fb(),requestSchema:xf,responseSchema:Af});return uR(n,r),n}async authorizeAndLoadConnections(t){let{request:r,response:n}=await this.#e({input:t,path:Zb(),requestSchema:kf,responseSchema:Tf});return dR(n,r),n}async#o(t){let r={items:[...t]},{response:n}=await this.#e({input:r,path:Ob(),requestSchema:tf,responseSchema:Gc});return Lf(n.items,t),n.items.map(a=>a.connection)}};var fR="__zuploMcpGatewayStorageBackend",Yc;function hR(){return new gi({})}o(hR,"buildProductionStorageBackend");function W(){let e=globalThis[fR];return e||(Yc||(Yc=hR()),Yc)}o(W,"getStorage");function gR(e,t){let r=Nc(e),n=Ao(e),a=t.ownerMode??t.routeBinding?.ownerMode,i=t.upstreamAuthMode??t.routeBinding?.authMode,s=t.virtualServerName??t.routeBinding?.virtualServerId??n?.virtualServerId,c=t.upstreamServerName??t.routeBinding?.upstreamServerId??n?.upstreamServerId,d=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName,p=t.authProfileId??t.routeBinding?.authProfileId??n?.authProfileId;return ym(e,{...t,subjectId:r?.subjectId,ownerMode:a,upstreamAuthMode:i,virtualServerName:s,upstreamServerName:c,upstreamServerTitle:d,authProfileId:p})}o(gR,"buildMcpAnalyticsMetadata");function K(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,gR(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(K,"emitMcpAnalyticsEvent");import{base64url as Xc}from"jose";var yR="sha256:",SR=32;function Bf(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Bf,"copyToArrayBuffer");function Yt(){let e=crypto.getRandomValues(new Uint8Array(SR));return Xc.encode(e)}o(Yt,"createOpaqueToken");async function fe(e){let t=await crypto.subtle.digest("SHA-256",Bf(new TextEncoder().encode(e)));return`${yR}${Xc.encode(new Uint8Array(t))}`}o(fe,"hashOpaqueValue");async function Gf(e){let t=await crypto.subtle.digest("SHA-256",Bf(new TextEncoder().encode(e)));return Xc.encode(new Uint8Array(t))}o(Gf,"calculatePkceS256Challenge");function Qc(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(Qc,"readBearerToken");function _R(e,t,r){return Ct(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(_R,"gatewayAuthenticationRequiredResponse");function vR(e){switch(e){case"expired":return"expired_token";case"revoked":return"revoked_token";case"missing":return"invalid_token";default:{let t=e;return"invalid_token"}}}o(vR,"tokenValidationReasonCode");async function wR(e,t,r){let n=await W().validateAccessToken({tokenHash:await fe(e),now:oe(new Date)});if(n.kind!=="valid"){t.log.warn({event:"gateway_access_token_validate_failed",code:"authentication_required",validationKind:n.kind,virtualServerId:r},"Gateway access token validation failed");let a=vR(n.kind);throw K(t,{eventType:F.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r,reasonClass:"auth",reasonCode:a,attributes:{validationKind:n.kind}}),K(t,{eventType:F.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r,httpStatusCode:401,reasonClass:"auth",reasonCode:a}),D("authentication_required","Gateway access token is expired, revoked, or invalid.")}return n.record}o(wR,"validateGatewayAccessToken");function bR(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"),K(t,{eventType:F.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:e.virtualServerId,reasonClass:"auth",reasonCode:"invalid_audience"}),K(t,{eventType:F.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:e.virtualServerId,httpStatusCode:401,reasonClass:"auth",reasonCode:"invalid_audience"}),D("authentication_required","Gateway access token was not issued for this MCP resource.")}o(bR,"assertAccessTokenResource");function RR(e,t,r){return Ct(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":li({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${_e} scope required by this MCP resource.`,scope:_e})}})}o(RR,"insufficientScopeResponse");function CR(e){return{subjectId:e.subjectId,roles:e.roles}}o(CR,"principalFromAccessToken");function IR(e){let t=Rt(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"),Ct(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":li({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(IR,"gatewayTokenRejectedResponse");async function eu(e,t){let r=Tn(t),n=gr(r.virtualServerId,e.url),a=Qc(e),i=li({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"),K(t,{eventType:F.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,httpStatusCode:401,reasonClass:"auth",reasonCode:"missing_token"}),_R(e,t,i);try{let s=await wR(a,t,r.virtualServerId);if(bR({accessToken:s,resource:n,virtualServerId:r.virtualServerId},t),s.scope!==_e)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:s.scope,requiredScope:_e,virtualServerId:r.virtualServerId,clientId:s.clientId},"Gateway access token does not have the required MCP scope"),K(t,{eventType:F.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,reasonClass:"auth",reasonCode:"insufficient_scope",attributes:{tokenScope:s.scope,requiredScope:_e,clientId:s.clientId}}),K(t,{eventType:F.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,httpStatusCode:403,reasonClass:"auth",reasonCode:"insufficient_scope"}),RR(e,t,r.virtualServerId);let c=CR(s);return Bm(t,c),xc(t,c),K(t,{eventType:F.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",virtualServerName:r.virtualServerId,attributes:{clientId:s.clientId}}),e}catch(s){return IR({request:e,context:t,error:s,virtualServerId:r.virtualServerId})}}o(eu,"gatewayTokenInbound");var Dn={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},PR="oauth-protected-resource-metadata",xR="/.well-known/oauth-protected-resource/";function AR(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}o(AR,"readRouteOperationId");function kR(e){return e.hasGatewayRouteContext?Dn.VIRTUAL_MCP_SERVER:e.routeOperationId===PR||e.routeOperationId===void 0&&e.routePath.startsWith(xR)?Dn.OAUTH_PROTECTED_RESOURCE_METADATA:Dn.OTHER}o(kR,"classifyAnalyticsRouteSurface");function TR(e){let t=e.route.path;return{routePath:t,routeSurface:kR({routePath:t,routeOperationId:AR(e),hasGatewayRouteContext:Ao(e)!==void 0})}}o(TR,"readAnalyticsRequestContext");function ER(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Dn.VIRTUAL_MCP_SERVER}o(ER,"isIntentionalMethodRejection");function UR(e){return ER(e)||e.response.status===401&&e.routeSurface===Dn.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(UR,"classifyRequestCompletedOutcome");async function tu(e,t){let r=Date.now(),n=TR(t);return K(t,{eventType:F.MCP_REQUEST_RECEIVED,outcome:"success",routeSurface:n.routeSurface,httpMethod:e.method}),Sc.getContextExtensions(t).addHandlerResponseHook(a=>{let i=UR({response:a,routeSurface:n.routeSurface});K(t,{eventType:F.MCP_REQUEST_COMPLETED,outcome:i,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(tu,"analyticsContextInbound");function OR(e){return e instanceof Response}o(OR,"isResponse");var Vf="/mcp/";function MR(e){let t=e.route.path;if(!t.startsWith(Vf))throw new $(`Route ${t} is bound to mcp-oauth-inbound but does not match the /mcp/{virtualServerId} convention.`);let r=t.slice(Vf.length);if(!r||r.includes("/"))throw new $(`Route ${t} is bound to mcp-oauth-inbound but must use exactly one /mcp/{virtualServerId} segment.`);return r}o(MR,"readVirtualServerIdFromRoute");async function zo(e,t){let n={virtualServerId:Ee.parse(MR(t))};_m(t,n),xm(t,n);let a=await tu(e,t);return OR(a)?a:eu(a,t)}o(zo,"mcpOAuthInboundPolicy");function yi(e,t,r){let n=e.safeParse(t);if(n.success)return n.data;throw new $(`${r} is misconfigured. Validation failed:
33
- ${zR(n.error)}`,{cause:n.error})}o(yi,"parseConfigOrThrow");function zR(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
34
- `)}o(zR,"formatZodIssues");var $R=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.'}),qR=u.object({auth0Domain:$R,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({error:"clientSecret is required and must be a string"}).trim().min(1,"clientSecret is required (commonly set via $env(AUTH0_CLIENT_SECRET))"),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(),ru=class extends kn{static{o(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,r){let n=Ff(t,r);super(n,r),this.#t=Kf(n,r)}async handler(t,r){return Ut("policy.inbound.mcp-auth0-oauth"),En(r,this.#t),zo(t,r)}};function Ff(e,t){return yi(qR,e,`MCP Auth0 OAuth policy "${t}"`)}o(Ff,"parseAuth0OAuthOptions");function Zf(e,t="mcp-auth0-oauth-inbound"){let r=Ff(e,t);return Kf(r,t)}o(Zf,"auth0OptionsToMcpOAuthRuntimeConfig");function Kf(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 Cm({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 $(`MCP Auth0 OAuth policy "${t}" is misconfigured. Check the policy options in policies.json.${c}`,s instanceof Error?{cause:s}:void 0)}}o(Kf,"buildAuth0McpOAuthRuntimeConfig");var nu=class extends kn{static{o(this,"McpOAuthInboundPolicy")}#t;constructor(t,r){let n=ou(t,r);super(n,r),this.#t=n}async handler(t,r){return Ut("policy.inbound.mcp-oauth"),En(r,this.#t),zo(t,r)}};function ou(e,t="mcp-oauth-inbound"){return yi(Rc,e,`MCP OAuth policy "${t}"`)}o(ou,"mcpOAuthOptionsToRuntimeConfig");var au=["mcp-oauth-inbound","mcp-auth0-oauth-inbound"],Jf={"mcp-oauth-inbound":"McpOAuthInboundPolicy","mcp-auth0-oauth-inbound":"McpAuth0OAuthInboundPolicy"};function NR(e,t,r){switch(e){case"mcp-oauth-inbound":return ou(r,t);case"mcp-auth0-oauth-inbound":return Zf(r,t);default:return}}o(NR,"parseMcpOAuthPolicyConfig");function Wf(e){return e!==void 0&&au.some(t=>t===e)}o(Wf,"isMcpOAuthInboundPolicyType");function iu(e){switch(e.policyType){case"mcp-oauth-inbound":return e.handler.export===Jf["mcp-oauth-inbound"];case"mcp-auth0-oauth-inbound":return e.handler.export===Jf["mcp-auth0-oauth-inbound"];default:return!1}}o(iu,"isMcpOAuthRuntimeConfigPolicy");function Yf(e){if(!e)return;let t=e.filter(iu);if(t.length>1){let a=t.map(i=>`"${i.name}" (${i.policyType})`).join(", ");throw new $(`MCP gateway found multiple OAuth policies in policies.json: ${a}. Use exactly one MCP OAuth policy for the gateway so internal OAuth routes resolve a single runtime config.`)}let r=t[0];if(!r)return;let n=NR(r.policyType,r.name,r.handler.options);if(!n)throw new $(`MCP gateway: policy '${r.name}' has unsupported MCP OAuth policy type '${r.policyType}'.`);return{policyName:r.name,config:n}}o(Yf,"resolveMcpOAuthRuntimeConfigFromPolicies");me();var _r="2025-11-25",Xf="2025-03-26",vr=[_r,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],wr="io.modelcontextprotocol/related-task",_i="2.0",xe=fm(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Qf=ye([f(),ne().int()]),eh=f(),yj=Pe({ttl:ne().optional(),pollInterval:ne().optional()}),jR=C({ttl:ne().optional()}),HR=C({taskId:f()}),su=Pe({progressToken:Qf.optional(),[wr]:HR.optional()}),it=C({_meta:su.optional()}),$o=it.extend({task:jR.optional()}),th=o(e=>$o.safeParse(e).success,"isTaskAugmentedRequestParams"),Me=C({method:f(),params:it.loose().optional()}),ht=C({_meta:su.optional()}),gt=C({method:f(),params:ht.loose().optional()}),ze=Pe({_meta:su.optional()}),vi=ye([f(),ne().int()]),rh=C({jsonrpc:O(_i),id:vi,...Me.shape}).strict(),Mt=o(e=>rh.safeParse(e).success,"isJSONRPCRequest"),nh=C({jsonrpc:O(_i),...gt.shape}).strict(),oh=o(e=>nh.safeParse(e).success,"isJSONRPCNotification"),cu=C({jsonrpc:O(_i),id:vi,result:ze}).strict(),It=o(e=>cu.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 uu=C({jsonrpc:O(_i),id:vi.optional(),error:C({code:ne().int(),message:f(),data:Re().optional()})}).strict();var Hn=o(e=>uu.safeParse(e).success,"isJSONRPCErrorResponse");var Wr=ye([rh,nh,cu,uu]),Sj=ye([cu,uu]),Qt=ze.strict(),LR=ht.extend({requestId:vi.optional(),reason:f().optional()}),wi=gt.extend({method:O("notifications/cancelled"),params:LR}),BR=C({src:f(),mimeType:f().optional(),sizes:R(f()).optional(),theme:ot(["light","dark"]).optional()}),qo=C({icons:R(BR).optional()}),jn=C({name:f(),title:f().optional()}),Ln=jn.extend({...jn.shape,...qo.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),GR=wc(C({applyDefaults:ce().optional()}),pe(f(),Re())),VR=bc(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,wc(C({form:GR.optional(),url:xe.optional()}),pe(f(),Re()).optional())),FR=Pe({list:xe.optional(),cancel:xe.optional(),requests:Pe({sampling:Pe({createMessage:xe.optional()}).optional(),elicitation:Pe({create:xe.optional()}).optional()}).optional()}),ZR=Pe({list:xe.optional(),cancel:xe.optional(),requests:Pe({tools:Pe({call:xe.optional()}).optional()}).optional()}),KR=C({experimental:pe(f(),xe).optional(),sampling:C({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:VR.optional(),roots:C({listChanged:ce().optional()}).optional(),tasks:FR.optional(),extensions:pe(f(),xe).optional()}),JR=it.extend({protocolVersion:f(),capabilities:KR,clientInfo:Ln}),bi=Me.extend({method:O("initialize"),params:JR}),du=o(e=>bi.safeParse(e).success,"isInitializeRequest"),WR=C({experimental:pe(f(),xe).optional(),logging:xe.optional(),completions:xe.optional(),prompts:C({listChanged:ce().optional()}).optional(),resources:C({subscribe:ce().optional(),listChanged:ce().optional()}).optional(),tools:C({listChanged:ce().optional()}).optional(),tasks:ZR.optional(),extensions:pe(f(),xe).optional()}),lu=ze.extend({protocolVersion:f(),capabilities:WR,serverInfo:Ln,instructions:f().optional()}),Ri=gt.extend({method:O("notifications/initialized"),params:ht.optional()}),ah=o(e=>Ri.safeParse(e).success,"isInitializedNotification"),Ci=Me.extend({method:O("ping"),params:it.optional()}),YR=C({progress:ne(),total:be(ne()),message:be(f())}),XR=C({...ht.shape,...YR.shape,progressToken:Qf}),Ii=gt.extend({method:O("notifications/progress"),params:XR}),QR=it.extend({cursor:eh.optional()}),No=Me.extend({params:QR.optional()}),Do=ze.extend({nextCursor:eh.optional()}),eC=ot(["working","input_required","completed","failed","cancelled"]),jo=C({taskId:f(),status:eC,ttl:ye([ne(),pm()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:be(ne()),statusMessage:be(f())}),er=ze.extend({task:jo}),tC=ht.merge(jo),Ho=gt.extend({method:O("notifications/tasks/status"),params:tC}),Pi=Me.extend({method:O("tasks/get"),params:it.extend({taskId:f()})}),xi=ze.merge(jo),Ai=Me.extend({method:O("tasks/result"),params:it.extend({taskId:f()})}),_j=ze.loose(),ki=No.extend({method:O("tasks/list")}),Ti=Do.extend({tasks:R(jo)}),Ei=Me.extend({method:O("tasks/cancel"),params:it.extend({taskId:f()})}),ih=ze.merge(jo),sh=C({uri:f(),mimeType:be(f()),_meta:pe(f(),Re()).optional()}),ch=sh.extend({text:f()}),pu=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),uh=sh.extend({blob:pu}),Lo=ot(["user","assistant"]),Bn=C({audience:R(Lo).optional(),priority:ne().min(0).max(1).optional(),lastModified:dm.datetime({offset:!0}).optional()}),dh=C({...jn.shape,...qo.shape,uri:f(),description:be(f()),mimeType:be(f()),size:be(ne()),annotations:Bn.optional(),_meta:be(Pe({}))}),rC=C({...jn.shape,...qo.shape,uriTemplate:f(),description:be(f()),mimeType:be(f()),annotations:Bn.optional(),_meta:be(Pe({}))}),mu=No.extend({method:O("resources/list")}),fu=Do.extend({resources:R(dh)}),hu=No.extend({method:O("resources/templates/list")}),gu=Do.extend({resourceTemplates:R(rC)}),yu=it.extend({uri:f()}),nC=yu,Su=Me.extend({method:O("resources/read"),params:nC}),_u=ze.extend({contents:R(ye([ch,uh]))}),vu=gt.extend({method:O("notifications/resources/list_changed"),params:ht.optional()}),oC=yu,aC=Me.extend({method:O("resources/subscribe"),params:oC}),iC=yu,sC=Me.extend({method:O("resources/unsubscribe"),params:iC}),cC=ht.extend({uri:f()}),uC=gt.extend({method:O("notifications/resources/updated"),params:cC}),dC=C({name:f(),description:be(f()),required:be(ce())}),lC=C({...jn.shape,...qo.shape,description:be(f()),arguments:be(R(dC)),_meta:be(Pe({}))}),wu=No.extend({method:O("prompts/list")}),bu=Do.extend({prompts:R(lC)}),pC=it.extend({name:f(),arguments:pe(f(),f()).optional()}),Ru=Me.extend({method:O("prompts/get"),params:pC}),Cu=C({type:O("text"),text:f(),annotations:Bn.optional(),_meta:pe(f(),Re()).optional()}),Iu=C({type:O("image"),data:pu,mimeType:f(),annotations:Bn.optional(),_meta:pe(f(),Re()).optional()}),Pu=C({type:O("audio"),data:pu,mimeType:f(),annotations:Bn.optional(),_meta:pe(f(),Re()).optional()}),mC=C({type:O("tool_use"),name:f(),id:f(),input:pe(f(),Re()),_meta:pe(f(),Re()).optional()}),fC=C({type:O("resource"),resource:ye([ch,uh]),annotations:Bn.optional(),_meta:pe(f(),Re()).optional()}),hC=dh.extend({type:O("resource_link")}),xu=ye([Cu,Iu,Pu,hC,fC]),gC=C({role:Lo,content:xu}),Au=ze.extend({description:f().optional(),messages:R(gC)}),ku=gt.extend({method:O("notifications/prompts/list_changed"),params:ht.optional()}),yC=C({title:f().optional(),readOnlyHint:ce().optional(),destructiveHint:ce().optional(),idempotentHint:ce().optional(),openWorldHint:ce().optional()}),SC=C({taskSupport:ot(["required","optional","forbidden"]).optional()}),lh=C({...jn.shape,...qo.shape,description:f().optional(),inputSchema:C({type:O("object"),properties:pe(f(),xe).optional(),required:R(f()).optional()}).catchall(Re()),outputSchema:C({type:O("object"),properties:pe(f(),xe).optional(),required:R(f()).optional()}).catchall(Re()).optional(),annotations:yC.optional(),execution:SC.optional(),_meta:pe(f(),Re()).optional()}),Tu=No.extend({method:O("tools/list")}),Eu=Do.extend({tools:R(lh)}),br=ze.extend({content:R(xu).default([]),structuredContent:pe(f(),Re()).optional(),isError:ce().optional()}),vj=br.or(ze.extend({toolResult:Re()})),_C=$o.extend({name:f(),arguments:pe(f(),Re()).optional()}),Bo=Me.extend({method:O("tools/call"),params:_C}),Uu=gt.extend({method:O("notifications/tools/list_changed"),params:ht.optional()}),ph=C({autoRefresh:ce().default(!0),debounceMs:ne().int().nonnegative().default(300)}),Go=ot(["debug","info","notice","warning","error","critical","alert","emergency"]),vC=it.extend({level:Go}),Ou=Me.extend({method:O("logging/setLevel"),params:vC}),wC=ht.extend({level:Go,logger:f().optional(),data:Re()}),bC=gt.extend({method:O("notifications/message"),params:wC}),RC=C({name:f().optional()}),CC=C({hints:R(RC).optional(),costPriority:ne().min(0).max(1).optional(),speedPriority:ne().min(0).max(1).optional(),intelligencePriority:ne().min(0).max(1).optional()}),IC=C({mode:ot(["auto","required","none"]).optional()}),PC=C({type:O("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:R(xu).default([]),structuredContent:C({}).loose().optional(),isError:ce().optional(),_meta:pe(f(),Re()).optional()}),xC=vc("type",[Cu,Iu,Pu]),Si=vc("type",[Cu,Iu,Pu,mC,PC]),AC=C({role:Lo,content:ye([Si,R(Si)]),_meta:pe(f(),Re()).optional()}),kC=$o.extend({messages:R(AC),modelPreferences:CC.optional(),systemPrompt:f().optional(),includeContext:ot(["none","thisServer","allServers"]).optional(),temperature:ne().optional(),maxTokens:ne().int(),stopSequences:R(f()).optional(),metadata:xe.optional(),tools:R(lh).optional(),toolChoice:IC.optional()}),Mu=Me.extend({method:O("sampling/createMessage"),params:kC}),Yr=ze.extend({model:f(),stopReason:be(ot(["endTurn","stopSequence","maxTokens"]).or(f())),role:Lo,content:xC}),Vo=ze.extend({model:f(),stopReason:be(ot(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:Lo,content:ye([Si,R(Si)])}),TC=C({type:O("boolean"),title:f().optional(),description:f().optional(),default:ce().optional()}),EC=C({type:O("string"),title:f().optional(),description:f().optional(),minLength:ne().optional(),maxLength:ne().optional(),format:ot(["email","uri","date","date-time"]).optional(),default:f().optional()}),UC=C({type:ot(["number","integer"]),title:f().optional(),description:f().optional(),minimum:ne().optional(),maximum:ne().optional(),default:ne().optional()}),OC=C({type:O("string"),title:f().optional(),description:f().optional(),enum:R(f()),default:f().optional()}),MC=C({type:O("string"),title:f().optional(),description:f().optional(),oneOf:R(C({const:f(),title:f()})),default:f().optional()}),zC=C({type:O("string"),title:f().optional(),description:f().optional(),enum:R(f()),enumNames:R(f()).optional(),default:f().optional()}),$C=ye([OC,MC]),qC=C({type:O("array"),title:f().optional(),description:f().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:C({type:O("string"),enum:R(f())}),default:R(f()).optional()}),NC=C({type:O("array"),title:f().optional(),description:f().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:C({anyOf:R(C({const:f(),title:f()}))}),default:R(f()).optional()}),DC=ye([qC,NC]),jC=ye([zC,$C,DC]),HC=ye([jC,TC,EC,UC]),LC=$o.extend({mode:O("form").optional(),message:f(),requestedSchema:C({type:O("object"),properties:pe(f(),HC),required:R(f()).optional()})}),BC=$o.extend({mode:O("url"),message:f(),elicitationId:f(),url:f().url()}),GC=ye([LC,BC]),zu=Me.extend({method:O("elicitation/create"),params:GC}),VC=ht.extend({elicitationId:f()}),FC=gt.extend({method:O("notifications/elicitation/complete"),params:VC}),Rr=ze.extend({action:ot(["accept","decline","cancel"]),content:bc(e=>e===null?void 0:e,pe(f(),ye([f(),ne(),ce(),R(f())])).optional())}),ZC=C({type:O("ref/resource"),uri:f()});var KC=C({type:O("ref/prompt"),name:f()}),JC=it.extend({ref:ye([KC,ZC]),argument:C({name:f(),value:f()}),context:C({arguments:pe(f(),f()).optional()}).optional()}),WC=Me.extend({method:O("completion/complete"),params:JC});var $u=ze.extend({completion:Pe({values:R(f()).max(100),total:be(ne().int()),hasMore:be(ce())})}),YC=C({uri:f().startsWith("file://"),name:f().optional(),_meta:pe(f(),Re()).optional()}),XC=Me.extend({method:O("roots/list"),params:it.optional()}),qu=ze.extend({roots:R(YC)}),QC=gt.extend({method:O("notifications/roots/list_changed"),params:ht.optional()}),wj=ye([Ci,bi,WC,Ou,Ru,wu,mu,hu,Su,aC,sC,Bo,Tu,Pi,Ai,ki,Ei]),bj=ye([wi,Ii,Ri,QC,Ho]),Rj=ye([Qt,Yr,Vo,Rr,qu,xi,Ti,er]),Cj=ye([Ci,Mu,zu,XC,Pi,Ai,ki,Ei]),Ij=ye([wi,Ii,bC,uC,vu,Uu,ku,Ho,FC]),Pj=ye([Qt,lu,$u,Au,bu,fu,gu,_u,br,Eu,xi,Ti,er]),I=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 Xt(a.elicitations,r)}return new e(t,r,n)}},Xt=class extends I{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??[]}};me();var hh=We,eI=u.object({mode:u.literal("auto")}).strict(),tI=u.object({mode:u.literal("manual"),clientId:u.string().trim().min(1),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:Cc.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"]})}),gh=u.discriminatedUnion("mode",[eI,tI]),rI=gh.default({mode:"auto"}),Nu=u.object({scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:rI}).strict(),mh=Nu.extend({redirectPath:u.string().startsWith("/auth/connections/")}).strict(),yh=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),nI=new Set([...yh,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),oI=u.object({kind:u.literal("bearer_token"),token:u.string().min(1)}).strict(),aI=u.object({kind:u.literal("headers"),headers:u.array(u.object({name:ni,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();yh.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)}}),Du=u.discriminatedUnion("kind",[oI,aI]),iI=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(),sI=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key"),capture:u.enum(["browser_login"]).optional()}).strict(),ju=u.discriminatedUnion("kind",[iI,sI]),Hu=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key")}).strict(),cI=u.discriminatedUnion("mode",[u.object({mode:u.literal("shared-oauth"),oauth:mh}).strict(),u.object({mode:u.literal("user-oauth"),oauth:mh}).strict(),u.object({mode:u.literal("static-secret"),secret:Du}).strict(),u.object({mode:u.literal("user-secret"),secret:ju}).strict(),u.object({mode:u.literal("shared-secret"),secret:Hu}).strict()]),uI=u.object({baseUrl:u.url(),resourceMetadataUrl:u.url(),requestHeaders:u.array(Ic).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let i=a.name.toLowerCase();nI.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)}}),Oj=u.object({displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:Ln.optional(),authProfiles:u.record(Ye,cI),transport:uI}).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"]})}),dI=u.object({"shared-oauth":Nu.optional(),"user-oauth":Nu.optional(),"static-secret":u.object({secret:Du}).strict().optional(),"user-secret":u.object({secret:ju}).strict().optional(),"shared-secret":u.object({secret:Hu}).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"})}),fh=u.object({id:hh,displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:Ln.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url(),requestHeaders:u.array(Ic).default([]),authProfiles:dI}).strict(),lI=u.object({name:ni,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict(),Ui={id:hh.optional(),displayName:u.string().min(1),summary:u.string().min(1).optional(),serverInfo:Ln.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url().optional(),requestHeaders:u.array(lI).default([])},pI=u.discriminatedUnion("authMode",[u.object({...Ui,authMode:u.enum(["shared-oauth","user-oauth"]),scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:gh.optional(),clientId:u.string().trim().min(1).optional(),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:Cc.optional()}).strict(),u.object({...Ui,authMode:u.literal("static-secret"),secret:Du}).strict(),u.object({...Ui,authMode:u.literal("user-secret"),secret:ju}).strict(),u.object({...Ui,authMode:u.literal("shared-secret"),secret:Hu}).strict()]);function mI(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
35
- `)}o(mI,"formatZodIssues");function Sh(e){throw new $(e)}o(Sh,"throwGatewayConfigError");function fI(e){let t="mcp-upstream-";return e.startsWith(t)||Sh(`Upstream policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`),We.parse(e.slice(t.length))}o(fI,"inferUpstreamConnectionIdFromPolicyName");function hI(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}o(hI,"buildDefaultProtectedResourceMetadataUrl");function Gn(e,t){return Ye.parse(`${e}:${t}`)}o(Gn,"buildUpstreamAuthProfileId");function Oi(e,t){try{let r=fh.safeParse(e);if(r.success)return r.data;let n=pI.parse(e),a=n.id??(t===void 0?void 0:fI(t));a===void 0&&Sh("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 fh.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??hI(n.mcpUrl),requestHeaders:i,authProfiles:s})}catch(r){if(r instanceof u.ZodError){let n=t===void 0?"MCP upstream policy":`Policy "${t}"`;throw new $(`${n} is misconfigured. Missing/invalid options in policies.json:
36
- ${mI(r)}`,{cause:r})}throw r}}o(Oi,"parseUpstreamConnectionPolicyOptions");function _h(e){return e.mode==="shared-oauth"||e.mode==="user-oauth"}o(_h,"isUpstreamOAuthAuthConfig");me();var gI=u.looseObject({name:u.string().min(1),version:u.string().min(1).optional()}),yI=u.looseObject({}),SI=u.looseObject({name:hr,namespace:hr.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional(),inputSchema:yI}),_I=u.looseObject({name:hr,namespace:hr.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional()}),vI=u.looseObject({name:hr,uri:u.string().min(1),upstreamPolicy:u.string().min(1).optional(),upstreamUri:u.string().min(1).optional(),enabled:u.boolean().optional()}),wI=u.enum(["openapi","upstream_mcp"]),bI=u.object({catalogSource:wI.default("openapi"),serverInfo:gI.optional(),tools:u.array(SI).default([]),prompts:u.array(_I).default([]),resources:u.array(vI).default([])}).strict();function RI(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
37
- `)}o(RI,"formatZodIssues");function vh(e,t){let r=bI.safeParse(e??{});if(!r.success){let n=t===void 0?"MCP virtual server route":`MCP virtual server route ${t}`;throw new $(`${n} is misconfigured. Missing/invalid handler options in routes.oas.json:
38
- ${RI(r.error)}`,{cause:r.error})}return r.data}o(vh,"parseVirtualServerRouteOptions");function Mi(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Mi,"toMcpTool");function zi(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(zi,"toMcpPrompt");function $i(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o($i,"toMcpResource");var CI="mcp-upstream-connection-inbound",wh="/mcp/";function Ae(e){throw new $(e)}o(Ae,"throwRegistryError");function II(e,t,r){let n=new $(t,r===void 0?void 0:{cause:r});return n.extensionMembers={[T]:e},n}o(II,"configurationProblem");function PI(e){return e.policyType===CI}o(PI,"isUpstreamConnectionPolicy");function xI(e){return Wf(e.policyType)}o(xI,"isMcpOAuthInboundPolicy");function AI(e){return e instanceof $?e:new $(e instanceof Error?e.message:"MCP virtual server route is misconfigured.",e instanceof Error?{cause:e}:void 0)}o(AI,"toRouteConfigurationError");function kI(e){e.startsWith(wh)||Ae(`MCP virtual server route ${e} must use a /mcp/{virtualServerId} path.`);let t=e.slice(wh.length);return(!t||t.includes("/"))&&Ae(`MCP virtual server route ${e} must use exactly one /mcp/{virtualServerId} path segment.`),Ee.parse(t)}o(kI,"readVirtualServerIdFromPath");function TI(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&Ae(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&Ae(`Upstream policy ${e.policyName} does not declare an auth mode.`),ri.parse(r)}o(TI,"readSingleAuthMode");function EI(e){let t=`/auth/connections/${encodeURIComponent(e.connection.id)}/callback`;switch(e.authMode){case"shared-oauth":{let r=e.connection.authProfiles["shared-oauth"];return r||Ae(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:e.authMode,oauth:{scopes:r.scopes,scopeDelimiter:r.scopeDelimiter,redirectPath:t,clientRegistration:r.clientRegistration}}}case"user-oauth":{let r=e.connection.authProfiles["user-oauth"];return r||Ae(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:e.authMode,oauth:{scopes:r.scopes,scopeDelimiter:r.scopeDelimiter,redirectPath:t,clientRegistration:r.clientRegistration}}}case"static-secret":{let r=e.connection.authProfiles["static-secret"];return r||Ae(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:"static-secret",secret:r.secret}}case"user-secret":{let r=e.connection.authProfiles["user-secret"];return r||Ae(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:"user-secret",secret:r.secret}}case"shared-secret":{let r=e.connection.authProfiles["shared-secret"];return r||Ae(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:"shared-secret",secret:r.secret}}}}o(EI,"buildResolvedAuthConfig");function UI(e){let t=TI({policyName:e.policyName,connection:e.connection}),r=Gn(e.connection.id,t),n=EI({connection:e.connection,authMode:t}),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(UI,"buildRegisteredConnection");function OI(e){let t=new Map;for(let r of e)t.has(r.name)&&Ae(`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(OI,"buildPolicyMap");function MI(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(MI,"readOperationId");function bh(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`,r=hr.safeParse(t);return r.success||Ae(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`),r.data}o(bh,"buildPublishedCapabilityName");function Gu(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||Ae(`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;Ae(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o(Gu,"readCapabilityUpstreamPolicy");function Lu(e){e.seen.has(e.key)&&Ae(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(Lu,"assertUniqueCatalogKey");function zI(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=bh({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:Gu({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(zI,"normalizeCatalogTool");function $I(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=bh({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:Gu({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o($I,"normalizeCatalogPrompt");function qI(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:Gu({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o(qI,"normalizeCatalogResource");function NI(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>zI({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>$I({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>qI({resource:d,connections:e.connections,routePath:e.routePath})),i=new Set;for(let d of r)Lu({kind:"tool",key:d.name,routePath:e.routePath,seen:i});let s=new Set;for(let d of n)Lu({kind:"prompt",key:d.name,routePath:e.routePath,seen:s});let c=new Set;for(let d of a)Lu({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(NI,"normalizeVirtualServerCatalog");function DI(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=Oi(c.handler.options,c.name);a.has(p.id)&&Ae(`Duplicate upstream MCP connection id ${p.id} in policies.json.`),a.add(p.id);let l=UI({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||!xI(l))continue;let m=MI(c),h;try{h=kI(c.path),m||Ae(`MCP virtual server route ${c.path} must declare an operationId in routes.oas.json.`),i.has(m)&&Ae(`Duplicate MCP virtual server operationId ${m} across routes.`),t.has(h)&&Ae(`Duplicate MCP virtual server id ${h} across routes.`);let g=[];for(let _ of d.slice(1)){let v=e.policyByName.get(_);!v||!PI(v)||g.push(s(v))}let S=vh(c.handler.options,c.path),y=NI({catalog:S,connections:g,routePath:c.path});y.catalogSource==="upstream_mcp"&&g.length!==1&&Ae(`MCP virtual server route ${c.path} uses upstream MCP catalog mode but declares ${g.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:y.serverInfo,catalog:y,connections:g}),i.add(m)}catch(g){h!==void 0&&r.set(h,AI(g))}}return{byVirtualServerId:t,virtualServerErrorsById:r,connectionsByPolicyName:n}}o(DI,"buildVirtualServers");function Vu(e){let t=OI(e.policies),{byVirtualServerId:r,virtualServerErrorsById:n,connectionsByPolicyName:a}=DI({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(Vu,"buildGatewayConnectionRegistry");var Xr,Bu;function Rh(e){Bu=e,Xr=void 0}o(Rh,"configureGatewayConnectionRegistrySource");function Ch(e){Xr=e}o(Ch,"setGatewayConnectionRegistry");function st(){if(!Xr&&Bu&&(Xr=Vu(Bu)),!Xr)throw new $("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 Xr}o(st,"getGatewayConnectionRegistry");function Kr(e){let t=st(),r=t.virtualServerErrorsById?.get(e);if(r)throw r;let n=t.byVirtualServerId.get(e);if(!n)throw II("unknown_virtual_server",`Unknown MCP virtual server: ${e}`,new Error(`Unknown MCP virtual server "${e}". Ensure routes.oas.json declares an MCP route for this virtual server and policies.json registers the matching MCP upstream connection policy.`));return n}o(Kr,"getRegisteredVirtualServer");function Ih(){return Xr}o(Ih,"tryGetGatewayConnectionRegistry");function Le(e){let t=st().connectionsById.get(e);if(!t)throw new $(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return t.config}o(Le,"getUpstreamServerConfig");function jI(e){let t=st().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new $(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authProfileId}o(jI,"resolveUpstreamAuthProfileId");function Cr(e){jI(e);let t=st().connectionsById.get(e.upstreamServerId);if(!t)throw new $(`Auth profile could not be resolved for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares the upstream connection before this handler runs.`);return t.authConfig}o(Cr,"getUpstreamAuthConfig");function Qr(e,t){let r=Cr({upstreamServerId:e,authProfileId:t});if(!_h(r))throw new $(`Upstream server "${e}" does not use upstream OAuth. Select an auth mode that supports the requested upstream connect flow or remove the upstream OAuth route for this server.`);return r.oauth}o(Qr,"requireUpstreamOAuthConfig");function zt(e){return new A({message:e,extensionMembers:{[T]:"invalid_request"}})}o(zt,"invalidOutboundUrl");function HI(){let e=ti.__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(HI,"isTestOnlyAllowHttpLoopbackIdpEnabled");function LI(){let e=ti.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD;return typeof e=="string"&&e==="1"}o(LI,"isTestOnlyAllowHttpLoopbackCimdEnabled");var BI=new Set(["undefined","null","nan"]);function Zu(e,t){if(!e.hostname)throw zt(`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(BI.has(e.hostname.toLowerCase()))throw zt(`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(Zu,"assertSafeOutboundHostname");var GI=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),VI=[{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 Ph(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(Ph,"parseIpv4Octets");function FI([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(FI,"ipv4RangeMatches");function xh(e){let t=Ph(e);return t!==void 0&&VI.some(r=>FI(t,r))}o(xh,"isPrivateIpv4");function Fu(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(Fu,"parseIpv6Word");function ZI(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(ZI,"formatIpv4FromWords");function KI(e){let t=e.slice(7),r=Ph(t);if(r!==void 0)return r.join(".");let[n,a,i]=t.split(":"),s=Fu(n),c=Fu(a);return i===void 0&&s!==void 0&&c!==void 0?ZI(s,c):void 0}o(KI,"parseIpv6MappedIpv4");function JI(e){return Fu(e.split(":").find(Boolean))}o(JI,"readFirstIpv6Hextet");function WI(e){let t=Kt(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=KI(t);return n===void 0||xh(n)}let r=JI(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(WI,"isPrivateIpv6");function Ku(e){let t=Kt(e);return GI.has(t)||t.endsWith(".internal")||xh(t)||WI(t)}o(Ku,"isBlockedOutboundHostname");function Ah(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw zt(`Unsupported outbound protocol: ${t.protocol}`);Zu(t,e);let r=ke(t);if(t.protocol==="http:"&&!r)throw zt("Configured outbound HTTP URLs must target loopback hosts.");let n=Kt(t.hostname);if(!r&&Ku(n))throw zt(`Blocked outbound host: ${n}`);return t}o(Ah,"validateConfiguredOutboundUrl");function kh(e){let t=new URL(e),r=ke(t),n=r&&HI();if(t.protocol!=="https:"&&!n)throw zt("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw zt("Identity provider URLs must not include credentials, query params, or fragments.");Zu(t,e);let a=Kt(t.hostname);if(!r&&Ku(a))throw zt(`Blocked identity provider host: ${a}`);return t}o(kh,"validateIdentityProviderUrl");function Th(e,t){let r=new URL(e),n=r.protocol==="http:"&&ke(r)&&LI();if(r.protocol!=="https:"&&!n||r.pathname==="/"||r.username||r.password||r.search||r.hash)throw zt(`CIMD ${t} must be an HTTPS URL with a path and no credentials, query, or fragment.`);if(Zu(r,e),!n&&Ku(r.hostname))throw zt(`CIMD ${t} points at a blocked host.`);return r}o(Th,"validateCimdUrl");function qi(e){return Th(e,"client_id")}o(qi,"validateCimdClientMetadataUrl");function Eh(e){return Th(e,"jwks_uri")}o(Eh,"validateCimdClientJwksUrl");function Uh(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(Uh,"mergeAbortSignals");async function YI(e){try{await e.cancel()}catch{}}o(YI,"cancelReader");async function Ni(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 YI(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(Ni,"readBoundedByteStream");var XI=2,QI=1024*1024,eP=1e4,tP=new Set([301,302,303,307,308]),rP=["authorization","proxy-authorization","cookie","cookie2"];function Ju(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(Ju,"readRequestUrl");function Vn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Vn,"readRequestMethod");function nP(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 new A({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[T]:r}})}o(nP,"assertContentLengthWithinLimit");async function oP(e,t,r){return nP(e,t,r),Ni(e.body,{maxBytes:t,createLimitError:o(()=>new A({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[T]:r}}),"createLimitError")})}o(oP,"readBoundedResponseBody");function aP(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(aP,"responseFromBufferedBody");function iP(e,t){if(!tP.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(iP,"resolveRedirectUrl");function Oh(e,t){try{return t.validateUrl(e)}catch(r){throw new A({message:"Outbound URL was not allowed.",extensionMembers:{[T]:t.problemCode}},{cause:r})}}o(Oh,"validateOutboundUrl");function sP(e,t){throw e instanceof A&&Wt(e.extensionMembers?.[T])?e:new A({message:"Outbound fetch failed.",extensionMembers:{[T]:t}},{cause:e})}o(sP,"normalizeFetchError");function Fo(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&&Xe(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Fo,"logOutboundFailure");async function cP(e,t,r,n,a,i,s){let c=Vn(r,n);try{return await t(r,n)}catch(d){let p=d instanceof DOMException&&d.name==="AbortError";Fo(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:c,host:mt(i),error:d,extra:{abortReason:s()}}),sP(d,a)}}o(cP,"fetchWithNormalizedError");function uP(e){if(e.redirects>=e.maxRedirects)throw new A({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[T]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new A({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[T]:e.problemCode}})}o(uP,"assertRedirectAllowed");function dP(e,t){let r=new Headers(e);for(let n of rP)r.delete(n);for(let n of t)r.delete(n);return r}o(dP,"stripCrossOriginHeaders");function lP(e,t,r,n,a){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=dP(e.headers,a)),i}o(lP,"buildRedirectInit");function pP(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(pP,"buildInitialRequestInit");function mP(e){let t=Vn(e.currentInput,e.currentInit);uP({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Oh(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:lP(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(mP,"followRedirect");async function Wu(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??XI,i=r.maxResponseBytes??QI,s=r.timeoutMs??eP,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],p=r.context,l=new AbortController,m=Uh(l,t.signal),h=!1,g=setTimeout(()=>{h=!0,l.abort()},s),S=e,y=pP(e,t,l.signal),_;try{_=Oh(Ju(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(w){throw Fo(p,{event:"outbound_url_blocked",problemCode:n,method:Vn(e,t),host:mt(Ju(e)),error:w}),clearTimeout(g),m?.(),w}let v=0;try{for(;;){let w=await cP(p,c,S,y,n,_,()=>h?`timeout_after_${s}ms`:void 0),b=iP(w,_);if(b!==void 0)try{let N=mP({currentInput:S,currentInit:y,currentUrl:_,redirectUrl:b,redirects:v,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:l.signal,additionalCrossOriginStrippedHeaders:d});S=N.currentInput,y=N.currentInit,_=N.currentUrl,v=N.redirects;continue}catch(N){throw Fo(p,{event:"outbound_redirect_blocked",problemCode:n,method:Vn(S,y),host:mt(_),error:N,extra:{redirects:v,maxRedirects:a,redirectTargetHost:mt(b)}}),N}try{return aP(w,await oP(w,i,n))}catch(N){throw Fo(p,{event:"outbound_response_size_exceeded",problemCode:n,method:Vn(S,y),host:mt(_),error:N,extra:{maxResponseBytes:i,status:w.status}}),N}}}finally{clearTimeout(g),m?.()}}o(Wu,"runSafeOutboundExchange");async function Di(e,t,r){let n=await Wu(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw Fo(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Vn(e,t),host:mt(Ju(e)),error:a,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),new A({message:"Outbound JSON response could not be parsed.",extensionMembers:{[T]:r.problemCode??"invalid_request"}},{cause:a})}}o(Di,"runSafeOutboundJsonExchange");function Fn(e,t={},r={}){return Wu(e,t,{...r,validateUrl:Ah})}o(Fn,"fetchConfiguredOutbound");function Mh(e,t={},r={}){return Di(e,t,{...r,validateUrl:kh})}o(Mh,"fetchIdentityProviderJson");function zh(e,t={},r={}){return Di(e,t,{...r,validateUrl:qi})}o(zh,"fetchCimdClientMetadataJson");function $h(e,t={},r={}){return Di(e,t,{...r,validateUrl:Eh})}o($h,"fetchCimdClientJwksJson");var fP={"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 fP[e]}o($t,"describeUpstreamAuthMode");function ji(e){return $t(e).ownerMode}o(ji,"resolveOwnerModeForUpstreamAuthMode");me();import{errors as Gh,jwtVerify as Vh,SignJWT as Fh}from"jose";var Qe="zuplo-mcp-gateway",ct=Qe,ut="HS256";import{base64url as hP}from"jose";var gP=new TextEncoder,yP="MCP gateway could not initialize secure key material.",SP=32,qh=new Map,Nh=new Map,_P;function vP(){return _P??xo.instance.authPrivateKey}o(vP,"readAuthPrivateKey");function Dh(e){return new A(yP,e===void 0?void 0:{cause:e})}o(Dh,"createGeneratedKeyMaterialError");function jh(e,t){let r=hP.decode(t);if(r.byteLength!==SP)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(jh,"decodeJwkKeyField");function wP(e){let t=vP();if(!t)throw Dh();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=jh("d",r.d);jh("x",r.x);let a=gP.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 Dh(r)}}o(wP,"decodeGeneratedKeyMaterial");function bP(e){let t=qh.get(e);return t||(t=wP(e),qh.set(e,t)),t}o(bP,"getMasterKeyMaterial");async function qt(e){let t=Nh.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(bP(e.keyMaterialPurpose));return Nh.set(e.purpose,r),r}o(qt,"readCachedDerivedKey");var RP="SHA-256";var CP="zuplo-mcp-gateway:",IP=new TextEncoder,Hh=new WeakMap;async function Ir(e,t){let r=Hh.get(e);r||(r=new Map,Hh.set(e,r));let n=r.get(t);if(n)return n;let a=await PP(e,t);return r.set(t,a),a}o(Ir,"deriveGatewaySigningKey");async function PP(e,t){let r=Lh(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=IP.encode(`${CP}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:RP,salt:new Uint8Array,info:Lh(a)},n,32*8);return new Uint8Array(i)}o(PP,"hkdfExpand");function Lh(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Lh,"copyToArrayBuffer");var Zh=15*60,xP=15*60,AP=Zm.extend({id:qn}),kP=AP.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),Kh=zn.extend({id:Oo,purpose:u.literal("browser_connect")}),TP=zn.extend({purpose:u.literal("browser_connect")}),EP=Kh.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),Jh=Zh*1e3;async function Wh(){return qt({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"oauth-state"),"derive")})}o(Wh,"getOAuthStateKey");async function Yh(){return qt({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"browser-connect"),"derive")})}o(Yh,"getBrowserConnectKey");async function Xh(e){let t=Math.floor(Date.now()/1e3)+Zh;return new Fh(e).setProtectedHeader({alg:ut,typ:"JWT"}).setIssuer(Qe).setAudience(ct).setIssuedAt().setExpirationTime(t).sign(await Wh())}o(Xh,"signOAuthState");async function Hi(e){try{let{payload:t}=await Vh(e,await Wh(),{algorithms:[ut],issuer:Qe,audience:ct});return kP.parse(t)}catch(t){throw t instanceof Gh.JWTExpired?new A({message:"OAuth state has expired",extensionMembers:{[T]:"oauth_state_expired"}},{cause:t}):new A({message:"OAuth state could not be verified",extensionMembers:{[T]:"oauth_state_invalid"}},{cause:t})}}o(Hi,"verifyOAuthState");async function Qh(e){let t=Math.floor(Date.now()/1e3)+xP,r=TP.parse(e),n=Kh.parse({...r,id:Xm()});return new Fh(n).setProtectedHeader({alg:ut,typ:"JWT"}).setIssuer(Qe).setAudience(ct).setIssuedAt().setExpirationTime(t).sign(await Yh())}o(Qh,"signBrowserConnectTicket");async function Li(e){try{let{payload:t}=await Vh(e,await Yh(),{algorithms:[ut],issuer:Qe,audience:ct});return EP.parse(t)}catch(t){throw t instanceof Gh.JWTExpired?new A({message:"Browser connect ticket has expired",extensionMembers:{[T]:"oauth_state_expired"}},{cause:t}):new A({message:"Browser connect ticket could not be verified",extensionMembers:{[T]:"oauth_state_invalid"}},{cause:t})}}o(Li,"verifyBrowserConnectTicket");async function Bi(e){if((await W().consumeBrowserConnectTicket({id:e.id,expiresAt:oe(new Date(e.exp*1e3)),now:oe(new Date)})).kind==="consumed")throw new A({message:"Browser connect ticket has already been used",extensionMembers:{[T]:"oauth_state_reused"}})}o(Bi,"consumeBrowserConnectTicket");function UP(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(UP,"buildConnectRequiredMessage");async function eg(e){let t=ue(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 Qh({...Uo(e),purpose:"browser_connect"})),r.toString()}o(eg,"buildGatewayBrowserTicketUrl");function OP(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(OP,"buildGatewayConnectPath");async function Yu(e){return eg({...e,path:OP(e.upstreamServerId),redirect:!0})}o(Yu,"buildGatewayConnectUrl");async function tg(e){return eg({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(tg,"buildGatewayAppPasswordCaptureUrl");async function Pr(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 Yu(t),message:UP(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Pr,"buildRedirectConnectRequiredResponse");function Gi(e){return rg({...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(Gi,"buildAdminConnectRequiredResponse");function rg(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(rg,"buildAdminSetupRequiredResponse");function ng(e){return rg({...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(ng,"buildAdminStaticSecretRequiredResponse");me();import{base64url as xr}from"jose";var MP="SHA-256",Kn="AES-GCM",zP=12,Qu="zuplo-secret",ed=1,og="generated:auth_private_key:token-encryption",$P=u.object({version:u.literal(ed),keyId:u.literal(og),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 Xu(){return qt({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(MP,Zn(e));return crypto.subtle.importKey("raw",t,{name:Kn},!1,["encrypt","decrypt"])},"derive")})}o(Xu,"getEncryptionKey");function ag(e){return Zn(new TextEncoder().encode(`${Qu}:v${e.version}:${e.keyId}`))}o(ag,"getAssociatedData");function qP(e){return`${Qu}:v${e.version}:${xr.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(qP,"encodeEnvelope");function NP(e){let t=`${Qu}:v${ed}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(xr.decode(r));return $P.parse(JSON.parse(n))}o(NP,"decodeEnvelope");async function en(e){let t=await Xu(),r=crypto.getRandomValues(new Uint8Array(zP)),n={version:ed,keyId:og},a=await crypto.subtle.encrypt({name:Kn,iv:r,additionalData:ag(n)},t,new TextEncoder().encode(e));return qP({...n,algorithm:Kn,iv:xr.encode(r),ciphertext:xr.encode(new Uint8Array(a))})}o(en,"encryptSecret");async function tr(e){let t=NP(e);if(t){let s=await Xu(),c=await crypto.subtle.decrypt({name:Kn,iv:Zn(xr.decode(t.iv)),additionalData:ag(t)},s,Zn(xr.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw new te("Encrypted payload is malformed");let a=await Xu(),i=await crypto.subtle.decrypt({name:Kn,iv:Zn(xr.decode(r))},a,Zn(xr.decode(n)));return new TextDecoder().decode(i)}o(tr,"decryptSecret");function DP(e,t){let r=Cr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-secret")throw new $(`Upstream server "${e}" does not use tenant static credentials. Select the shared-secret auth mode for this upstream connection or remove the tenant static credential route.`);return r.secret}o(DP,"requireTenantStaticSecretConfig");function ig(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(ig,"hasUsableTenantStaticSecret");async function jP(e){if(!ig(e.connection))throw new te("Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await tr(e.connection.metadata.encryptedStaticSecret)}}o(jP,"resolveTenantStaticSecretCredential");async function sg(e){let t=Le(e.upstreamServerId);DP(e.upstreamServerId,e.authProfileId);let r="preloadedConnection"in e?e.preloadedConnection:(await W().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(ig(r))return{kind:"authorized",credential:await jP({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:ng(n)}}o(sg,"resolveTenantStaticSecretCredentialForRequest");me();async function td(e){return W().upsertUpstreamConnection({id:fi(),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(td,"upsertStaticSecretConnection");var HP=u.string().trim().min(1).max(320),LP=u.string().min(1).max(4096),BP=u.string().trim().min(1).max(4096);function rd(e,t){let r=Cr({upstreamServerId:e,authProfileId:t});if(r.mode!=="user-secret")throw new $(`Upstream server "${e}" does not use user static credentials. Select the user-secret auth mode for this upstream connection or remove the user static credential route.`);return r.secret}o(rd,"requireUserStaticSecretConfig");function GP(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o(GP,"encodeBase64Utf8");function VP(e){return`Basic ${GP(`${e.username}:${e.appPassword}`)}`}o(VP,"buildBasicAuthHeader");function cg(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(cg,"hasEncryptedUserStaticSecret");async function FP(e){if(!cg(e.connection))throw new te("Stored user static credential is incomplete.");if(e.connection.metadata.staticSecretKind==="bearer_token")return{type:"bearer_token",token:await tr(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:VP({username:e.connection.metadata.staticSecretUsername,appPassword:await tr(e.connection.metadata.encryptedStaticSecret)})}};throw new te("Stored user static credential kind is unsupported.")}o(FP,"resolveUserStaticSecretCredential");async function ug(e){if(rd(e.upstreamServerId,e.authProfileId).kind!=="basic_auth_app_password")throw new te("This upstream does not use username and app-password credentials.");if(e.owner.mode!=="user")throw new te("User static credentials must be stored under a user-owned connection.");let r=HP.parse(e.username),n=LP.parse(e.appPassword);return td({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await en(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(ug,"saveUserStaticSecretCredential");async function Vi(e){let t=rd(e.upstreamServerId,e.authProfileId);if(t.kind!=="bearer_token")throw new te("This upstream does not use bearer token credentials.");if(e.owner.mode!=="user")throw new te("User static credentials must be stored under a user-owned connection.");let r=BP.parse(e.token);return td({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await en(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(Vi,"saveUserStaticBearerTokenCredential");function nd(e,t){return rd(e,t)}o(nd,"readUserStaticSecretCaptureConfig");async function dg(e){let t=Le(e.upstreamServerId);if(e.owner.mode!=="user")throw new te("User static credential flow resolved a non-user owner.");let r="preloadedConnection"in e?e.preloadedConnection:(await W().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(cg(r))return{kind:"authorized",credential:await FP({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 Pr(n)}}o(dg,"resolveUserStaticSecretCredentialForRequest");function lg(e){if(e.owner.mode!=="user")throw new te("User static credential capture requires a user-owned connection.");return tg({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(lg,"buildUserStaticSecretConnectUrl");var od;od=globalThis.crypto;async function ZP(e){return(await od).getRandomValues(new Uint8Array(e))}o(ZP,"getRandomValues");async function KP(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await ZP(e-n.length);for(let i of a)i<r&&(n+=t[i%t.length])}return n}o(KP,"random");async function JP(e){return await KP(e)}o(JP,"generateVerifier");async function WP(e){let t=await(await od).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(WP,"generateChallenge");async function ad(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await JP(e),r=await WP(t);return{code_verifier:t,code_challenge:r}}o(ad,"pkceChallenge");me();var $e=lm().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:hm.custom,message:"URL must be parseable",fatal:!0}),um}).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"}),Fi=Pe({resource:f().url(),authorization_servers:R($e).optional(),jwks_uri:f().url().optional(),scopes_supported:R(f()).optional(),bearer_methods_supported:R(f()).optional(),resource_signing_alg_values_supported:R(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:ce().optional(),authorization_details_types_supported:R(f()).optional(),dpop_signing_alg_values_supported:R(f()).optional(),dpop_bound_access_tokens_required:ce().optional()}),Zo=Pe({issuer:f(),authorization_endpoint:$e,token_endpoint:$e,registration_endpoint:$e.optional(),scopes_supported:R(f()).optional(),response_types_supported:R(f()),response_modes_supported:R(f()).optional(),grant_types_supported:R(f()).optional(),token_endpoint_auth_methods_supported:R(f()).optional(),token_endpoint_auth_signing_alg_values_supported:R(f()).optional(),service_documentation:$e.optional(),revocation_endpoint:$e.optional(),revocation_endpoint_auth_methods_supported:R(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:R(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:R(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:R(f()).optional(),code_challenge_methods_supported:R(f()).optional(),client_id_metadata_document_supported:ce().optional()}),YP=Pe({issuer:f(),authorization_endpoint:$e,token_endpoint:$e,userinfo_endpoint:$e.optional(),jwks_uri:$e,registration_endpoint:$e.optional(),scopes_supported:R(f()).optional(),response_types_supported:R(f()),response_modes_supported:R(f()).optional(),grant_types_supported:R(f()).optional(),acr_values_supported:R(f()).optional(),subject_types_supported:R(f()),id_token_signing_alg_values_supported:R(f()),id_token_encryption_alg_values_supported:R(f()).optional(),id_token_encryption_enc_values_supported:R(f()).optional(),userinfo_signing_alg_values_supported:R(f()).optional(),userinfo_encryption_alg_values_supported:R(f()).optional(),userinfo_encryption_enc_values_supported:R(f()).optional(),request_object_signing_alg_values_supported:R(f()).optional(),request_object_encryption_alg_values_supported:R(f()).optional(),request_object_encryption_enc_values_supported:R(f()).optional(),token_endpoint_auth_methods_supported:R(f()).optional(),token_endpoint_auth_signing_alg_values_supported:R(f()).optional(),display_values_supported:R(f()).optional(),claim_types_supported:R(f()).optional(),claims_supported:R(f()).optional(),service_documentation:f().optional(),claims_locales_supported:R(f()).optional(),ui_locales_supported:R(f()).optional(),claims_parameter_supported:ce().optional(),request_parameter_supported:ce().optional(),request_uri_parameter_supported:ce().optional(),require_request_uri_registration:ce().optional(),op_policy_uri:$e.optional(),op_tos_uri:$e.optional(),client_id_metadata_document_supported:ce().optional()}),Zi=C({...YP.shape,...Zo.pick({code_challenge_methods_supported:!0}).shape}),Ko=C({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:gm.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),mg=C({error:f(),error_description:f().optional(),error_uri:f().optional()}),pg=$e.optional().or(O("").transform(()=>{})),XP=C({redirect_uris:R($e),token_endpoint_auth_method:f().optional(),grant_types:R(f()).optional(),response_types:R(f()).optional(),client_name:f().optional(),client_uri:$e.optional(),logo_uri:pg,scope:f().optional(),contacts:R(f()).optional(),tos_uri:pg,policy_uri:f().optional(),jwks_uri:$e.optional(),jwks:mm().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),id=C({client_id:f(),client_secret:f().optional(),client_id_issued_at:ne().optional(),client_secret_expires_at:ne().optional()}).strip(),Jo=XP.merge(id),wL=C({error:f(),error_description:f().optional()}).strip(),bL=C({token:f(),token_type_hint:f().optional()}).strip();function fg(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(fg,"resourceUrlFromServerUrl");function hg({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(hg,"checkResourceAllowed");var Ce=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}},Wo=class extends Ce{static{o(this,"InvalidRequestError")}};Wo.errorCode="invalid_request";var tn=class extends Ce{static{o(this,"InvalidClientError")}};tn.errorCode="invalid_client";var rn=class extends Ce{static{o(this,"InvalidGrantError")}};rn.errorCode="invalid_grant";var nn=class extends Ce{static{o(this,"UnauthorizedClientError")}};nn.errorCode="unauthorized_client";var Yo=class extends Ce{static{o(this,"UnsupportedGrantTypeError")}};Yo.errorCode="unsupported_grant_type";var Xo=class extends Ce{static{o(this,"InvalidScopeError")}};Xo.errorCode="invalid_scope";var Qo=class extends Ce{static{o(this,"AccessDeniedError")}};Qo.errorCode="access_denied";var rr=class extends Ce{static{o(this,"ServerError")}};rr.errorCode="server_error";var ea=class extends Ce{static{o(this,"TemporarilyUnavailableError")}};ea.errorCode="temporarily_unavailable";var ta=class extends Ce{static{o(this,"UnsupportedResponseTypeError")}};ta.errorCode="unsupported_response_type";var ra=class extends Ce{static{o(this,"UnsupportedTokenTypeError")}};ra.errorCode="unsupported_token_type";var na=class extends Ce{static{o(this,"InvalidTokenError")}};na.errorCode="invalid_token";var oa=class extends Ce{static{o(this,"MethodNotAllowedError")}};oa.errorCode="method_not_allowed";var aa=class extends Ce{static{o(this,"TooManyRequestsError")}};aa.errorCode="too_many_requests";var on=class extends Ce{static{o(this,"InvalidClientMetadataError")}};on.errorCode="invalid_client_metadata";var ia=class extends Ce{static{o(this,"InsufficientScopeError")}};ia.errorCode="insufficient_scope";var sa=class extends Ce{static{o(this,"InvalidTargetError")}};sa.errorCode="invalid_target";var gg={[Wo.errorCode]:Wo,[tn.errorCode]:tn,[rn.errorCode]:rn,[nn.errorCode]:nn,[Yo.errorCode]:Yo,[Xo.errorCode]:Xo,[Qo.errorCode]:Qo,[rr.errorCode]:rr,[ea.errorCode]:ea,[ta.errorCode]:ta,[ra.errorCode]:ra,[na.errorCode]:na,[oa.errorCode]:oa,[aa.errorCode]:aa,[on.errorCode]:on,[ia.errorCode]:ia,[sa.errorCode]:sa};var Pt=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function QP(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(QP,"isClientAuthMethod");var sd="code",cd="S256";function ex(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&QP(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(ex,"selectClientAuthMethod");function tx(e,t,r,n){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":rx(a,i,r);return;case"client_secret_post":nx(a,i,n);return;case"none":ox(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(tx,"applyClientAuthentication");function rx(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(rx,"applyBasicAuth");function nx(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(nx,"applyPostAuth");function ox(e,t){t.set("client_id",e)}o(ox,"applyPublicAuth");async function Sg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=mg.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:s}=n,c=gg[a]||rr;return new c(i||"",s)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new rr(a)}}o(Sg,"parseErrorResponse");async function Ar(e,t){try{return await ud(e,t)}catch(r){if(r instanceof tn||r instanceof nn)return await e.invalidateCredentials?.("all"),await ud(e,t);if(r instanceof rn)return await e.invalidateCredentials?.("tokens"),await ud(e,t);throw r}}o(Ar,"auth");async function ud(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 vg(d,{fetchFn:i}),!c)try{c=await _g(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 b=await dx(t,{resourceMetadataUrl:l,fetchFn:i});d=b.authorizationServerUrl,p=b.authorizationServerMetadata,c=b.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let m=await ax(t,e,c),h=n||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,g=await Promise.resolve(e.clientInformation());if(!g){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let b=p?.client_id_metadata_document_supported===!0,N=e.clientMetadataUrl;if(N&&!ld(N))throw new on(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${N}`);if(b&&N)g={client_id:N},await e.saveClientInformation?.(g);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let He=await hx(d,{metadata:p,clientMetadata:e.clientMetadata,scope:h,fetchFn:i});await e.saveClientInformation(He),g=He}}let S=!e.redirectUrl;if(r!==void 0||S){let b=await fx(e,d,{metadata:p,resource:m,authorizationCode:r,fetchFn:i});return await e.saveTokens(b),"AUTHORIZED"}let y=await e.tokens();if(y?.refresh_token)try{let b=await mx(d,{metadata:p,clientInformation:g,refreshToken:y.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Ce)||b instanceof rr))throw b}let _=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:w}=await lx(d,{metadata:p,clientInformation:g,state:_,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(w),await e.redirectToAuthorization(v),"REDIRECT"}o(ud,"authInternal");function ld(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(ld,"isHttpsUrl");async function ax(e,t,r){let n=fg(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!hg({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(ax,"selectResourceURL");function pd(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=dd(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let s=dd(e,"scope")||void 0,c=dd(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}o(pd,"extractWWWAuthenticateParams");function dd(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(dd,"extractFieldFromWwwAuth");async function _g(e,t,r=fetch){let n=await cx(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 Fi.parse(await n.json())}o(_g,"discoverOAuthProtectedResourceMetadata");async function md(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?md(e,void 0,r):void 0;throw n}}o(md,"fetchWithCorsRetry");function ix(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(ix,"buildWellKnownPath");async function yg(e,t,r=fetch){return await md(e,{"MCP-Protocol-Version":t},r)}o(yg,"tryMetadataDiscovery");function sx(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(sx,"shouldAttemptFallback");async function cx(e,t,r,n){let a=new URL(e),i=n?.protocolVersion??_r,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let d=ix(t,a.pathname);s=new URL(d,n?.metadataServerUrl??a),s.search=a.search}let c=await yg(s,i,r);if(!n?.metadataUrl&&sx(c,a.pathname)){let d=new URL(`/.well-known/${t}`,a);c=await yg(d,i,r)}return c}o(cx,"discoverMetadataWithFallback");function ux(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(ux,"buildDiscoveryUrls");async function vg(e,{fetchFn:t=fetch,protocolVersion:r=_r}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=ux(e);for(let{url:i,type:s}of a){let c=await md(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"?Zo.parse(await c.json()):Zi.parse(await c.json())}}}o(vg,"discoverAuthorizationServerMetadata");async function dx(e,t){let r,n;try{r=await _g(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 vg(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o(dx,"discoverOAuthServerInfo");async function lx(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(sd))throw new Error(`Incompatible auth server: does not support response type ${sd}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(cd))throw new Error(`Incompatible auth server: does not support code challenge method ${cd}`)}else c=new URL("/authorize",e);let d=await ad(),p=d.code_verifier,l=d.code_challenge;return c.searchParams.set("response_type",sd),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",l),c.searchParams.set("code_challenge_method",cd),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(lx,"startAuthorization");function px(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(px,"prepareAuthorizationCodeRequest");async function wg(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=ex(n,l);tx(m,n,d,r)}let p=await(s??fetch)(c,{method:"POST",headers:d,body:r});if(!p.ok)throw await Sg(p);return Ko.parse(await p.json())}o(wg,"executeTokenRequest");async function mx(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 wg(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:s});return{refresh_token:n,...d}}o(mx,"refreshAuthorization");async function fx(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=px(a,p,e.redirectUrl)}let d=await e.clientInformation();return wg(t,{metadata:r,tokenRequestParams:c,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}o(fx,"fetchToken");async function hx(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 Sg(s);return Jo.parse(await s.json())}o(hx,"registerClient");me();function fd(e){return`Zuplo MCP Gateway - ${e}`}o(fd,"buildGatewayOAuthClientName");function bg(e,t){let r=new URL(e,ue(t));return ke(r)&&Kt(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(bg,"buildGatewayOAuthRedirectUri");function hd(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(hd,"buildOAuthClientMetadataDocumentUrl");function Rg(e){return ue(e)}o(Rg,"requireOAuthClientMetadataOrigin");function Cg(e,t,r){let n=Le(t),a=Qr(t,r);return{client_id:hd({origin:e,upstreamServerId:t,authProfileId:r}),client_name:fd(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(Cg,"buildOAuthClientMetadataDocument");var gx=u.union([Jo,id]),yx=u.object({authorizationServerUrl:u.url(),resourceMetadataUrl:u.url().optional(),resourceMetadata:Fi.optional(),authorizationServerMetadata:u.union([Zo,Zi]).optional()}).passthrough(),Sx="Bearer";function _x(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(_x,"splitScopes");function vx(e){return si.parse(e)}o(vx,"parsePkceCodeVerifier");function wx(e){if(typeof e.expires_in=="number")return oe(new Date(Date.now()+e.expires_in*1e3))}o(wx,"readTokenExpiry");async function Ig(e){if(e!==void 0)return en(JSON.stringify(e))}o(Ig,"encryptJson");async function Pg(e,t){if(!e)return;let r=await tr(e);try{return t.parse(JSON.parse(r))}catch(n){throw new A({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[T]:"oauth_state_invalid"}},{cause:n})}}o(Pg,"decryptJson");function bx(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(bx,"toOAuthDiscoveryState");function Rx(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(Rx,"clientInformationAllowsRedirectUri");function Cx(e,t,r){let n=Le(e),a=Qr(e,t),i;return a.scopes.length>0&&(i=a.scopes.join(a.scopeDelimiter)),{client_name:fd(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(Cx,"buildOAuthClientMetadata");function Ix(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new $(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return Jo.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(Ix,"buildManualOAuthClientInformation");function Px(e,t,r){let n=hd({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return ld(n)?n:void 0}o(Px,"buildClientMetadataUrl");function xg(e){for(let t of e)if(t!==void 0)return t}o(xg,"firstDefined");function xx(e){let t=Qr(e.target.upstreamServerId,e.target.authProfileId),r=Cx(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:Ix({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=Px(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(xx,"buildInitialOAuthClientSetup");function Ax(e,t){if(t===void 0)return xg([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(Ax,"readEncryptedClientInformation");function kx(e){return xg([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(kx,"readEncryptedDiscoveryState");var an=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=xx({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=Ax(t,this.configuredClientInformation),this.encryptedDiscoveryState=kx(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return Xh({id:t.id,...Uo({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 Ig(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Ig(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Ko.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??fi(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await en(r.access_token),encryptedRefreshToken:r.refresh_token?await en(r.refresh_token):void 0,scopes:_x(r.scope??this.clientMetadataValue.scope),expiresAt:wx(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await W().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:vx(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new A({message:"OAuth code verifier is missing",extensionMembers:{[T]:"oauth_state_invalid"}});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:Ym(),...Uo({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:oe(new Date(Date.now()+Jh)),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 W().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 Pg(this.encryptedClientInformation,gx)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!Rx(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=bx(await Pg(this.encryptedDiscoveryState,yx))}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=Ko.parse({access_token:await tr(this.connection.encryptedAccessToken),token_type:Sx,refresh_token:this.connection.encryptedRefreshToken?await tr(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 W().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var Tx=3e4,Ex=256*1024,Ux=2;function Ox(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(Ox,"hasUsableAccessToken");var Mx="does not support dynamic client registration";function zx(e){return e instanceof Error&&e.message.includes(Mx)}o(zx,"isDynamicClientRegistrationUnsupported");function $x(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o($x,"readOAuthFetchRequest");function qx(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(qx,"responseLooksJson");function Ag(e){return async(t,r)=>{let n=$x(t),a=await Fn(t,r,{maxRedirects:Ux,maxResponseBytes:Ex,problemCode:"upstream_token_exchange_failed",timeoutMs:Tx}),i=await a.clone().text();if(!qx(a,i))return a;try{JSON.parse(i)}catch(s){throw new A({message:`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[T]:"upstream_token_exchange_failed"}},{cause:s})}return a}}o(Ag,"createUpstreamOAuthFetch");async function kg(e,t){try{return await Ar(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ag(t.upstreamServerId)})}catch(r){throw zx(r)?new A({message:`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.`,extensionMembers:{[T]:"upstream_client_registration_required"}},{cause:r}):r}}o(kg,"runUpstreamOAuth");async function Nx(e,t){return Ar(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ag(t.upstreamServerId)})}o(Nx,"exchangeUpstreamAuthorizationCode");async function Tg(e,t){let r=await kg(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new A({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}}):new A({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}})}o(Tg,"requireUpstreamAuthorizationRedirect");async function Eg(e){if(Ox(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await kg(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 new A({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new A({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await Bx({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(Eg,"authorizeUpstreamOAuthSession");async function Dx(e){let t=await Hi(e.stateToken),r=await W().consumeUpstreamOAuthState({id:t.id,now:oe(new Date)}),n=jx(r);return Hx({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Lx(n),n}o(Dx,"consumeStoredCallbackState");function jx(e){switch(e.kind){case"consumed":throw new A({message:"OAuth state has already been used",extensionMembers:{[T]:"oauth_state_reused"}});case"missing":throw new A({message:"OAuth state is missing or expired",extensionMembers:{[T]:"oauth_state_expired"}});case"available":return e.record}}o(jx,"readConsumedCallbackState");function Hx(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 new A({message:"OAuth callback did not match the initiating request",extensionMembers:{[T]:"oauth_callback_mismatch"}})}o(Hx,"assertStoredCallbackStateMatches");function Lx(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new A({message:"OAuth state has expired",extensionMembers:{[T]:"oauth_state_expired"}})}o(Lx,"assertStoredCallbackStateFresh");async function Bx(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),Gi(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),Pr(t)}o(Bx,"buildOAuthConnectRequiredResponse");async function Ug(e){let t=await Dx({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=$n(t),[n]=await W().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 an(a),s=await Nx(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"?new A({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}}):new A({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}})}o(Ug,"finishUpstreamOAuthCallback");async function Og(e){let t=Le(e.upstreamServerId),r=Qr(e.upstreamServerId,e.authProfileId),n=bg(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await W().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:ue(e.request.url)}}}o(Og,"prepareUpstreamOAuthRequest");async function Mg(e){let t=await Og(e),r=new an({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Tg(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(Mg,"startUpstreamConnect");async function zg(e){let t=await Og(e),r=new an({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return Eg({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(zg,"authorizeUpstreamRequest");function Gx(e,t){switch(e.kind){case"bearer_token":{if(!e.token)throw new $(`Static bearer token is not configured for upstream "${t}". Set the env var that backs the token or update the upstream connection policy to use a configured secret.`);return{type:"bearer_token",token:e.token}}case"headers":{let r={};for(let n of e.headers){if(!n.value)throw new $(`Static header "${n.name}" is not configured for upstream "${t}". Set the env var that backs the header or mark the header optional.`);r[n.name]=n.value}return{type:"headers",headers:r}}}}o(Gx,"resolveStaticSecretCredential");async function Ki(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return zg({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 sg({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 new te(`Resolved static-secret credential context loaded ${n.mode} config.`);return{kind:"authorized",credential:Gx(n.secret,t.upstreamServerId)}}case"user-secret":return dg({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}})}let r=t;throw new te(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}o(Ki,"resolveUpstreamCredentialForRoute");async function $g(e){let t=yr(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 Vi({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o($g,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function qg(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 Mg(r);break;case"user_secret_capture":t=await lg(r);break;case"none":throw new te(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(qg,"startUpstreamConnectForRequest");async function Ng(e){let r=(await Hi(e.callbackRequest.state)).authProfileId,n=Cr({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if($t(n.mode).callbackSupport!=="authorization_code")throw new te(`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return Ug({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Le(e.callbackRequest.upstreamServerId)})}o(Ng,"finishUpstreamCallbackForRequest");var gd=new Ot("route-upstream-bindings");function Dg(e){return`${e.upstreamServerId}:${e.authProfileId}`}o(Dg,"buildRouteBindingDuplicateKey");function yd(e,t){let r=gd.get(e)??[],n=Dg(t);if(r.find(i=>Dg(i)===n)!==void 0)throw new te(`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.push(t),gd.set(e,r)}o(yd,"appendResolvedUpstreamBindingContext");function Ji(e){return gd.get(e)??[]}o(Ji,"readResolvedUpstreamBindingContexts");var Vx=new Set(["authorization","connection","content-length","cookie","cookie2","host","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),Fx=3e4,Zx=2*1024*1024,Kx=2,Sd="upstream_capability_invocation_failed",Jx="upstream_capability_unavailable";function Wx(e){return e.kind!=="authorized"||e.credential.type!=="headers"?[]:Object.keys(e.credential.headers)}o(Wx,"readCredentialHeaderNames");function Yx(e){let t=e.headers.get("retry-after");if(t!==null)return{"retry-after":t}}o(Yx,"readRetryAfterHeaders");function Xx(e,t,r){let n=Yx(r),a=Qx(r.status);return Ct(e,t,{code:a,headers:n})}o(Xx,"proxyUpstreamErrorResponse");function Qx(e){switch(e){case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";case 429:return"too_many_requests";case 503:return Jx;default:return"upstream_capability_invocation_failed"}}o(Qx,"readProxyProblemCode");async function eA(e,t){Ut("handler.mcp-upstream");let r=Ji(t);if(r.length!==1)throw new $(`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 Ki({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=Le(n.upstreamServerId),s=i.transport.baseUrl,c=new Headers;for(let[h,g]of e.headers.entries())Vx.has(h.toLowerCase())||c.set(h,g);let d=[];for(let h of i.transport.requestHeaders??[]){if(h.value===void 0){if(h.required)throw new $(`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,g]of Object.entries(p.headers))c.set(h,g);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,...Wx(a)],m={method:e.method,headers:c,body:e.method==="GET"||e.method==="HEAD"?void 0:e.body,duplex:"half"};t.log.info({event:"mcp_upstream_handler_proxy",upstreamServerId:n.upstreamServerId,upstreamUrl:s,method:e.method},"MCP upstream proxy: forwarding request");try{let h=await Fn(s,m,{additionalCrossOriginStrippedHeaders:l,context:t,maxRedirects:Kx,maxResponseBytes:Zx,problemCode:Sd,timeoutMs:Fx});return h.ok?h:Xx(e,t,h)}catch(h){if(!(h instanceof A)||h.extensionMembers?.[T]!==Sd)throw h;return Ct(e,t,{code:Sd})}}o(eA,"mcpUpstreamHandler");Zw();function kr(e){return!!e._zod}o(kr,"isZ4Schema");function Fe(e,t){return kr(e)?_c(e,t):e.safeParse(t)}o(Fe,"safeParse");function Jn(e){if(!e)return;let t;if(kr(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}o(Jn,"getObjectShape");function jg(e){if(kr(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(jg,"getLiteralValue");function Tr(e){return e==="completed"||e==="failed"||e==="cancelled"}o(Tr,"isTerminal");var rA=Symbol("Let zodToJsonSchema decide on which parser to use");var W2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _d(e){let r=Jn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=jg(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(_d,"getMethodLiteral");function vd(e,t){let r=Fe(e,t);if(!r.success)throw r.error;return r.data}o(vd,"parseWithCompat");var cA=6e4,Wn=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(wi,r=>{this._oncancel(r)}),this.setNotificationHandler(Ii,r=>{this._onprogress(r)}),this.setRequestHandler(Ci,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Pi,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new I(E.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(Ai,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 I(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 I(E.InvalidParams,`Task not found: ${i}`);if(!Tr(s.status))return await this._waitForTaskUpdate(i,n.signal),await a();if(Tr(s.status)){let c=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[wr]:{taskId:i}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(ki,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 I(E.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(Ei,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new I(E.InvalidParams,`Task not found: ${r.params.taskId}`);if(Tr(a.status))throw new I(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 I(E.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(a){throw a instanceof I?a:new I(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),I.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),It(i)||Hn(i)?this._onresponse(i):Mt(i)?this._onrequest(i,s):oh(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=I.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?.[wr]?.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=th(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 I(E.ConnectionClosed,"Request was cancelled");let g={...h,relatedRequestId:t.id};i&&!g.relatedTask&&(g.relatedTask={taskId:i});let S=g.relatedTask?.taskId??i;return S&&d&&await d.updateTaskStatus(S,"input_required"),await this.request(l,m,g)},"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),It(t))n(t);else{let s=new I(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(It(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),It(t))a(t);else{let s=I.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 I?s:new I(E.InternalError,String(s))}}return}let i;try{let s=await this.request(t,er,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new I(E.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},Tr(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new I(E.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new I(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 I?s:new I(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(w=>{l(w)},"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(w){m(w);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,g={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),g.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),c&&(g.params={...g.params,task:c}),d&&(g.params={...g.params,_meta:{...g.params?._meta||{},[wr]:d}});let S=o(w=>{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(w)}},{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(N=>this._onerror(new Error(`Failed to send cancellation: ${N}`)));let b=w instanceof I?w:new I(E.RequestTimeout,String(w));l(b)},"cancel");this._responseHandlers.set(h,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return l(w);try{let b=Fe(r,w.result);b.success?p(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{S(n?.signal?.reason)});let y=n?.timeout??cA,_=o(()=>S(I.fromError(E.RequestTimeout,"Request timed out",{timeout:y})),"timeoutHandler");this._setupTimeout(h,y,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let v=d?.taskId;if(v){let w=o(b=>{let N=this._responseHandlers.get(h);N?N(b):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))},"responseResolver");this._requestResolvers.set(h,w),this._enqueueTaskMessage(v,{type:"request",message:g,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(h),l(b)})}else this._transport.send(g,{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(w=>{this._cleanupTimeout(h),l(w)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},xi,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},Ti,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},ih,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||{},[wr]: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||{},[wr]: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||{},[wr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=_d(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,i)=>{let s=vd(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=_d(t);this._notificationHandlers.set(n,a=>{let i=vd(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"&&Mt(a.message)){let i=a.message.id,s=this._requestResolvers.get(i);s?(s(new I(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 I(E.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new I(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 I(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=Ho.parse({method:"notifications/tasks/status",params:c});await this.notification(d),Tr(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 I(E.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(Tr(c.status))throw new I(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=Ho.parse({method:"notifications/tasks/status",params:d});await this.notification(p),Tr(d.status)&&this._cleanupTaskProgressHandler(a)}},"updateTaskStatus"),listTasks:o(a=>n.listTasks(a,r),"listTasks")}}};function Hg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Hg,"isPlainObject");function Wi(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];Hg(s)&&Hg(i)?r[a]={...s,...i}:r[a]=i}return r}o(Wi,"mergeCapabilities");var x_=im(ap(),1),A_=im(P_(),1);function XU(){let e=new x_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,A_.default)(e),e}o(XU,"createDefaultAjvInstance");var fo=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??XU()}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 Os=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},Yr,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},Rr,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 Ms(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(Ms,"assertToolsCallTaskCapability");function zs(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(zs,"assertClientRequestTaskCapability");var $s=class extends Wn{static{o(this,"Server")}constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Go.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 fo,this.setRequestHandler(bi,n=>this._oninitialize(n)),this.setNotificationHandler(Ri,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ou,async(n,a)=>{let i=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,c=Go.safeParse(s);return c.success&&this._loggingLevels.set(i,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Os(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Wi(this._capabilities,t)}setRequestHandler(t,r){let a=Jn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(kr(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=Fe(Bo,d);if(!l.success){let S=l.error instanceof Error?l.error.message:String(l.error);throw new I(E.InvalidParams,`Invalid tools/call request: ${S}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let S=Fe(er,h);if(!S.success){let y=S.error instanceof Error?S.error.message:String(S.error);throw new I(E.InvalidParams,`Invalid task creation result: ${y}`)}return S.data}let g=Fe(br,h);if(!g.success){let S=g.error instanceof Error?g.error.message:String(g.error);throw new I(E.InvalidParams,`Invalid tools/call result: ${S}`)}return g.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){zs(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Ms(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:vr.includes(r)?r:_r,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"},Qt)}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},Vo,r):this.request({method:"sampling/createMessage",params:t},Yr,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},Rr,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},Rr,r);if(i.action==="accept"&&i.content&&a.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!c.valid)throw new I(E.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(s){throw s instanceof I?s:new I(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},qu,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 qs=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 L0={keyword:"dependencies",type:"object",schemaType:"object",error:Ft.error,code(e){let[t,r]=B0(e);BS(e,t),GS(e,r)}};function B0({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(B0,"splitDependencies");function BS(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,ja.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,ja.checkReportMissingProp)(e,p)}):(r.if((0,jl._)`${d} && (${(0,ja.checkMissingProp)(e,c,i)})`),(0,ja.reportMissingProp)(e,i),r.else())}}o(BS,"validatePropertyDeps");Ft.validatePropertyDeps=BS;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,H0.alwaysValidSchema)(i,t[c])||(r.if((0,ja.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");Ft.validateSchemaDeps=GS;Ft.default=L0});var ZS=x(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var FS=W(),G0=ie(),V0={message:"property name must be valid",params:o(({params:e})=>(0,FS._)`{propertyName: ${e.propertyName}}`,"params")},F0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:V0,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,G0.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,FS.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};Hl.default=F0});var Bl=x(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var xs=vt(),Et=W(),Z0=pr(),ks=ie(),K0={message:"must NOT have additional properties",params:o(({params:e})=>(0,Et._)`{additionalProperty: ${e.additionalProperty}}`,"params")},J0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:K0,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,ks.alwaysValidSchema)(s,r))return;let p=(0,xs.allSchemaProperties)(n.properties),l=(0,xs.allSchemaProperties)(n.patternProperties);m(),e.ok((0,Et._)`${i} === ${Z0.default.errors}`);function m(){t.forIn("key",a,_=>{!p.length&&!l.length?S(_):t.if(h(_),()=>S(_))})}o(m,"checkAdditionalProperties");function h(_){let v;if(p.length>8){let w=(0,ks.schemaRefOrVal)(s,n.properties,"properties");v=(0,xs.isOwnProperty)(t,w,_)}else p.length?v=(0,Et.or)(...p.map(w=>(0,Et._)`${_} === ${w}`)):v=Et.nil;return l.length&&(v=(0,Et.or)(v,...l.map(w=>(0,Et._)`${(0,xs.usePattern)(e,w)}.test(${_})`))),(0,Et.not)(v)}o(h,"isAdditional");function g(_){t.code((0,Et._)`delete ${a}[${_}]`)}o(g,"deleteAdditional");function S(_){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){g(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),c||t.break();return}if(typeof r=="object"&&!(0,ks.alwaysValidSchema)(s,r)){let v=t.name("valid");d.removeAdditional==="failing"?(y(_,v,!1),t.if((0,Et.not)(v),()=>{e.reset(),g(_)})):(y(_,v),c||t.if((0,Et.not)(v),()=>t.break()))}}o(S,"additionalPropertyCode");function y(_,v,w){let b={keyword:"additionalProperties",dataProp:_,dataPropType:ks.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,v)}o(y,"applyAdditionalSchema")}};Ll.default=J0});var WS=x(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var W0=Pa(),KS=vt(),Gl=ie(),JS=Bl(),Y0={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&&JS.default.code(new W0.KeywordCxt(i,JS.default,"additionalProperties"));let s=(0,KS.allSchemaProperties)(r);for(let m of s)i.definedProperties.add(m);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Gl.mergeEvaluated.props(t,(0,Gl.toHash)(s),i.props));let c=s.filter(m=>!(0,Gl.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,KS.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")}};Vl.default=Y0});var e_=x(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var YS=vt(),As=W(),XS=ie(),QS=ie(),X0={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,YS.allSchemaProperties)(r),d=c.filter(y=>(0,XS.alwaysValidSchema)(i,r[y]));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 As.Name)&&(i.props=(0,QS.evaluatedPropsToName)(t,i.props));let{props:m}=i;h();function h(){for(let y of c)p&&g(y),i.allErrors?S(y):(t.var(l,!0),S(y),t.if(l))}o(h,"validatePatternProperties");function g(y){for(let _ in p)new RegExp(y).test(_)&&(0,XS.checkStrictMode)(i,`property ${_} matches pattern ${y} (use allowMatchingProperties)`)}o(g,"checkMatchingProperties");function S(y){t.forIn("key",n,_=>{t.if((0,As._)`${(0,YS.usePattern)(e,y)}.test(${_})`,()=>{let v=d.includes(y);v||e.subschema({keyword:"patternProperties",schemaProp:y,dataProp:_,dataPropType:QS.Type.Str},l),i.opts.unevaluated&&m!==!0?t.assign((0,As._)`${m}[${_}]`,!0):!v&&!i.allErrors&&t.if((0,As.not)(l),()=>t.break())})})}o(S,"validateProperties")}};Fl.default=X0});var t_=x(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var Q0=ie(),eU={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,Q0.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"}};Zl.default=eU});var r_=x(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var tU=vt(),rU={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:tU.validateUnion,error:{message:"must match a schema in anyOf"}};Kl.default=rU});var n_=x(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var Ts=W(),nU=ie(),oU={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,Ts._)`{passingSchemas: ${e.passing}}`,"params")},aU={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:oU,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,nU.alwaysValidSchema)(a,l)?t.var(d,!0):h=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,Ts._)`${d} && ${s}`).assign(s,!1).assign(c,(0,Ts._)`[${c}, ${m}]`).else(),t.if(d,()=>{t.assign(s,!0),t.assign(c,m),h&&e.mergeEvaluated(h,Ts.Name)})})}o(p,"validateOneOf")}};Jl.default=aU});var o_=x(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var iU=ie(),sU={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,iU.alwaysValidSchema)(n,i))return;let c=e.subschema({keyword:"allOf",schemaProp:s},a);e.ok(a),e.mergeEvaluated(c)})}};Wl.default=sU});var s_=x(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var Es=W(),i_=ie(),cU={message:o(({params:e})=>(0,Es.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,Es._)`{failingKeyword: ${e.ifClause}}`,"params")},uU={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:cU,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,i_.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=a_(n,"then"),i=a_(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,Es.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,Es._)`${l}`):e.setParams({ifClause:l})}}o(p,"validateClause")}};function a_(e,t){let r=e.schema[t];return r!==void 0&&!(0,i_.alwaysValidSchema)(e,r)}o(a_,"hasSchema");Yl.default=uU});var c_=x(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var dU=ie(),lU={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,dU.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Xl.default=lU});var u_=x(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var pU=zl(),mU=DS(),fU=$l(),hU=HS(),gU=LS(),yU=VS(),SU=ZS(),_U=Bl(),vU=WS(),wU=e_(),bU=t_(),RU=r_(),CU=n_(),IU=o_(),PU=s_(),xU=c_();function kU(e=!1){let t=[bU.default,RU.default,CU.default,IU.default,PU.default,xU.default,SU.default,_U.default,yU.default,vU.default,wU.default];return e?t.push(mU.default,hU.default):t.push(pU.default,fU.default),t.push(gU.default),t}o(kU,"getApplicator");Ql.default=kU});var d_=x(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var Ie=W(),AU={message:o(({schemaCode:e})=>(0,Ie.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Ie._)`{format: ${e}}`,"params")},TU={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():g();function h(){let S=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),y=r.const("fDef",(0,Ie._)`${S}[${s}]`),_=r.let("fType"),v=r.let("format");r.if((0,Ie._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(_,(0,Ie._)`${y}.type || "string"`).assign(v,(0,Ie._)`${y}.validate`),()=>r.assign(_,(0,Ie._)`"string"`).assign(v,y)),e.fail$data((0,Ie.or)(w(),b()));function w(){return d.strictSchema===!1?Ie.nil:(0,Ie._)`${s} && !${v}`}o(w,"unknownFmt");function b(){let N=l.$async?(0,Ie._)`(${y}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Ie._)`${v}(${n})`,j=(0,Ie._)`(typeof ${v} == "function" ? ${N} : ${v}.test(${n}))`;return(0,Ie._)`${v} && ${v} !== true && ${_} === ${t} && !${j}`}o(b,"invalidFmt")}o(h,"validate$DataFormat");function g(){let S=m.formats[i];if(!S){w();return}if(S===!0)return;let[y,_,v]=b(S);y===t&&e.pass(N());function w(){if(d.strictSchema===!1){m.logger.warn(j());return}throw new Error(j());function j(){return`unknown format "${i}" ignored in schema at path "${p}"`}}o(w,"unknownFormat");function b(j){let Be=j instanceof RegExp?(0,Ie.regexpCode)(j):d.code.formats?(0,Ie._)`${d.code.formats}${(0,Ie.getProperty)(i)}`:void 0,ht=r.scopeValue("formats",{key:i,ref:j,code:Be});return typeof j=="object"&&!(j instanceof RegExp)?[j.type||"string",j.validate,(0,Ie._)`${ht}.validate`]:["string",j,ht]}o(b,"getFormat");function N(){if(typeof S=="object"&&!(S instanceof RegExp)&&S.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ie._)`await ${v}(${n})`}return typeof _=="function"?(0,Ie._)`${v}(${n})`:(0,Ie._)`${v}.test(${n})`}o(N,"validCondition")}o(g,"validateFormat")}};ep.default=TU});var l_=x(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var EU=d_(),UU=[EU.default];tp.default=UU});var p_=x(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.contentVocabulary=po.metadataVocabulary=void 0;po.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];po.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var f_=x(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var OU=wS(),MU=zS(),zU=u_(),$U=l_(),m_=p_(),qU=[OU.default,MU.default,(0,zU.default)(),$U.default,m_.metadataVocabulary,m_.contentVocabulary];rp.default=qU});var g_=x(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.DiscrError=void 0;var h_;(function(e){e.Tag="tag",e.Mapping="mapping"})(h_||(Us.DiscrError=h_={}))});var S_=x(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var mo=W(),np=g_(),y_=ms(),NU=xa(),DU=ie(),jU={message:o(({params:{discrError:e,tagName:t}})=>e===np.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,mo._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},HU={keyword:"discriminator",type:"object",schemaType:"object",error:jU,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,mo._)`${r}${(0,mo.getProperty)(c)}`);t.if((0,mo._)`typeof ${p} == "string"`,()=>l(),()=>e.error(!1,{discrError:np.DiscrError.Tag,tag:p,tagName:c})),e.ok(d);function l(){let g=h();t.if(!1);for(let S in g)t.elseIf((0,mo._)`${p} === ${S}`),t.assign(d,m(g[S]));t.else(),e.error(!1,{discrError:np.DiscrError.Mapping,tag:p,tagName:c}),t.endIf()}o(l,"validateMapping");function m(g){let S=t.name("valid"),y=e.subschema({keyword:"oneOf",schemaProp:g},S);return e.mergeEvaluated(y,mo.Name),S}o(m,"applyTagSchema");function h(){var g;let S={},y=v(a),_=!0;for(let N=0;N<s.length;N++){let j=s[N];if(j?.$ref&&!(0,DU.schemaHasRulesButRef)(j,i.self.RULES)){let ht=j.$ref;if(j=y_.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,ht),j instanceof y_.SchemaEnv&&(j=j.schema),j===void 0)throw new NU.default(i.opts.uriResolver,i.baseId,ht)}let Be=(g=j?.properties)===null||g===void 0?void 0:g[c];if(typeof Be!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);_=_&&(y||v(j)),w(Be,N)}if(!_)throw new Error(`discriminator: "${c}" must be required`);return S;function v({required:N}){return Array.isArray(N)&&N.includes(c)}function w(N,j){if(N.const)b(N.const,j);else if(N.enum)for(let Be of N.enum)b(Be,j);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function b(N,j){if(typeof N!="string"||N in S)throw new Error(`discriminator: "${c}" values must be unique strings`);S[N]=j}}o(h,"getMapping")}};op.default=HU});var __=x((tK,LU)=>{LU.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 ip=x((ge,ap)=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.MissingRefError=ge.ValidationError=ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=ge.Ajv=void 0;var BU=hS(),GU=f_(),VU=S_(),v_=__(),FU=["/properties"],Os="http://json-schema.org/draft-07/schema",fo=class extends BU.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),GU.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(v_,FU):v_;this.addMetaSchema(t,Os,!1),this.refs["http://json-schema.org/schema"]=Os}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Os)?Os:void 0)}};ge.Ajv=fo;ap.exports=ge=fo;ap.exports.Ajv=fo;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=fo;var ZU=Pa();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:o(function(){return ZU.KeywordCxt},"get")});var ho=W();Object.defineProperty(ge,"_",{enumerable:!0,get:o(function(){return ho._},"get")});Object.defineProperty(ge,"str",{enumerable:!0,get:o(function(){return ho.str},"get")});Object.defineProperty(ge,"stringify",{enumerable:!0,get:o(function(){return ho.stringify},"get")});Object.defineProperty(ge,"nil",{enumerable:!0,get:o(function(){return ho.nil},"get")});Object.defineProperty(ge,"Name",{enumerable:!0,get:o(function(){return ho.Name},"get")});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:o(function(){return ho.CodeGen},"get")});var KU=ls();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:o(function(){return KU.default},"get")});var JU=xa();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:o(function(){return JU.default},"get")})});var k_=x(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.formatNames=Kt.fastFormats=Kt.fullFormats=void 0;function Zt(e,t){return{validate:e,compare:t}}o(Zt,"fmtDef");Kt.fullFormats={date:Zt(C_,dp),time:Zt(cp(!0),lp),"date-time":Zt(w_(!0),P_),"iso-time":Zt(cp(),I_),"iso-date-time":Zt(w_(),x_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:tO,"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:cO,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:rO,int32:{type:"number",validate:aO},int64:{type:"number",validate:iO},float:{type:"number",validate:R_},double:{type:"number",validate:R_},password:!0,binary:!0};Kt.fastFormats={...Kt.fullFormats,date:Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,dp),time:Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,lp),"date-time":Zt(/^\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,P_),"iso-time":Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,I_),"iso-date-time":Zt(/^\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,x_),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};Kt.formatNames=Object.keys(Kt.fullFormats);function WU(e){return e%4===0&&(e%100!==0||e%400===0)}o(WU,"isLeapYear");var YU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,XU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function C_(e){let t=YU.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&&WU(r)?29:XU[n])}o(C_,"date");function dp(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(dp,"compareDate");var sp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function cp(e){return o(function(r){let n=sp.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(cp,"getTime");function lp(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(lp,"compareTime");function I_(e,t){if(!(e&&t))return;let r=sp.exec(e),n=sp.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(I_,"compareIsoTime");var up=/t|\s/i;function w_(e){let t=cp(e);return o(function(n){let a=n.split(up);return a.length===2&&C_(a[0])&&t(a[1])},"date_time")}o(w_,"getDateTime");function P_(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(P_,"compareDateTime");function x_(e,t){if(!(e&&t))return;let[r,n]=e.split(up),[a,i]=t.split(up),s=dp(r,a);if(s!==void 0)return s||lp(n,i)}o(x_,"compareIsoDateTime");var QU=/\/|:/,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;function tO(e){return QU.test(e)&&eO.test(e)}o(tO,"uri");var b_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function rO(e){return b_.lastIndex=0,b_.test(e)}o(rO,"byte");var nO=-(2**31),oO=2**31-1;function aO(e){return Number.isInteger(e)&&e<=oO&&e>=nO}o(aO,"validateInt32");function iO(e){return Number.isInteger(e)}o(iO,"validateInt64");function R_(){return!0}o(R_,"validateNumber");var sO=/[^\\]\\Z/;function cO(e){if(sO.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(cO,"regex")});var A_=x(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.formatLimitDefinition=void 0;var uO=ip(),Ut=W(),Vr=Ut.operators,Ms={formatMaximum:{okStr:"<=",ok:Vr.LTE,fail:Vr.GT},formatMinimum:{okStr:">=",ok:Vr.GTE,fail:Vr.LT},formatExclusiveMaximum:{okStr:"<",ok:Vr.LT,fail:Vr.GTE},formatExclusiveMinimum:{okStr:">",ok:Vr.GT,fail:Vr.LTE}},dO={message:o(({keyword:e,schemaCode:t})=>(0,Ut.str)`should be ${Ms[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,Ut._)`{comparison: ${Ms[e].okStr}, limit: ${t}}`,"params")};go.formatLimitDefinition={keyword:Object.keys(Ms),type:"string",schemaType:"string",$data:!0,error:dO,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 uO.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}),g=t.const("fmt",(0,Ut._)`${h}[${d.schemaCode}]`);e.fail$data((0,Ut.or)((0,Ut._)`typeof ${g} != "object"`,(0,Ut._)`${g} instanceof RegExp`,(0,Ut._)`typeof ${g}.compare != "function"`,m(g)))}o(p,"validate$DataFormat");function l(){let h=d.schema,g=c.formats[h];if(!g||g===!0)return;if(typeof g!="object"||g instanceof RegExp||typeof g.compare!="function")throw new Error(`"${a}": format "${h}" does not define "compare" function`);let S=t.scopeValue("formats",{key:h,ref:g,code:s.code.formats?(0,Ut._)`${s.code.formats}${(0,Ut.getProperty)(h)}`:void 0});e.fail$data(m(S))}o(l,"validateFormat");function m(h){return(0,Ut._)`${h}.compare(${r}, ${n}) ${Ms[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var lO=o(e=>(e.addKeyword(go.formatLimitDefinition),e),"formatLimitPlugin");go.default=lO});var O_=x((Ha,U_)=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var yo=k_(),pO=A_(),pp=W(),T_=new pp.Name("fullFormats"),mO=new pp.Name("fastFormats"),mp=o((e,t={keywords:!0})=>{if(Array.isArray(t))return E_(e,t,yo.fullFormats,T_),e;let[r,n]=t.mode==="fast"?[yo.fastFormats,mO]:[yo.fullFormats,T_],a=t.formats||yo.formatNames;return E_(e,a,r,n),t.keywords&&(0,pO.default)(e),e},"formatsPlugin");mp.get=(e,t="full")=>{let n=(t==="fast"?yo.fastFormats:yo.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function E_(e,t,r,n){var a,i;(a=(i=e.opts.code).formats)!==null&&a!==void 0||(i.formats=(0,pp._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}o(E_,"addFormats");U_.exports=Ha=mp;Object.defineProperty(Ha,"__esModule",{value:!0});Ha.default=mp});de();var br="2025-11-25",vm="2025-03-26",Rr=[br,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Cr="io.modelcontextprotocol/related-task",ai="2.0",xe=gm(e=>e!==null&&(typeof e=="object"||typeof e=="function")),wm=ye([f(),ne().int()]),bm=f(),nN=Pe({ttl:ne().optional(),pollInterval:ne().optional()}),ob=C({ttl:ne().optional()}),ab=C({taskId:f()}),Ic=Pe({progressToken:wm.optional(),[Cr]:ab.optional()}),ut=C({_meta:Ic.optional()}),Uo=ut.extend({task:ob.optional()}),Rm=o(e=>Uo.safeParse(e).success,"isTaskAugmentedRequestParams"),$e=C({method:f(),params:ut.loose().optional()}),gt=C({_meta:Ic.optional()}),yt=C({method:f(),params:gt.loose().optional()}),qe=Pe({_meta:Ic.optional()}),ii=ye([f(),ne().int()]),Cm=C({jsonrpc:O(ai),id:ii,...$e.shape}).strict(),qt=o(e=>Cm.safeParse(e).success,"isJSONRPCRequest"),Im=C({jsonrpc:O(ai),...yt.shape}).strict(),Pm=o(e=>Im.safeParse(e).success,"isJSONRPCNotification"),Pc=C({jsonrpc:O(ai),id:ii,result:qe}).strict(),It=o(e=>Pc.safeParse(e).success,"isJSONRPCResultResponse");var k;(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"})(k||(k={}));var xc=C({jsonrpc:O(ai),id:ii.optional(),error:C({code:ne().int(),message:f(),data:Re().optional()})}).strict();var Mn=o(e=>xc.safeParse(e).success,"isJSONRPCErrorResponse");var en=ye([Cm,Im,Pc,xc]),oN=ye([Pc,xc]),tr=qe.strict(),ib=gt.extend({requestId:ii.optional(),reason:f().optional()}),si=yt.extend({method:O("notifications/cancelled"),params:ib}),sb=C({src:f(),mimeType:f().optional(),sizes:R(f()).optional(),theme:ct(["light","dark"]).optional()}),Oo=C({icons:R(sb).optional()}),On=C({name:f(),title:f().optional()}),zn=On.extend({...On.shape,...Oo.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),cb=Rc(C({applyDefaults:ue().optional()}),me(f(),Re())),ub=Cc(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Rc(C({form:cb.optional(),url:xe.optional()}),me(f(),Re()).optional())),db=Pe({list:xe.optional(),cancel:xe.optional(),requests:Pe({sampling:Pe({createMessage:xe.optional()}).optional(),elicitation:Pe({create:xe.optional()}).optional()}).optional()}),lb=Pe({list:xe.optional(),cancel:xe.optional(),requests:Pe({tools:Pe({call:xe.optional()}).optional()}).optional()}),pb=C({experimental:me(f(),xe).optional(),sampling:C({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:ub.optional(),roots:C({listChanged:ue().optional()}).optional(),tasks:db.optional(),extensions:me(f(),xe).optional()}),mb=ut.extend({protocolVersion:f(),capabilities:pb,clientInfo:zn}),ci=$e.extend({method:O("initialize"),params:mb}),kc=o(e=>ci.safeParse(e).success,"isInitializeRequest"),fb=C({experimental:me(f(),xe).optional(),logging:xe.optional(),completions:xe.optional(),prompts:C({listChanged:ue().optional()}).optional(),resources:C({subscribe:ue().optional(),listChanged:ue().optional()}).optional(),tools:C({listChanged:ue().optional()}).optional(),tasks:lb.optional(),extensions:me(f(),xe).optional()}),Ac=qe.extend({protocolVersion:f(),capabilities:fb,serverInfo:zn,instructions:f().optional()}),ui=yt.extend({method:O("notifications/initialized"),params:gt.optional()}),xm=o(e=>ui.safeParse(e).success,"isInitializedNotification"),di=$e.extend({method:O("ping"),params:ut.optional()}),hb=C({progress:ne(),total:be(ne()),message:be(f())}),gb=C({...gt.shape,...hb.shape,progressToken:wm}),li=yt.extend({method:O("notifications/progress"),params:gb}),yb=ut.extend({cursor:bm.optional()}),Mo=$e.extend({params:yb.optional()}),zo=qe.extend({nextCursor:bm.optional()}),Sb=ct(["working","input_required","completed","failed","cancelled"]),$o=C({taskId:f(),status:Sb,ttl:ye([ne(),fm()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:be(ne()),statusMessage:be(f())}),rr=qe.extend({task:$o}),_b=gt.merge($o),qo=yt.extend({method:O("notifications/tasks/status"),params:_b}),pi=$e.extend({method:O("tasks/get"),params:ut.extend({taskId:f()})}),mi=qe.merge($o),fi=$e.extend({method:O("tasks/result"),params:ut.extend({taskId:f()})}),aN=qe.loose(),hi=Mo.extend({method:O("tasks/list")}),gi=zo.extend({tasks:R($o)}),yi=$e.extend({method:O("tasks/cancel"),params:ut.extend({taskId:f()})}),km=qe.merge($o),Am=C({uri:f(),mimeType:be(f()),_meta:me(f(),Re()).optional()}),Tm=Am.extend({text:f()}),Tc=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Em=Am.extend({blob:Tc}),No=ct(["user","assistant"]),$n=C({audience:R(No).optional(),priority:ne().min(0).max(1).optional(),lastModified:pm.datetime({offset:!0}).optional()}),Um=C({...On.shape,...Oo.shape,uri:f(),description:be(f()),mimeType:be(f()),size:be(ne()),annotations:$n.optional(),_meta:be(Pe({}))}),vb=C({...On.shape,...Oo.shape,uriTemplate:f(),description:be(f()),mimeType:be(f()),annotations:$n.optional(),_meta:be(Pe({}))}),Ec=Mo.extend({method:O("resources/list")}),Uc=zo.extend({resources:R(Um)}),Oc=Mo.extend({method:O("resources/templates/list")}),Mc=zo.extend({resourceTemplates:R(vb)}),zc=ut.extend({uri:f()}),wb=zc,$c=$e.extend({method:O("resources/read"),params:wb}),qc=qe.extend({contents:R(ye([Tm,Em]))}),Nc=yt.extend({method:O("notifications/resources/list_changed"),params:gt.optional()}),bb=zc,Rb=$e.extend({method:O("resources/subscribe"),params:bb}),Cb=zc,Ib=$e.extend({method:O("resources/unsubscribe"),params:Cb}),Pb=gt.extend({uri:f()}),xb=yt.extend({method:O("notifications/resources/updated"),params:Pb}),kb=C({name:f(),description:be(f()),required:be(ue())}),Ab=C({...On.shape,...Oo.shape,description:be(f()),arguments:be(R(kb)),_meta:be(Pe({}))}),Dc=Mo.extend({method:O("prompts/list")}),jc=zo.extend({prompts:R(Ab)}),Tb=ut.extend({name:f(),arguments:me(f(),f()).optional()}),Hc=$e.extend({method:O("prompts/get"),params:Tb}),Lc=C({type:O("text"),text:f(),annotations:$n.optional(),_meta:me(f(),Re()).optional()}),Bc=C({type:O("image"),data:Tc,mimeType:f(),annotations:$n.optional(),_meta:me(f(),Re()).optional()}),Gc=C({type:O("audio"),data:Tc,mimeType:f(),annotations:$n.optional(),_meta:me(f(),Re()).optional()}),Eb=C({type:O("tool_use"),name:f(),id:f(),input:me(f(),Re()),_meta:me(f(),Re()).optional()}),Ub=C({type:O("resource"),resource:ye([Tm,Em]),annotations:$n.optional(),_meta:me(f(),Re()).optional()}),Ob=Um.extend({type:O("resource_link")}),Vc=ye([Lc,Bc,Gc,Ob,Ub]),Mb=C({role:No,content:Vc}),Fc=qe.extend({description:f().optional(),messages:R(Mb)}),Zc=yt.extend({method:O("notifications/prompts/list_changed"),params:gt.optional()}),zb=C({title:f().optional(),readOnlyHint:ue().optional(),destructiveHint:ue().optional(),idempotentHint:ue().optional(),openWorldHint:ue().optional()}),$b=C({taskSupport:ct(["required","optional","forbidden"]).optional()}),Om=C({...On.shape,...Oo.shape,description:f().optional(),inputSchema:C({type:O("object"),properties:me(f(),xe).optional(),required:R(f()).optional()}).catchall(Re()),outputSchema:C({type:O("object"),properties:me(f(),xe).optional(),required:R(f()).optional()}).catchall(Re()).optional(),annotations:zb.optional(),execution:$b.optional(),_meta:me(f(),Re()).optional()}),Kc=Mo.extend({method:O("tools/list")}),Jc=zo.extend({tools:R(Om)}),Ir=qe.extend({content:R(Vc).default([]),structuredContent:me(f(),Re()).optional(),isError:ue().optional()}),iN=Ir.or(qe.extend({toolResult:Re()})),qb=Uo.extend({name:f(),arguments:me(f(),Re()).optional()}),Do=$e.extend({method:O("tools/call"),params:qb}),Wc=yt.extend({method:O("notifications/tools/list_changed"),params:gt.optional()}),Mm=C({autoRefresh:ue().default(!0),debounceMs:ne().int().nonnegative().default(300)}),jo=ct(["debug","info","notice","warning","error","critical","alert","emergency"]),Nb=ut.extend({level:jo}),Yc=$e.extend({method:O("logging/setLevel"),params:Nb}),Db=gt.extend({level:jo,logger:f().optional(),data:Re()}),jb=yt.extend({method:O("notifications/message"),params:Db}),Hb=C({name:f().optional()}),Lb=C({hints:R(Hb).optional(),costPriority:ne().min(0).max(1).optional(),speedPriority:ne().min(0).max(1).optional(),intelligencePriority:ne().min(0).max(1).optional()}),Bb=C({mode:ct(["auto","required","none"]).optional()}),Gb=C({type:O("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:R(Vc).default([]),structuredContent:C({}).loose().optional(),isError:ue().optional(),_meta:me(f(),Re()).optional()}),Vb=bc("type",[Lc,Bc,Gc]),oi=bc("type",[Lc,Bc,Gc,Eb,Gb]),Fb=C({role:No,content:ye([oi,R(oi)]),_meta:me(f(),Re()).optional()}),Zb=Uo.extend({messages:R(Fb),modelPreferences:Lb.optional(),systemPrompt:f().optional(),includeContext:ct(["none","thisServer","allServers"]).optional(),temperature:ne().optional(),maxTokens:ne().int(),stopSequences:R(f()).optional(),metadata:xe.optional(),tools:R(Om).optional(),toolChoice:Bb.optional()}),Xc=$e.extend({method:O("sampling/createMessage"),params:Zb}),tn=qe.extend({model:f(),stopReason:be(ct(["endTurn","stopSequence","maxTokens"]).or(f())),role:No,content:Vb}),Ho=qe.extend({model:f(),stopReason:be(ct(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:No,content:ye([oi,R(oi)])}),Kb=C({type:O("boolean"),title:f().optional(),description:f().optional(),default:ue().optional()}),Jb=C({type:O("string"),title:f().optional(),description:f().optional(),minLength:ne().optional(),maxLength:ne().optional(),format:ct(["email","uri","date","date-time"]).optional(),default:f().optional()}),Wb=C({type:ct(["number","integer"]),title:f().optional(),description:f().optional(),minimum:ne().optional(),maximum:ne().optional(),default:ne().optional()}),Yb=C({type:O("string"),title:f().optional(),description:f().optional(),enum:R(f()),default:f().optional()}),Xb=C({type:O("string"),title:f().optional(),description:f().optional(),oneOf:R(C({const:f(),title:f()})),default:f().optional()}),Qb=C({type:O("string"),title:f().optional(),description:f().optional(),enum:R(f()),enumNames:R(f()).optional(),default:f().optional()}),eR=ye([Yb,Xb]),tR=C({type:O("array"),title:f().optional(),description:f().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:C({type:O("string"),enum:R(f())}),default:R(f()).optional()}),rR=C({type:O("array"),title:f().optional(),description:f().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:C({anyOf:R(C({const:f(),title:f()}))}),default:R(f()).optional()}),nR=ye([tR,rR]),oR=ye([Qb,eR,nR]),aR=ye([oR,Kb,Jb,Wb]),iR=Uo.extend({mode:O("form").optional(),message:f(),requestedSchema:C({type:O("object"),properties:me(f(),aR),required:R(f()).optional()})}),sR=Uo.extend({mode:O("url"),message:f(),elicitationId:f(),url:f().url()}),cR=ye([iR,sR]),Qc=$e.extend({method:O("elicitation/create"),params:cR}),uR=gt.extend({elicitationId:f()}),dR=yt.extend({method:O("notifications/elicitation/complete"),params:uR}),Pr=qe.extend({action:ct(["accept","decline","cancel"]),content:Cc(e=>e===null?void 0:e,me(f(),ye([f(),ne(),ue(),R(f())])).optional())}),lR=C({type:O("ref/resource"),uri:f()});var pR=C({type:O("ref/prompt"),name:f()}),mR=ut.extend({ref:ye([pR,lR]),argument:C({name:f(),value:f()}),context:C({arguments:me(f(),f()).optional()}).optional()}),fR=$e.extend({method:O("completion/complete"),params:mR});var eu=qe.extend({completion:Pe({values:R(f()).max(100),total:be(ne().int()),hasMore:be(ue())})}),hR=C({uri:f().startsWith("file://"),name:f().optional(),_meta:me(f(),Re()).optional()}),gR=$e.extend({method:O("roots/list"),params:ut.optional()}),tu=qe.extend({roots:R(hR)}),yR=yt.extend({method:O("notifications/roots/list_changed"),params:gt.optional()}),sN=ye([di,ci,fR,Yc,Hc,Dc,Ec,Oc,$c,Rb,Ib,Do,Kc,pi,fi,hi,yi]),cN=ye([si,li,ui,yR,qo]),uN=ye([tr,tn,Ho,Pr,tu,mi,gi,rr]),dN=ye([di,Xc,Qc,gR,pi,fi,hi,yi]),lN=ye([si,li,jb,xb,Nc,Wc,Zc,qo,dR]),pN=ye([tr,Ac,eu,Fc,jc,Uc,Mc,qc,Ir,Jc,mi,gi,rr]),I=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===k.UrlElicitationRequired&&n){let a=n;if(a.elicitations)return new Ct(a.elicitations,r)}return new e(t,r,n)}},Ct=class extends I{static{o(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(k.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};de();de();de();var _R=new Set(["localhost","::1"]);function nr(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(nr,"normalizeHostname");function ke(e){let t=nr(e.hostname);return e.protocol==="http:"&&(_R.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(ke,"isLoopbackHttpUrl");var zm=new $t("gateway-route");function $m(e,t){zm.set(e,t)}o($m,"setGatewayRouteContext");function Lo(e){return zm.get(e)}o(Lo,"readGatewayRouteContext");function qn(e){let t=Lo(e);if(!t)throw new K("Gateway route context has not been set");return t}o(qn,"requireGatewayRouteContext");var qm=new $t("mcp-oauth-runtime-config");function Nn(e,t){qm.set(e,t)}o(Nn,"setMcpOAuthRuntimeConfig");function Nm(e){let t=qm.get(e);if(!t)throw new q("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(Nm,"requireMcpOAuthRuntimeConfig");var Bo=u.string().trim().min(1),vR=60,wR=24*60*60,bR=15*vR,RR=10*365*wR,Go={accessTokenTtlSeconds:bR,refreshTokenTtlSeconds:RR,cimdEnabled:!0},CR=u.object({issuer:u.url(),jwksUrl:u.url(),audience:Bo.optional()}),IR=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().superRefine((e,t)=>{if(!jm(e.url))for(let r of["tokenUrl","clientId","clientSecret"])e[r]||t.addIssue({code:u.ZodIssueCode.custom,message:`${r} is required for federated browser login`,path:[r]})}),PR=u.object({accessTokenTtlSeconds:u.coerce.number().int().positive().default(Go.accessTokenTtlSeconds),refreshTokenTtlSeconds:u.coerce.number().int().positive().default(Go.refreshTokenTtlSeconds),cimdEnabled:u.boolean().default(Go.cimdEnabled)}).strict().default(Go),ru=u.object({oidc:CR,browserLogin:IR,gateway:PR.optional().default(Go)}).strict();function Dm(e){return jm(e.browserLogin.url)?"local_dev":"federated_oidc"}o(Dm,"readBrowserLoginKind");function jm(e){let t;try{t=new URL(e)}catch{return!1}return ke(t)&&t.pathname==="/oauth/dev-login"}o(jm,"isLoopbackDevLoginUrl");function Hm(e){return ru.parse(e)}o(Hm,"parseMcpOAuthRuntimeConfig");function Te(){let e;try{e=_c()}catch(t){throw new K("MCP gateway OAuth config can only be read during a request. Wrap tests in `runWithRequestContext` and ensure MCP OAuth routes are registered through `McpGatewayPlugin`.",{cause:t})}return Nm(e)}o(Te,"getGatewayOAuthConfig");de();var Q=u.string().datetime({offset:!0}).brand();function oe(e){return Q.parse(e.toISOString())}o(oe,"toIsoTimestamp");function or(e,t){return new Date(e.getTime()+t*1e3)}o(or,"addSeconds");de();function le(e){return new URL(e).origin}o(le,"readGatewayRequestOrigin");function Pt(e){return le(e)}o(Pt,"readGatewayOAuthIssuer");function nu(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(nu,"truncate");function Lm(e){return"cause"in e?e.cause:void 0}o(Lm,"readCause");function Xe(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=nu(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=nu(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`]=nu(n.message),n=Lm(n)}}o(Xe,"addErrorLogFields");function St(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}o(St,"safeHost");function Bm(e,t){let r=Object.entries(t).filter(n=>n[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}o(Bm,"setLogProperties");function ou(e,t){Bm(e,{subjectId:t.subjectId})}o(ou,"applyGatewayPrincipalLogProperties");function Gm(e,t){Bm(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(Gm,"applyGatewayRouteLogProperties");var T="gatewayCode",Dn={runtime:{invalid_request:{code:"invalid_request",status:400,title:"Bad Request",publicDetail:"The request did not match the route contract.",oauthError:"invalid_request"},forbidden:{code:"forbidden",status:403,title:"Forbidden",publicDetail:"The request is not allowed.",oauthError:"invalid_request"},not_found:{code:"not_found",status:404,title:"Not Found",publicDetail:"The requested resource was not found.",oauthError:"invalid_request"},too_many_requests:{code:"too_many_requests",status:429,title:"Too Many Requests",publicDetail:"The request exceeded the allowed rate.",oauthError:"invalid_request"},internal_server_error:{code:"internal_server_error",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",status:404,title:"Not Found",publicDetail:"The requested virtual server is not enabled."},unknown_upstream_server:{code:"unknown_upstream_server",status:400,title:"Bad Request",publicDetail:"The requested upstream server is not configured.",oauthError:"invalid_request"},unknown_virtual_server:{code:"unknown_virtual_server",status:400,title:"Bad Request",publicDetail:"The requested virtual server is not configured.",oauthError:"invalid_target"},unknown_auth_profile:{code:"unknown_auth_profile",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",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",status:401,title:"Unauthorized",publicDetail:"Authentication is required to access this route.",oauthError:"invalid_client"},identity_context_missing:{code:"identity_context_missing",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",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",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",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",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",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",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",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",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",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",status:502,title:"Bad Gateway",publicDetail:"The upstream capability invocation failed. Retry later or reconnect the upstream if the issue persists."},upstream_capability_unavailable:{code:"upstream_capability_unavailable",status:503,title:"Service Unavailable",publicDetail:"The upstream capability is unavailable. Retry later or reconnect the upstream if the issue persists."},upstream_import_failed:{code:"upstream_import_failed",status:502,title:"Bad Gateway",publicDetail:"The upstream capability import failed. Retry later or reconnect the upstream if the issue persists."}}},Qe={...Dn.runtime,...Dn.config,...Dn.downstream_auth,...Dn.downstream_oauth,...Dn.upstream_auth,...Dn.upstream_mcp};function ar(e){return typeof e=="string"&&Object.hasOwn(Qe,e)}o(ar,"isGatewayProblemCode");function Si(e){return ar(e)&&Ee(e).callbackFailure===!0}o(Si,"isGatewayCallbackFailureCode");function Ee(e){return Qe[e]}o(Ee,"readGatewayProblemDefinition");function Vm(e){switch(e){case 400:return"invalid_request";case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";case 429:return"too_many_requests";default:return"internal_server_error"}}o(Vm,"readDefaultGatewayProblemCodeForStatus");function Fm(e){let t=Ee(e);return{title:t.title,body:t.publicDetail}}o(Fm,"readGatewayCallbackFailureContent");function dt(e){if(!(e instanceof E))return;let t=e.extensionMembers?.[T];return ar(t)?t:void 0}o(dt,"readGatewayProblemCode");function D(e,t,r){let n=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...r===void 0?{}:{cause:r}}:e,a=Ee(n.code),i=n.privateDetail??(_i(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),s=xR(n);return new E({message:i,extensionMembers:{[T]:n.code}},s===void 0?void 0:{cause:s})}o(D,"createGatewayRuntimeError");async function xr(e,t,r){let n=Ee(r.code),a=kR(r.code,r.detail),i=_i(r.code)?r.title??n.title:n.title,c={problem:{...Ae.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),Ae.format(c,e,t)}o(xr,"gatewayProblemResponse");function _i(e){return Ee(e).status<500}o(_i,"canExposeGatewayProblemDetail");function xR(e){return!e.privateDetail||_i(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o(xR,"readRuntimeErrorCause");function kR(e,t){let r=Ee(e);return _i(e)&&t||r.publicDetail}o(kR,"readSafeGatewayProblemDetail");de();var AR=["shared-oauth","user-oauth","static-secret","user-secret","shared-secret"],TR=["none","client_secret_basic","client_secret_post"],et=u.string().min(1).brand(),Ue=u.string().min(1).brand(),tt=u.string().min(1).brand(),kr=u.string().min(1).brand(),vi=u.enum(AR),au=u.enum(TR),wi=u.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),iu=u.object({name:wi,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict();var ER=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function UR(e){return e.protocol.replace(/:$/u,"").toLowerCase()}o(UR,"readScheme");function OR(e){return e.protocol==="https:"}o(OR,"isSpecCompliantRedirectUri");function MR(e){let t=UR(e);return t.length>0&&t!=="http"&&t!=="https"&&!ER.has(t)}o(MR,"isNativeAppCustomSchemeRedirectUri");var Km=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:o(e=>OR(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:o(e=>ke(e),"accepts"),matches:o((e,t)=>ke(e)&&ke(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:o(e=>MR(e),"accepts")}];function Jm(e){let t=Km.find(r=>r.accepts(e.url,e.context));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}o(Jm,"evaluateBuiltInRedirectUriCompatibility");function Zm(e){try{return new URL(e)}catch{return}}o(Zm,"parseUrl");function Wm(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=Zm(e.registeredRedirectUri),r=Zm(e.requestedRedirectUri);if(t===void 0||r===void 0)return!1;let n=e.context??{source:"registration_match"};return Km.some(a=>a.matches?.(t,r,n))}o(Wm,"redirectUriMatchesBuiltInCompatibility");de();var zR=43,$R=128,qR=/^[A-Za-z0-9._~-]+$/,su="S256",bi=u.literal(su),Ri=u.string().min(zR).max($R).regex(qR);de();var Ym=["none","client_secret_post","client_secret_basic"],cu=[...Ym,"private_key_jwt"],NR=["awaiting_login","awaiting_setup"],DR=u.string().min(1).brand(),Oe=u.string().min(1).brand(),Vo=u.uuid().brand(),lt=u.uuid().brand(),Ci=u.uuid().brand(),Xm=u.enum(Ym),Qm=u.enum(cu),gD=u.enum(NR),ef=u.object({client_id:Oe,client_name:u.string().min(1),redirect_uris:u.array(u.string().min(1)).min(1),jwks_uri:u.string().min(1).optional(),token_endpoint_auth_method:Qm.default("none")}).superRefine((e,t)=>{e.token_endpoint_auth_method==="private_key_jwt"&&e.jwks_uri===void 0&&t.addIssue({code:"custom",path:["jwks_uri"],message:"jwks_uri is required for private_key_jwt clients."})}),uu=u.object({clientId:Oe,clientName:u.string().min(1),redirectUris:u.array(u.string().min(1)),tokenEndpointAuthMethod:Qm,hashedClientSecret:u.string().optional(),clientSecretExpiresAt:Q.optional(),clientExpiresAt:Q,revokedAt:Q.optional(),createdAt:Q}),du=u.object({clientId:Oe,resource:u.string(),virtualServerId:Ue,subjectId:DR,scope:u.string(),roles:u.array(u.string()),createdAt:Q,expiresAt:Q}),yD=du.extend({id:lt,redirectUri:u.string(),clientState:u.string().optional(),codeChallenge:u.string(),codeChallengeMethod:bi}),lu=du.extend({id:Vo,currentRefreshTokenHash:u.string().optional(),previousRefreshTokenHash:u.string().optional(),previousRefreshTokenRotatedAt:Q.optional(),revokedAt:Q.optional(),revokedReason:u.string().optional()}),Ii=du.extend({tokenHash:u.string(),grantId:Vo,revokedAt:Q.optional()});function pu(){return lt.parse(crypto.randomUUID())}o(pu,"createDownstreamAuthorizationTransactionId");function mu(){return Ci.parse(crypto.randomUUID())}o(mu,"createDownstreamBrowserLoginStateId");function tf(){return Vo.parse(crypto.randomUUID())}o(tf,"createDownstreamGrantId");var _e="mcp:tools";function rf(e,t){return Wm({registeredRedirectUri:e,requestedRedirectUri:t,context:{source:"registration_match"}})}o(rf,"redirectUriMatchesRegistration");function nf(e){return ke(e)&&e.pathname==="/oauth/dev-login"}o(nf,"isLoopbackDevLoginUrl");function Pi(e,t){return new URL(e,Pt(t)).toString()}o(Pi,"buildGatewayOAuthUrl");function fu(e){let t=Nt(Ue.parse(e.virtualServerId));return new URL(t.routePath,le(e.requestUrl)).toString()}o(fu,"buildScopedAuthorizationServerIssuer");function jR(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,le(e.requestUrl)).toString()}o(jR,"buildScopedAuthorizationEndpoint");function hu(e){let t=Te();return{issuer:Pt(e),authorization_endpoint:Pi("/oauth/authorize",e),token_endpoint:Pi("/oauth/token",e),registration_endpoint:Pi("/oauth/register",e),revocation_endpoint:Pi("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[_e],code_challenge_methods_supported:[su],token_endpoint_auth_methods_supported:cu,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","private_key_jwt","none"],client_id_metadata_document_supported:t.gateway.cimdEnabled,"x-zuplo-browser-login-kind":Dm(t)}}o(hu,"buildAuthorizationServerMetadata");function of(e){let t=fu(e);return{...hu(e.requestUrl),issuer:t,authorization_endpoint:jR(e)}}o(of,"buildScopedAuthorizationServerMetadata");var rn="2025-06-18";async function af(e,t){try{let r=Ue.parse(e.params.virtualServerId),n=Nt(r);return Response.json(HR(n.virtualServerId,e.url))}catch(r){let n=dt(r);return xr(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(af,"protectedResourceMetadataHandler");function HR(e,t){return{resource:Ar(e,t),resource_name:e,authorization_servers:[fu({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[_e],mcp_protocol_version:rn}}o(HR,"buildProtectedResourceMetadataResponseBody");function Ar(e,t){let r=Nt(e);return new URL(r.routePath,le(t)).toString()}o(Ar,"buildCanonicalMcpResourceForVirtualServer");function sf(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,le(t)).toString()}o(sf,"buildProtectedResourceMetadataUrlForVirtualServer");var LR=u.record(u.string(),u.unknown()),cf=u.string().min(1),BR=u.union([cf.transform(e=>[e]),u.array(cf)]),ve=u.string().min(1).brand(),GR=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],VR=["https://zuplo.com/roles","roles","role","permissions","groups"],uf=new $t("gateway-principal");function FR(e){let t=LR.safeParse(e);return t.success?t.data:{}}o(FR,"toClaimRecord");function ZR(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(ZR,"readValidationFailureDetail");function KR(e,t,r){for(let i of GR){let s=ve.safeParse(t[i]);if(s.success)return s.data}let n=ve.safeParse(e?.sub);if(!n.success)throw D("identity_context_missing",ZR(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===Pt(r)?n.data:ve.parse(`${a}|${n.data}`)}o(KR,"readNormalizedSubjectId");function JR(e){let t=new Set;for(let r of VR){let n=BR.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o(JR,"readRoles");function jn(e,t){let r=FR(e?.data),n={subjectId:KR(e,r,t)},a=JR(r);return a&&(n.roles=a),n}o(jn,"parseGatewayPrincipal");function df(e){let t=yu(e);if(!t)throw D("identity_context_missing","Gateway principal has not been hydrated");return t}o(df,"requireGatewayPrincipal");function lf(e,t){uf.set(e,t)}o(lf,"setGatewayPrincipal");function yu(e){return uf.get(e)}o(yu,"readGatewayPrincipal");function xi(e){let r=['realm="OAuth"',`resource_metadata="${gu(sf(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${gu(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${gu(e.scope)}"`),`Bearer ${r.join(", ")}`}o(xi,"buildGatewayBearerChallenge");function gu(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(gu,"sanitizeQuotedHeaderParameter");de();de();function pf(e){return new E({message:e,extensionMembers:{[T]:"invalid_request"}})}o(pf,"invalidReturnTo");function ki(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw pf("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 pf("returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}o(ki,"parseSafeRelativeReturnTo");de();var WR=["user","shared"],Hn=u.enum(WR);function Tr(e){return{mode:"user",subjectId:e}}o(Tr,"buildUserUpstreamConnectionOwner");function Ai(){return{mode:"shared"}}o(Ai,"buildSharedUpstreamConnectionOwner");var mf=u.object({ownerMode:Hn,initiatedBySubjectId:ve,ownerSubjectId:ve.optional(),upstreamServerId:et,authProfileId:tt,virtualServerId:Ue,returnTo:u.string().min(1).transform(e=>ki(e)).optional()});function ff(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(ff,"validateUpstreamOwnerState");var Ln=mf.superRefine(ff),hf=mf.omit({returnTo:!0}).superRefine(ff);function Fo(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(Fo,"buildUpstreamOwnerState");function Bn(e){if(e.ownerMode==="shared")return Ai();if(!e.ownerSubjectId)throw new E({message:"User-owned upstream state is missing the owner subject.",extensionMembers:{[T]:"oauth_state_invalid"}});return Tr(e.ownerSubjectId)}o(Bn,"resolveUpstreamConnectionOwnerFromState");var YR=["active","not_connected","reconsent_required"],XR=["basic_auth_app_password","bearer_token"],gf=u.string().trim().min(1).brand(),Gn=u.uuid().brand(),Zo=u.uuid().brand(),Su=u.enum(YR),QR=u.enum(XR),yf=u.object({encryptedClientInformation:u.string().optional(),encryptedDiscoveryState:u.string().optional(),connectedBySubjectId:ve.optional()}),eC=yf.extend({encryptedStaticSecret:u.string().optional(),staticSecretKind:QR.optional(),staticSecretLabel:u.string().min(1).optional(),staticSecretUsername:u.string().min(1).optional()}).strict(),tC=u.object({id:gf,subjectId:ve.optional(),ownerMode:Hn,upstreamServerId:et,authProfileId:tt,status:Su,encryptedAccessToken:u.string().min(1).optional(),encryptedRefreshToken:u.string().min(1).optional(),scopes:u.array(u.string()),expiresAt:Q.optional(),metadata:eC.optional(),createdAt:Q,updatedAt:Q});function _u(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(_u,"validateUpstreamConnectionOwnerShape");var Vn=tC.superRefine(_u);function Er(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}o(Er,"readUpstreamConnectionLookupKey");var vu=Ln.extend({id:Gn,callbackPath:u.string().min(1),expiresAt:Q,codeVerifier:u.string().optional(),redirectUri:u.url(),returnOrigin:u.url().optional()}).extend(yf.shape);function Sf(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o(Sf,"readUpstreamConnectionStatus");function Ti(){return gf.parse(`mcpgw2uc_${crypto.randomUUID()}`)}o(Ti,"createUpstreamConnectionId");function _f(){return Gn.parse(crypto.randomUUID())}o(_f,"createOAuthStateId");function vf(){return Zo.parse(crypto.randomUUID())}o(vf,"createBrowserConnectTicketId");de();var bu=u.discriminatedUnion("mode",[u.object({mode:u.literal("user"),subjectId:ve}).strict(),u.object({mode:u.literal("shared")}).strict()]),bf=u.object({owner:bu,upstreamServerId:et,authProfileId:tt}).strict(),Rf=u.object({items:u.array(bf).min(1).max(100)}).strict(),Ru=u.object({items:u.array(u.object({key:u.object({ownerMode:Hn,subjectId:ve.optional(),upstreamServerId:et,authProfileId:tt}).strict(),connection:Vn.strict().optional()}).strict())}).strict(),Cf=Vn.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(_u),If=Vn.strict(),Pf=u.object({owner:bu,upstreamServerId:et,authProfileId:tt}).strict(),xf=u.object({owner:bu,upstreamServerId:et,authProfileId:tt,connection:Vn.strict().optional(),connectionStatus:u.object({connected:u.boolean(),status:Su,updatedAt:Vn.shape.updatedAt.optional()}).strict()}).strict(),rC=u.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]),nn=u.object({clientId:Oe,clientName:u.string().min(1),tokenEndpointAuthMethod:rC}).strict(),Cu=u.discriminatedUnion("method",[u.object({method:u.literal("none"),clientId:Oe}).strict(),u.object({method:u.enum(["client_secret_basic","client_secret_post"]),clientId:Oe,clientSecretHashInput:u.string().min(1)}).strict(),u.object({method:u.literal("private_key_jwt"),clientId:Oe}).strict()]),Iu=u.object({id:lt,currentStateHash:u.string().min(1),clientId:Oe,redirectUri:u.string().min(1),resource:u.string().min(1),virtualServerId:Ue,clientState:u.string().optional(),scope:u.string(),codeChallenge:u.string().min(1),codeChallengeMethod:u.literal("S256"),setupApprovedAt:Q.optional(),createdAt:Q,expiresAt:Q,consumedAt:Q.optional()}).strict(),wf=Iu.omit({id:!0,consumedAt:!0}).extend({transactionId:lt,client:nn.optional()}).strict(),Pu=u.object({subjectId:ve,roles:u.array(u.string()).optional()}).strict(),nC=Iu.extend({phase:u.literal("awaiting_login")}).strict(),wu=Iu.extend({phase:u.literal("awaiting_setup"),principal:Pu}).strict(),oC=u.discriminatedUnion("phase",[nC,wu]),Ei=u.object({transaction:oC,client:nn}).strict(),kf=uu.omit({revokedAt:!0}).strict(),Af=u.discriminatedUnion("kind",[u.object({kind:u.literal("registered"),client:nn}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),Tf=u.object({clientId:Oe}).strict(),Ef=u.discriminatedUnion("kind",[u.object({kind:u.literal("found"),client:uu.strict()}).strict(),u.object({kind:u.literal("missing")}).strict()]),Uf=u.discriminatedUnion("phase",[wf.extend({phase:u.literal("awaiting_login")}).strict(),wf.extend({phase:u.literal("awaiting_setup"),principal:Pu}).strict()]),Of=u.discriminatedUnion("kind",[Ei.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()]),Mf=u.object({transactionId:lt,currentStateHash:u.string().min(1),now:Q}).strict(),zf=u.discriminatedUnion("kind",[Ei.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()]),$f=u.object({transactionId:lt,expectedPhase:u.literal("awaiting_login"),currentStateHash:u.string().min(1),nextStateHash:u.string().min(1),nextPhase:u.literal("awaiting_setup"),principal:Pu,now:Q}).strict(),qf=u.discriminatedUnion("kind",[Ei.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()]),Nf=u.object({transactionId:lt,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),now:Q}).strict(),Df=u.discriminatedUnion("kind",[Ei.extend({kind:u.literal("marked")}).strict(),u.object({kind:u.literal("wrong_phase"),current:u.enum(["awaiting_login","awaiting_setup"])}).strict(),u.object({kind:u.literal("principal_mismatch")}).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()]),jf=u.discriminatedUnion("decision",[u.object({decision:u.literal("approve"),transactionId:lt,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),authorizationCodeHash:u.string().min(1),authorizationCodeExpiresAt:Q,grantId:Vo,now:Q}).strict(),u.object({decision:u.literal("cancel"),transactionId:lt,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),now:Q}).strict()]),Hf=u.discriminatedUnion("kind",[u.object({kind:u.literal("approved"),transaction:wu,client:nn}).strict(),u.object({kind:u.literal("cancelled"),transaction:wu,client:nn}).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()]),Lf=u.object({clientAuth:Cu,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(),Bf=u.discriminatedUnion("kind",[u.object({kind:u.literal("exchanged"),client:nn,grant:lu.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()]),Gf=u.object({clientAuth:Cu,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(),Vf=u.discriminatedUnion("kind",[u.object({kind:u.literal("rotated"),client:nn,grant:lu.strict(),accessToken:Ii.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("previous_token_grace")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),Ff=u.object({clientAuth:Cu,tokenHash:u.string().min(1),now:Q}).strict(),Zf=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()]),Kf=u.object({tokenHash:u.string().min(1),now:Q}).strict(),Jf=u.discriminatedUnion("kind",[u.object({kind:u.literal("valid"),record:Ii.strict()}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),Wf=u.object({accessTokenHash:u.string().min(1),resource:u.string().min(1),virtualServerId:Ue,upstreamConnectionKeys:u.array(bf).max(100),now:Q}).strict(),Yf=u.discriminatedUnion("kind",[u.object({kind:u.literal("authorized"),principal:u.object({subjectId:ve,roles:u.array(u.string())}).strict(),accessToken:Ii.strict(),upstreamConnections:Ru.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()]),Xf=u.object({record:vu}).strict(),Qf=u.object({kind:u.literal("saved")}).strict(),eh=u.object({id:Gn,now:Q}).strict(),th=u.discriminatedUnion("kind",[u.object({kind:u.literal("available"),record:vu}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict()]),rh=u.object({id:Zo,expiresAt:Q,now:Q}).strict(),nh=u.discriminatedUnion("kind",[u.object({kind:u.literal("available")}).strict(),u.object({kind:u.literal("consumed")}).strict()]);var oh=100,aC=new Set(["undefined","null","nan"]);function ah(e){return e!==null&&typeof e=="object"}o(ah,"isProblemDetailsShape");var iC="/zups/v2/mcp/storage";function Me(e){return`${iC}/${e}`}o(Me,"buildStoragePath");function sC(){return Me("upstream-connections/batch-get")}o(sC,"buildBatchGetUpstreamConnectionsPath");function cC(){return Me("upstream-connections/upsert")}o(cC,"buildUpsertUpstreamConnectionPath");function uC(){return Me("authorization/read-setup")}o(uC,"buildReadAuthorizationSetupPath");function dC(){return Me("oauth/register-client")}o(dC,"buildRegisterClientPath");function lC(){return Me("oauth/read-client")}o(lC,"buildReadClientPath");function pC(){return Me("authorization/start")}o(pC,"buildStartAuthorizationPath");function mC(){return Me("authorization/read-pending")}o(mC,"buildReadPendingAuthorizationPath");function fC(){return Me("authorization/advance-pending")}o(fC,"buildAdvancePendingAuthorizationPath");function hC(){return Me("authorization/mark-setup-approved")}o(hC,"buildMarkAuthorizationSetupApprovedPath");function gC(){return Me("authorization/decide-setup")}o(gC,"buildDecideAuthorizationSetupPath");function yC(){return Me("token/exchange-authorization-code")}o(yC,"buildExchangeAuthorizationCodePath");function SC(){return Me("token/refresh")}o(SC,"buildRefreshTokenPath");function _C(){return Me("token/revoke")}o(_C,"buildRevokeOAuthTokenPath");function vC(){return Me("token/validate-access-token")}o(vC,"buildValidateAccessTokenPath");function wC(){return Me("mcp/authorize-and-load-connections")}o(wC,"buildAuthorizeAndLoadConnectionsPath");function bC(){return Me("upstream-oauth-state/save")}o(bC,"buildSaveUpstreamOAuthStatePath");function RC(){return Me("upstream-oauth-state/consume")}o(RC,"buildConsumeUpstreamOAuthStatePath");function CC(){return Me("browser-connect-ticket/consume")}o(CC,"buildConsumeBrowserConnectTicketPath");function IC(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(IC,"responseKeyMatchesLookup");function PC(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(PC,"authorizationSetupMatchesLookup");function ch(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(ch,"connectionMatchesLookup");function xC(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??"")&&Au(e.scopes,t.scopes)&&ku(e.expiresAt,t.expiresAt)&&kC(e.metadata,t.metadata)}o(xC,"connectionMatchesUpsertRecord");function ku(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}o(ku,"optionalTimestampInstantsMatch");function ih(e,t){return Date.parse(e)<=Date.parse(t)}o(ih,"timestampInstantIsAtOrBefore");function Au(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}o(Au,"stringArraysMatch");function kC(e,t){let r=sh(e),n=sh(t),a=Object.fromEntries(n);return r.length===n.length&&r.every(([i,s])=>a[i]===s)}o(kC,"metadataMatches");function sh(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}o(sh,"definedMetadataEntries");function we(e,t){throw Ko("internal_server_error",e,t)}o(we,"throwInvalidStorageResponse");function Ko(e,t,r){let n=Qe[e],a=n.status<500,i=a?r:new Error(t,r===void 0?void 0:{cause:r});return new E({message:a?t:n.publicDetail,extensionMembers:{[T]:e}},i===void 0?void 0:{cause:i})}o(Ko,"storageRuntimeError");async function AC(e,t){try{let r=await e.json();return r&&typeof r=="object"&&!Array.isArray(r)&&delete r.$schema,t.parse(r)}catch(r){we("Gateway Service storage response did not match the runtime storage contract.",r)}}o(AC,"parseRuntimeHttpStorageResponse");function uh(e,t){e.length!==t.length&&we("Gateway Service storage response item count did not match the request.");for(let[r,n]of e.entries()){let a=t[r];IC(n.key,a)||we("Gateway Service storage response key did not match the request."),n.connection!==void 0&&!ch(n.connection,a)&&we("Gateway Service storage response connection did not match the response key.")}}o(uh,"validateUpstreamConnectionItemsMatchLookups");function TC(e,t){PC(e,t)||we("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!ch(e.connection,t)&&we("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||!ku(e.connectionStatus.updatedAt,a))&&we("Gateway Service storage response authorization setup status did not match the connection.")}o(TC,"validateAuthorizationSetupResponseMatchesLookup");function EC(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&we("Gateway Service storage response registered client did not match the request.")}o(EC,"validateRegisterClientResponseMatchesRequest");function UC(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&we("Gateway Service storage response client did not match the request.")}o(UC,"validateReadClientResponseMatchesRequest");function OC(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)&&we("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)&&we("Gateway Service storage response started authorization principal did not match the request."))}o(OC,"validateStartAuthorizationResponseMatchesRequest");function xu(e,t){e.kind!=="available"&&e.kind!=="advanced"&&e.kind!=="marked"||((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==("nextStateHash"in t?t.nextStateHash:t.currentStateHash))&&we("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)&&we("Gateway Service storage response advanced authorization did not match the request."),"currentPrincipal"in t&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&we("Gateway Service storage response marked authorization principal did not match the request."),e.kind==="marked"&&"currentPrincipal"in t&&e.transaction.setupApprovedAt!==t.now&&we("Gateway Service storage response marked authorization setup approval timestamp did not match the request."))}o(xu,"validatePendingAuthorizationResponseMatchesRequest");function MC(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)&&we("Gateway Service storage response authorization setup transaction did not match the request.")}o(MC,"validateAuthorizationSetupDecisionResponseMatchesRequest");function zC(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||!ku(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&we("Gateway Service storage response authorization-code exchange did not match the request.")}o(zC,"validateExchangeAuthorizationCodeResponseMatchesRequest");function $C(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)&&we("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!ih(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!ih(e.accessToken.expiresAt,e.grant.expiresAt)||!DC(e.accessToken,e.grant))&&we("Gateway Service storage response token refresh access token did not match the request."))}o($C,"validateRefreshTokenResponseMatchesRequest");function qC(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&we("Gateway Service storage response access token did not match the request.")}o(qC,"validateAccessTokenValidationResponseMatchesRequest");function NC(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||!Au(e.principal.roles,e.accessToken.roles))&&we("Gateway Service storage response MCP authorization did not match the request."),uh(e.upstreamConnections,t.upstreamConnectionKeys))}o(NC,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function DC(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.virtualServerId===t.virtualServerId&&e.subjectId===t.subjectId&&e.scope===t.scope&&Au(e.roles,t.roles)}o(DC,"accessTokenMatchesGrant");async function jC(e){try{return await e.clone().json()}catch{return}}o(jC,"readProblemDetails");async function HC(e){let t=await jC(e),r=ah(t)&&typeof t.status=="number"?t.status:e.status,n=ah(t)&&ar(t.code)?t.code:Vm(r);throw Ko(n,`Gateway Service storage request failed with HTTP ${r}.`)}o(HC,"throwRuntimeHttpStorageError");var Ui=class{static{o(this,"RuntimeHttpStorageClient")}#t;#r;constructor(t){this.#t=t.baseUrl??Eo.instance.zuploEdgeApiUrl,this.#r=t.fetch??fetch}#n(t){let r;try{r=new URL(t,this.#t)}catch(n){throw Ko("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 Ko("internal_server_error",`Gateway Service storage base URL must use http(s); got protocol "${r.protocol}" from ${JSON.stringify(this.#t)}.`);if(!r.hostname||aC.has(r.hostname))throw Ko("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"});um(a);let i=await this.#r(n,{method:"POST",headers:a,body:JSON.stringify(r)});return i.ok||await HC(i),{request:r,response:await AC(i,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],n=new Map,a=t.map(s=>{let c=Er(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+=oh){let c=r.slice(s,s+oh);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:cC(),requestSchema:Cf,responseSchema:If});return xC(n,r)||we("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:uC(),requestSchema:Pf,responseSchema:xf});return TC(n,r),n}async registerClient(t){let{request:r,response:n}=await this.#e({input:t,path:dC(),requestSchema:kf,responseSchema:Af});return EC(n,r),n}async readClient(t){let{request:r,response:n}=await this.#e({input:t,path:lC(),requestSchema:Tf,responseSchema:Ef});return UC(n,r),n}async startAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:pC(),requestSchema:Uf,responseSchema:Of});return OC(n,r),n}async readPendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:mC(),requestSchema:Mf,responseSchema:zf});return xu(n,r),n}async advancePendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:fC(),requestSchema:$f,responseSchema:qf});return xu(n,r),n}async markAuthorizationSetupApproved(t){let{request:r,response:n}=await this.#e({input:t,path:hC(),requestSchema:Nf,responseSchema:Df});return xu(n,r),n}async decideAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:gC(),requestSchema:jf,responseSchema:Hf});return MC(n,r),n}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:bC(),requestSchema:Xf,responseSchema:Qf});return r}async consumeUpstreamOAuthState(t){let{request:r,response:n}=await this.#e({input:t,path:RC(),requestSchema:eh,responseSchema:th});return n.kind==="available"&&n.record.id!==r.id&&we("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:CC(),requestSchema:rh,responseSchema:nh});return r}async exchangeAuthorizationCode(t){let{request:r,response:n}=await this.#e({input:t,path:yC(),requestSchema:Lf,responseSchema:Bf});return zC(n,r),n}async refreshToken(t){let{request:r,response:n}=await this.#e({input:t,path:SC(),requestSchema:Gf,responseSchema:Vf});return $C(n,r),n}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:_C(),requestSchema:Ff,responseSchema:Zf});return r}async validateAccessToken(t){let{request:r,response:n}=await this.#e({input:t,path:vC(),requestSchema:Kf,responseSchema:Jf});return qC(n,r),n}async authorizeAndLoadConnections(t){let{request:r,response:n}=await this.#e({input:t,path:wC(),requestSchema:Wf,responseSchema:Yf});return NC(n,r),n}async#o(t){let r={items:[...t]},{response:n}=await this.#e({input:r,path:sC(),requestSchema:Rf,responseSchema:Ru});return uh(n.items,t),n.items.map(a=>a.connection)}};var LC="__zuploMcpGatewayStorageBackend",Tu;function BC(){return new Ui({})}o(BC,"buildProductionStorageBackend");function Y(){let e=globalThis[LC];return e||(Tu||(Tu=BC()),Tu)}o(Y,"getStorage");function GC(e,t){let r=yu(e),n=Lo(e),a=t.ownerMode??t.routeBinding?.ownerMode,i=t.upstreamAuthMode??t.routeBinding?.authMode,s=t.virtualServerName??t.routeBinding?.virtualServerId??n?.virtualServerId,c=t.upstreamServerName??t.routeBinding?.upstreamServerId??n?.upstreamServerId,d=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName,p=t.authProfileId??t.routeBinding?.authProfileId??n?.authProfileId;return _m(e,{...t,subjectId:r?.subjectId,ownerMode:a,upstreamAuthMode:i,virtualServerName:s,upstreamServerName:c,upstreamServerTitle:d,authProfileId:p})}o(GC,"buildMcpAnalyticsMetadata");function J(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,GC(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(J,"emitMcpAnalyticsEvent");import{base64url as Eu}from"jose";var VC="sha256:",FC=32;function dh(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(dh,"copyToArrayBuffer");function ir(){let e=crypto.getRandomValues(new Uint8Array(FC));return Eu.encode(e)}o(ir,"createOpaqueToken");async function fe(e){let t=await crypto.subtle.digest("SHA-256",dh(new TextEncoder().encode(e)));return`${VC}${Eu.encode(new Uint8Array(t))}`}o(fe,"hashOpaqueValue");async function lh(e){let t=await crypto.subtle.digest("SHA-256",dh(new TextEncoder().encode(e)));return Eu.encode(new Uint8Array(t))}o(lh,"calculatePkceS256Challenge");function Uu(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(Uu,"readBearerToken");function ZC(e,t,r){return xr(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(ZC,"gatewayAuthenticationRequiredResponse");function KC(e){switch(e){case"expired":return"expired_token";case"revoked":return"revoked_token";case"missing":return"invalid_token";default:{let t=e;return"invalid_token"}}}o(KC,"tokenValidationReasonCode");async function JC(e,t,r){let n=await Y().validateAccessToken({tokenHash:await fe(e),now:oe(new Date)});if(n.kind!=="valid"){t.log.warn({event:"gateway_access_token_validate_failed",code:"authentication_required",validationKind:n.kind,virtualServerId:r},"Gateway access token validation failed");let a=KC(n.kind);throw J(t,{eventType:F.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r,reasonClass:"auth",reasonCode:a,attributes:{validationKind:n.kind}}),J(t,{eventType:F.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r,httpStatusCode:401,reasonClass:"auth",reasonCode:a}),D("authentication_required","Gateway access token is expired, revoked, or invalid.")}return n.record}o(JC,"validateGatewayAccessToken");function WC(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"),J(t,{eventType:F.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:e.virtualServerId,reasonClass:"auth",reasonCode:"invalid_audience"}),J(t,{eventType:F.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:e.virtualServerId,httpStatusCode:401,reasonClass:"auth",reasonCode:"invalid_audience"}),D("authentication_required","Gateway access token was not issued for this MCP resource.")}o(WC,"assertAccessTokenResource");function YC(e,t,r){return xr(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":xi({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${_e} scope required by this MCP resource.`,scope:_e})}})}o(YC,"insufficientScopeResponse");function XC(e){return{subjectId:e.subjectId,roles:e.roles}}o(XC,"principalFromAccessToken");function QC(e){let t=dt(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"),xr(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":xi({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(QC,"gatewayTokenRejectedResponse");async function Ou(e,t){let r=qn(t),n=Ar(r.virtualServerId,e.url),a=Uu(e),i=xi({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"),J(t,{eventType:F.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,httpStatusCode:401,reasonClass:"auth",reasonCode:"missing_token"}),ZC(e,t,i);try{let s=await JC(a,t,r.virtualServerId);if(WC({accessToken:s,resource:n,virtualServerId:r.virtualServerId},t),s.scope!==_e)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:s.scope,requiredScope:_e,virtualServerId:r.virtualServerId,clientId:s.clientId},"Gateway access token does not have the required MCP scope"),J(t,{eventType:F.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,reasonClass:"auth",reasonCode:"insufficient_scope",attributes:{tokenScope:s.scope,requiredScope:_e,clientId:s.clientId}}),J(t,{eventType:F.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,httpStatusCode:403,reasonClass:"auth",reasonCode:"insufficient_scope"}),YC(e,t,r.virtualServerId);let c=XC(s);return lf(t,c),ou(t,c),J(t,{eventType:F.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",virtualServerName:r.virtualServerId,attributes:{clientId:s.clientId}}),e}catch(s){return QC({request:e,context:t,error:s,virtualServerId:r.virtualServerId})}}o(Ou,"gatewayTokenInbound");var Fn={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},eI="oauth-protected-resource-metadata",tI="/.well-known/oauth-protected-resource/";function rI(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}o(rI,"readRouteOperationId");function nI(e){return e.hasGatewayRouteContext?Fn.VIRTUAL_MCP_SERVER:e.routeOperationId===eI||e.routeOperationId===void 0&&e.routePath.startsWith(tI)?Fn.OAUTH_PROTECTED_RESOURCE_METADATA:Fn.OTHER}o(nI,"classifyAnalyticsRouteSurface");function oI(e){let t=e.route.path;return{routePath:t,routeSurface:nI({routePath:t,routeOperationId:rI(e),hasGatewayRouteContext:Lo(e)!==void 0})}}o(oI,"readAnalyticsRequestContext");function aI(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Fn.VIRTUAL_MCP_SERVER}o(aI,"isIntentionalMethodRejection");function iI(e){return aI(e)||e.response.status===401&&e.routeSurface===Fn.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(iI,"classifyRequestCompletedOutcome");async function Mu(e,t){let r=Date.now(),n=oI(t);return J(t,{eventType:F.MCP_REQUEST_RECEIVED,outcome:"success",routeSurface:n.routeSurface,httpMethod:e.method}),vc.getContextExtensions(t).addHandlerResponseHook(a=>{let i=iI({response:a,routeSurface:n.routeSurface});J(t,{eventType:F.MCP_REQUEST_COMPLETED,outcome:i,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(Mu,"analyticsContextInbound");function sI(e){return e instanceof Response}o(sI,"isResponse");async function Jo(e,t){let n={virtualServerId:ph(t.route.path).virtualServerId};$m(t,n),Gm(t,n);let a=await Mu(e,t);return sI(a)?a:Ou(a,t)}o(Jo,"mcpOAuthInboundPolicy");function Oi(e,t,r){let n=e.safeParse(t);if(n.success)return n.data;throw new q(`${r} is misconfigured. Validation failed:
33
+ ${cI(n.error)}`,{cause:n.error})}o(Oi,"parseConfigOrThrow");function cI(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
34
+ `)}o(cI,"formatZodIssues");var uI=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.'}),dI=u.object({auth0Domain:uI,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({error:"clientSecret is required and must be a string"}).trim().min(1,"clientSecret is required (commonly set via $env(AUTH0_CLIENT_SECRET))"),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(),zu=class extends Un{static{o(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,r){let n=mh(t,r);super(n,r),this.#t=hh(n,r)}async handler(t,r){return zt("policy.inbound.mcp-auth0-oauth"),Nn(r,this.#t),Jo(t,r)}};function mh(e,t){return Oi(dI,e,`MCP Auth0 OAuth policy "${t}"`)}o(mh,"parseAuth0OAuthOptions");function fh(e,t="mcp-auth0-oauth-inbound"){let r=mh(e,t);return hh(r,t)}o(fh,"auth0OptionsToMcpOAuthRuntimeConfig");function hh(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 Hm({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 q(`MCP Auth0 OAuth policy "${t}" is misconfigured. Check the policy options in policies.json.${c}`,s instanceof Error?{cause:s}:void 0)}}o(hh,"buildAuth0McpOAuthRuntimeConfig");var $u=class extends Un{static{o(this,"McpOAuthInboundPolicy")}#t;constructor(t,r){let n=qu(t,r);super(n,r),this.#t=n}async handler(t,r){return zt("policy.inbound.mcp-oauth"),Nn(r,this.#t),Jo(t,r)}};function qu(e,t="mcp-oauth-inbound"){return Oi(ru,e,`MCP OAuth policy "${t}"`)}o(qu,"mcpOAuthOptionsToRuntimeConfig");var Nu=["mcp-oauth-inbound","mcp-auth0-oauth-inbound"],gh={"mcp-oauth-inbound":"McpOAuthInboundPolicy","mcp-auth0-oauth-inbound":"McpAuth0OAuthInboundPolicy"};function lI(e,t,r){switch(e){case"mcp-oauth-inbound":return qu(r,t);case"mcp-auth0-oauth-inbound":return fh(r,t);default:return}}o(lI,"parseMcpOAuthPolicyConfig");function yh(e){return e!==void 0&&Nu.some(t=>t===e)}o(yh,"isMcpOAuthInboundPolicyType");function Du(e){switch(e.policyType){case"mcp-oauth-inbound":return e.handler.export===gh["mcp-oauth-inbound"];case"mcp-auth0-oauth-inbound":return e.handler.export===gh["mcp-auth0-oauth-inbound"];default:return!1}}o(Du,"isMcpOAuthRuntimeConfigPolicy");function Sh(e){if(!e)return;let t=e.filter(Du);if(t.length>1){let a=t.map(i=>`"${i.name}" (${i.policyType})`).join(", ");throw new q(`MCP gateway found multiple OAuth policies in policies.json: ${a}. Use exactly one MCP OAuth policy for the gateway so internal OAuth routes resolve a single runtime config.`)}let r=t[0];if(!r)return;let n=lI(r.policyType,r.name,r.handler.options);if(!n)throw new q(`MCP gateway: policy '${r.name}' has unsupported MCP OAuth policy type '${r.policyType}'.`);return{policyName:r.name,config:n}}o(Sh,"resolveMcpOAuthRuntimeConfigFromPolicies");de();var wh=et,pI=u.object({mode:u.literal("auto")}).strict(),mI=u.object({mode:u.literal("manual"),clientId:u.string().trim().min(1),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:au.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"]})}),bh=u.discriminatedUnion("mode",[pI,mI]),fI=bh.default({mode:"auto"}),ju=u.object({scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:fI}).strict(),_h=ju.extend({redirectPath:u.string().startsWith("/auth/connections/")}).strict(),Rh=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),hI=new Set([...Rh,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),gI=u.object({kind:u.literal("bearer_token"),token:u.string().min(1)}).strict(),yI=u.object({kind:u.literal("headers"),headers:u.array(u.object({name:wi,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();Rh.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)}}),Hu=u.discriminatedUnion("kind",[gI,yI]),SI=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(),_I=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key"),capture:u.enum(["browser_login"]).optional()}).strict(),Lu=u.discriminatedUnion("kind",[SI,_I]),Bu=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key")}).strict(),vI=u.discriminatedUnion("mode",[u.object({mode:u.literal("shared-oauth"),oauth:_h}).strict(),u.object({mode:u.literal("user-oauth"),oauth:_h}).strict(),u.object({mode:u.literal("static-secret"),secret:Hu}).strict(),u.object({mode:u.literal("user-secret"),secret:Lu}).strict(),u.object({mode:u.literal("shared-secret"),secret:Bu}).strict()]),wI=u.object({baseUrl:u.url(),resourceMetadataUrl:u.url(),requestHeaders:u.array(iu).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let i=a.name.toLowerCase();hI.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)}}),aH=u.object({displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:zn.optional(),authProfiles:u.record(tt,vI),transport:wI}).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"]})}),bI=u.object({"shared-oauth":ju.optional(),"user-oauth":ju.optional(),"static-secret":u.object({secret:Hu}).strict().optional(),"user-secret":u.object({secret:Lu}).strict().optional(),"shared-secret":u.object({secret:Bu}).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"})}),vh=u.object({id:wh,displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:zn.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url(),requestHeaders:u.array(iu).default([]),authProfiles:bI}).strict(),RI=u.object({name:wi,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict(),Mi={id:wh.optional(),displayName:u.string().min(1),summary:u.string().min(1).optional(),serverInfo:zn.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url().optional(),requestHeaders:u.array(RI).default([])},CI=u.discriminatedUnion("authMode",[u.object({...Mi,authMode:u.enum(["shared-oauth","user-oauth"]),scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:bh.optional(),clientId:u.string().trim().min(1).optional(),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:au.optional()}).strict(),u.object({...Mi,authMode:u.literal("static-secret"),secret:Hu}).strict(),u.object({...Mi,authMode:u.literal("user-secret"),secret:Lu}).strict(),u.object({...Mi,authMode:u.literal("shared-secret"),secret:Bu}).strict()]);function II(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
35
+ `)}o(II,"formatZodIssues");function Ch(e){throw new q(e)}o(Ch,"throwGatewayConfigError");function PI(e){let t="mcp-upstream-";return e.startsWith(t)||Ch(`Upstream policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`),et.parse(e.slice(t.length))}o(PI,"inferUpstreamConnectionIdFromPolicyName");function xI(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}o(xI,"buildDefaultProtectedResourceMetadataUrl");function Zn(e,t){return tt.parse(`${e}:${t}`)}o(Zn,"buildUpstreamAuthProfileId");function zi(e,t){try{let r=vh.safeParse(e);if(r.success)return r.data;let n=CI.parse(e),a=n.id??(t===void 0?void 0:PI(t));a===void 0&&Ch("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 vh.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??xI(n.mcpUrl),requestHeaders:i,authProfiles:s})}catch(r){if(r instanceof u.ZodError){let n=t===void 0?"MCP upstream policy":`Policy "${t}"`;throw new q(`${n} is misconfigured. Missing/invalid options in policies.json:
36
+ ${II(r)}`,{cause:r})}throw r}}o(zi,"parseUpstreamConnectionPolicyOptions");function Ih(e){return e.mode==="shared-oauth"||e.mode==="user-oauth"}o(Ih,"isUpstreamOAuthAuthConfig");de();var kI=u.looseObject({name:u.string().min(1),version:u.string().min(1).optional()}),AI=u.looseObject({}),TI=u.looseObject({name:kr,namespace:kr.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional(),inputSchema:AI}),EI=u.looseObject({name:kr,namespace:kr.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional()}),UI=u.looseObject({name:kr,uri:u.string().min(1),upstreamPolicy:u.string().min(1).optional(),upstreamUri:u.string().min(1).optional(),enabled:u.boolean().optional()}),OI=u.enum(["openapi","upstream_mcp"]),MI=u.object({catalogSource:OI.default("openapi"),serverInfo:kI.optional(),tools:u.array(TI).default([]),prompts:u.array(EI).default([]),resources:u.array(UI).default([])}).strict();function zI(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
37
+ `)}o(zI,"formatZodIssues");function Ph(e,t){let r=MI.safeParse(e??{});if(!r.success){let n=t===void 0?"MCP virtual server route":`MCP virtual server route ${t}`;throw new q(`${n} is misconfigured. Missing/invalid handler options in routes.oas.json:
38
+ ${zI(r.error)}`,{cause:r.error})}return r.data}o(Ph,"parseVirtualServerRouteOptions");function $i(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o($i,"toMcpTool");function qi(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(qi,"toMcpPrompt");function Ni(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o(Ni,"toMcpResource");var $I="mcp-upstream-connection-inbound";function ze(e){throw new q(e)}o(ze,"throwRegistryError");function qI(e,t,r){let n=new q(t,r===void 0?void 0:{cause:r});return n.extensionMembers={[T]:e},n}o(qI,"configurationProblem");function NI(e){return e.policyType===$I}o(NI,"isUpstreamConnectionPolicy");function DI(e){return yh(e.policyType)}o(DI,"isMcpOAuthInboundPolicy");function xh(e){if(e instanceof q)return e;if(e instanceof u.ZodError)return new q("MCP virtual server route is misconfigured. Check routes.oas.json for invalid MCP virtual server ids, upstream auth modes, or handler options.",{cause:e});throw new K("MCP virtual server route registration failed unexpectedly.",e instanceof Error?{cause:e}:void 0)}o(xh,"toRouteConfigurationError");function jI(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&ze(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&ze(`Upstream policy ${e.policyName} does not declare an auth mode.`),vi.parse(r)}o(jI,"readSingleAuthMode");function HI(e){let t=`/auth/connections/${encodeURIComponent(e.connection.id)}/callback`;switch(e.authMode){case"shared-oauth":{let r=e.connection.authProfiles["shared-oauth"];return r||ze(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:e.authMode,oauth:{scopes:r.scopes,scopeDelimiter:r.scopeDelimiter,redirectPath:t,clientRegistration:r.clientRegistration}}}case"user-oauth":{let r=e.connection.authProfiles["user-oauth"];return r||ze(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:e.authMode,oauth:{scopes:r.scopes,scopeDelimiter:r.scopeDelimiter,redirectPath:t,clientRegistration:r.clientRegistration}}}case"static-secret":{let r=e.connection.authProfiles["static-secret"];return r||ze(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:"static-secret",secret:r.secret}}case"user-secret":{let r=e.connection.authProfiles["user-secret"];return r||ze(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:"user-secret",secret:r.secret}}case"shared-secret":{let r=e.connection.authProfiles["shared-secret"];return r||ze(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:"shared-secret",secret:r.secret}}}}o(HI,"buildResolvedAuthConfig");function LI(e){let t=jI({policyName:e.policyName,connection:e.connection}),r=Zn(e.connection.id,t),n=HI({connection:e.connection,authMode:t}),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(LI,"buildRegisteredConnection");function BI(e){let t=new Map;for(let r of e)t.has(r.name)&&ze(`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(BI,"buildPolicyMap");function GI(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(GI,"readOperationId");function VI(e){let t=GI(e);return t||ze(`MCP virtual server route ${e.path} must declare operationId in routes.oas.json. The operationId is used as the stable MCP server identity for OAuth tokens, storage, upstream auth state, and analytics.`),Ue.parse(t)}o(VI,"readVirtualServerIdFromOperationId");function kh(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`,r=kr.safeParse(t);return r.success||ze(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`),r.data}o(kh,"buildPublishedCapabilityName");function Fu(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||ze(`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;ze(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o(Fu,"readCapabilityUpstreamPolicy");function Gu(e){e.seen.has(e.key)&&ze(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(Gu,"assertUniqueCatalogKey");function FI(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=kh({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:Fu({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(FI,"normalizeCatalogTool");function ZI(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=kh({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:Fu({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(ZI,"normalizeCatalogPrompt");function KI(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:Fu({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o(KI,"normalizeCatalogResource");function JI(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>FI({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>ZI({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>KI({resource:d,connections:e.connections,routePath:e.routePath})),i=new Set;for(let d of r)Gu({kind:"tool",key:d.name,routePath:e.routePath,seen:i});let s=new Set;for(let d of n)Gu({kind:"prompt",key:d.name,routePath:e.routePath,seen:s});let c=new Set;for(let d of a)Gu({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(JI,"normalizeVirtualServerCatalog");function WI(e){let t=new Map,r=new Map,n=new Map,a=new Map,i=new Set,s=new Set;function c(d){let p=a.get(d.name);if(p)return p;let l=zi(d.handler.options,d.name);i.has(l.id)&&ze(`Duplicate upstream MCP connection id ${l.id} in policies.json.`),i.add(l.id);let m=LI({policyName:d.name,connection:l});return a.set(d.name,m),m}o(c,"readConnectionForPolicy");for(let d of e.routes){let p=d.policies?.inbound??[];if(p.length===0)continue;let l=p[0],m=l===void 0?void 0:e.policyByName.get(l);if(!m||!DI(m))continue;let h;try{h=VI(d),s.has(h)&&ze(`Duplicate MCP virtual server operationId ${h} across routes.`),t.has(h)&&ze(`Duplicate MCP virtual server id ${h} across routes.`),r.has(d.path)&&ze(`Duplicate MCP virtual server route path ${d.path} across routes.`);let g=[];for(let v of p.slice(1)){let w=e.policyByName.get(v);!w||!NI(w)||g.push(c(w))}let S=Ph(d.handler.options,d.path),y=JI({catalog:S,connections:g,routePath:d.path});y.catalogSource==="upstream_mcp"&&g.length!==1&&ze(`MCP virtual server route ${d.path} uses upstream MCP catalog mode but declares ${g.length} upstream bindings; upstream MCP catalog mode requires exactly one upstream binding.`);let _={virtualServerId:h,operationId:h,routePath:d.path,handlerExport:d.handler.export,serverInfo:y.serverInfo,catalog:y,connections:g};t.set(h,_),r.set(d.path,_),s.add(h)}catch(g){if(h!==void 0)n.set(h,xh(g));else throw xh(g)}}return{byVirtualServerId:t,byRoutePath:r,virtualServerErrorsById:n,connectionsByPolicyName:a}}o(WI,"buildVirtualServers");function Zu(e){let t=BI(e.policies),{byVirtualServerId:r,byRoutePath:n,virtualServerErrorsById:a,connectionsByPolicyName:i}=WI({routes:e.routes,policyByName:t}),s=new Map;for(let c of i.values())s.set(c.upstreamServerId,c);return{byVirtualServerId:r,byRoutePath:n,connectionsById:s,virtualServerErrorsById:a}}o(Zu,"buildGatewayConnectionRegistry");var on,Vu;function Ah(e){Vu=e,on=void 0}o(Ah,"configureGatewayConnectionRegistrySource");function Th(e){on=e}o(Th,"setGatewayConnectionRegistry");function rt(){if(!on&&Vu&&(on=Zu(Vu)),!on)throw new q("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 on}o(rt,"getGatewayConnectionRegistry");function Nt(e){let t=rt(),r=t.virtualServerErrorsById?.get(e);if(r)throw r;let n=t.byVirtualServerId.get(e);if(!n)throw qI("unknown_virtual_server",`Unknown MCP virtual server: ${e}`,new Error(`Unknown MCP virtual server "${e}". Ensure routes.oas.json declares an MCP route for this virtual server and policies.json registers the matching MCP upstream connection policy.`));return n}o(Nt,"getRegisteredVirtualServer");function ph(e){let t=rt(),r=t.byRoutePath?.get(e)??[...t.byVirtualServerId.values()].find(n=>n.routePath===e);if(!r)throw new q(`MCP virtual server route ${e} is not registered. Ensure routes.oas.json declares operationId on this MCP route and its first inbound policy is an MCP OAuth policy.`);return r}o(ph,"getRegisteredVirtualServerByRoutePath");function Eh(){return on}o(Eh,"tryGetGatewayConnectionRegistry");function Ge(e){let t=rt().connectionsById.get(e);if(!t)throw new q(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return t.config}o(Ge,"getUpstreamServerConfig");function YI(e){let t=rt().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new q(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authProfileId}o(YI,"resolveUpstreamAuthProfileId");function Ur(e){YI(e);let t=rt().connectionsById.get(e.upstreamServerId);if(!t)throw new q(`Auth profile could not be resolved for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares the upstream connection before this handler runs.`);return t.authConfig}o(Ur,"getUpstreamAuthConfig");function an(e,t){let r=Ur({upstreamServerId:e,authProfileId:t});if(!Ih(r))throw new q(`Upstream server "${e}" does not use upstream OAuth. Select an auth mode that supports the requested upstream connect flow or remove the upstream OAuth route for this server.`);return r.oauth}o(an,"requireUpstreamOAuthConfig");function Dt(e){return new E({message:e,extensionMembers:{[T]:"invalid_request"}})}o(Dt,"invalidOutboundUrl");function XI(){let e=ni.__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(XI,"isTestOnlyAllowHttpLoopbackIdpEnabled");function QI(){let e=ni.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD;return typeof e=="string"&&e==="1"}o(QI,"isTestOnlyAllowHttpLoopbackCimdEnabled");var eP=new Set(["undefined","null","nan"]);function Ju(e,t){if(!e.hostname)throw Dt(`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(eP.has(e.hostname.toLowerCase()))throw Dt(`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(Ju,"assertSafeOutboundHostname");var tP=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),rP=[{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 Uh(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(Uh,"parseIpv4Octets");function nP([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(nP,"ipv4RangeMatches");function Oh(e){let t=Uh(e);return t!==void 0&&rP.some(r=>nP(t,r))}o(Oh,"isPrivateIpv4");function Ku(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(Ku,"parseIpv6Word");function oP(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(oP,"formatIpv4FromWords");function aP(e){let t=e.slice(7),r=Uh(t);if(r!==void 0)return r.join(".");let[n,a,i]=t.split(":"),s=Ku(n),c=Ku(a);return i===void 0&&s!==void 0&&c!==void 0?oP(s,c):void 0}o(aP,"parseIpv6MappedIpv4");function iP(e){return Ku(e.split(":").find(Boolean))}o(iP,"readFirstIpv6Hextet");function sP(e){let t=nr(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=aP(t);return n===void 0||Oh(n)}let r=iP(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(sP,"isPrivateIpv6");function Wu(e){let t=nr(e);return tP.has(t)||t.endsWith(".internal")||Oh(t)||sP(t)}o(Wu,"isBlockedOutboundHostname");function Mh(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw Dt(`Unsupported outbound protocol: ${t.protocol}`);Ju(t,e);let r=ke(t);if(t.protocol==="http:"&&!r)throw Dt("Configured outbound HTTP URLs must target loopback hosts.");let n=nr(t.hostname);if(!r&&Wu(n))throw Dt(`Blocked outbound host: ${n}`);return t}o(Mh,"validateConfiguredOutboundUrl");function zh(e){let t=new URL(e),r=ke(t),n=r&&XI();if(t.protocol!=="https:"&&!n)throw Dt("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw Dt("Identity provider URLs must not include credentials, query params, or fragments.");Ju(t,e);let a=nr(t.hostname);if(!r&&Wu(a))throw Dt(`Blocked identity provider host: ${a}`);return t}o(zh,"validateIdentityProviderUrl");function $h(e,t){let r=new URL(e),n=r.protocol==="http:"&&ke(r)&&QI();if(r.protocol!=="https:"&&!n||r.pathname==="/"||r.username||r.password||r.search||r.hash)throw Dt(`CIMD ${t} must be an HTTPS URL with a path and no credentials, query, or fragment.`);if(Ju(r,e),!n&&Wu(r.hostname))throw Dt(`CIMD ${t} points at a blocked host.`);return r}o($h,"validateCimdUrl");function Di(e){return $h(e,"client_id")}o(Di,"validateCimdClientMetadataUrl");function qh(e){return $h(e,"jwks_uri")}o(qh,"validateCimdClientJwksUrl");function Nh(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(Nh,"mergeAbortSignals");async function cP(e){try{await e.cancel()}catch{}}o(cP,"cancelReader");async function ji(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 cP(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(ji,"readBoundedByteStream");var uP=2,dP=1024*1024,lP=1e4,pP=new Set([301,302,303,307,308]),mP=["authorization","proxy-authorization","cookie","cookie2"];function Yu(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(Yu,"readRequestUrl");function Kn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(Kn,"readRequestMethod");function fP(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 new E({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[T]:r}})}o(fP,"assertContentLengthWithinLimit");async function hP(e,t,r){return fP(e,t,r),ji(e.body,{maxBytes:t,createLimitError:o(()=>new E({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[T]:r}}),"createLimitError")})}o(hP,"readBoundedResponseBody");function gP(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(gP,"responseFromBufferedBody");function yP(e,t){if(!pP.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(yP,"resolveRedirectUrl");function Dh(e,t){try{return t.validateUrl(e)}catch(r){throw new E({message:"Outbound URL was not allowed.",extensionMembers:{[T]:t.problemCode}},{cause:r})}}o(Dh,"validateOutboundUrl");function SP(e,t){throw e instanceof E&&ar(e.extensionMembers?.[T])?e:new E({message:"Outbound fetch failed.",extensionMembers:{[T]:t}},{cause:e})}o(SP,"normalizeFetchError");function Wo(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&&Xe(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Wo,"logOutboundFailure");async function _P(e,t,r,n,a,i,s){let c=Kn(r,n);try{return await t(r,n)}catch(d){let p=d instanceof DOMException&&d.name==="AbortError";Wo(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:c,host:St(i),error:d,extra:{abortReason:s()}}),SP(d,a)}}o(_P,"fetchWithNormalizedError");function vP(e){if(e.redirects>=e.maxRedirects)throw new E({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[T]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new E({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[T]:e.problemCode}})}o(vP,"assertRedirectAllowed");function wP(e,t){let r=new Headers(e);for(let n of mP)r.delete(n);for(let n of t)r.delete(n);return r}o(wP,"stripCrossOriginHeaders");function bP(e,t,r,n,a){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=wP(e.headers,a)),i}o(bP,"buildRedirectInit");function RP(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(RP,"buildInitialRequestInit");function CP(e){let t=Kn(e.currentInput,e.currentInit);vP({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Dh(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:bP(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(CP,"followRedirect");async function Xu(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??uP,i=r.maxResponseBytes??dP,s=r.timeoutMs??lP,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],p=r.context,l=new AbortController,m=Nh(l,t.signal),h=!1,g=setTimeout(()=>{h=!0,l.abort()},s),S=e,y=RP(e,t,l.signal),_;try{_=Dh(Yu(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(w){throw Wo(p,{event:"outbound_url_blocked",problemCode:n,method:Kn(e,t),host:St(Yu(e)),error:w}),clearTimeout(g),m?.(),w}let v=0;try{for(;;){let w=await _P(p,c,S,y,n,_,()=>h?`timeout_after_${s}ms`:void 0),b=yP(w,_);if(b!==void 0)try{let N=CP({currentInput:S,currentInit:y,currentUrl:_,redirectUrl:b,redirects:v,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:l.signal,additionalCrossOriginStrippedHeaders:d});S=N.currentInput,y=N.currentInit,_=N.currentUrl,v=N.redirects;continue}catch(N){throw Wo(p,{event:"outbound_redirect_blocked",problemCode:n,method:Kn(S,y),host:St(_),error:N,extra:{redirects:v,maxRedirects:a,redirectTargetHost:St(b)}}),N}try{return gP(w,await hP(w,i,n))}catch(N){throw Wo(p,{event:"outbound_response_size_exceeded",problemCode:n,method:Kn(S,y),host:St(_),error:N,extra:{maxResponseBytes:i,status:w.status}}),N}}}finally{clearTimeout(g),m?.()}}o(Xu,"runSafeOutboundExchange");async function Hi(e,t,r){let n=await Xu(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw Wo(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Kn(e,t),host:St(Yu(e)),error:a,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),new E({message:"Outbound JSON response could not be parsed.",extensionMembers:{[T]:r.problemCode??"invalid_request"}},{cause:a})}}o(Hi,"runSafeOutboundJsonExchange");function Jn(e,t={},r={}){return Xu(e,t,{...r,validateUrl:Mh})}o(Jn,"fetchConfiguredOutbound");function jh(e,t={},r={}){return Hi(e,t,{...r,validateUrl:zh})}o(jh,"fetchIdentityProviderJson");function Hh(e,t={},r={}){return Hi(e,t,{...r,validateUrl:Di})}o(Hh,"fetchCimdClientMetadataJson");function Lh(e,t={},r={}){return Hi(e,t,{...r,validateUrl:qh})}o(Lh,"fetchCimdClientJwksJson");var IP={"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 jt(e){return IP[e]}o(jt,"describeUpstreamAuthMode");function Li(e){return jt(e).ownerMode}o(Li,"resolveOwnerModeForUpstreamAuthMode");de();import{errors as Wh,jwtVerify as Yh,SignJWT as Xh}from"jose";var nt="zuplo-mcp-gateway",pt=nt,mt="HS256";import{base64url as PP}from"jose";var xP=new TextEncoder,kP="MCP gateway could not initialize secure key material.",AP=32,Bh=new Map,Gh=new Map,TP;function EP(){return TP??Eo.instance.authPrivateKey}o(EP,"readAuthPrivateKey");function Vh(e){return new K(kP,e===void 0?void 0:{cause:e})}o(Vh,"createGeneratedKeyMaterialError");function Fh(e,t){let r=PP.decode(t);if(r.byteLength!==AP)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(Fh,"decodeJwkKeyField");function UP(e){let t=EP();if(!t)throw Vh();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=Fh("d",r.d);Fh("x",r.x);let a=xP.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 Vh(r)}}o(UP,"decodeGeneratedKeyMaterial");function OP(e){let t=Bh.get(e);return t||(t=UP(e),Bh.set(e,t)),t}o(OP,"getMasterKeyMaterial");async function Ht(e){let t=Gh.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(OP(e.keyMaterialPurpose));return Gh.set(e.purpose,r),r}o(Ht,"readCachedDerivedKey");var MP="SHA-256";var zP="zuplo-mcp-gateway:",$P=new TextEncoder,Zh=new WeakMap;async function Or(e,t){let r=Zh.get(e);r||(r=new Map,Zh.set(e,r));let n=r.get(t);if(n)return n;let a=await qP(e,t);return r.set(t,a),a}o(Or,"deriveGatewaySigningKey");async function qP(e,t){let r=Kh(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=$P.encode(`${zP}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:MP,salt:new Uint8Array,info:Kh(a)},n,32*8);return new Uint8Array(i)}o(qP,"hkdfExpand");function Kh(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Kh,"copyToArrayBuffer");var Qh=15*60,NP=15*60,DP=hf.extend({id:Gn}),jP=DP.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),eg=Ln.extend({id:Zo,purpose:u.literal("browser_connect")}),HP=Ln.extend({purpose:u.literal("browser_connect")}),LP=eg.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),tg=Qh*1e3;async function rg(){return Ht({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Or(e,"oauth-state"),"derive")})}o(rg,"getOAuthStateKey");async function ng(){return Ht({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Or(e,"browser-connect"),"derive")})}o(ng,"getBrowserConnectKey");async function og(e){let t=Math.floor(Date.now()/1e3)+Qh;return new Xh(e).setProtectedHeader({alg:mt,typ:"JWT"}).setIssuer(nt).setAudience(pt).setIssuedAt().setExpirationTime(t).sign(await rg())}o(og,"signOAuthState");async function Bi(e){try{let{payload:t}=await Yh(e,await rg(),{algorithms:[mt],issuer:nt,audience:pt});return jP.parse(t)}catch(t){throw t instanceof Wh.JWTExpired?new E({message:"OAuth state has expired",extensionMembers:{[T]:"oauth_state_expired"}},{cause:t}):new E({message:"OAuth state could not be verified",extensionMembers:{[T]:"oauth_state_invalid"}},{cause:t})}}o(Bi,"verifyOAuthState");async function ag(e){let t=Math.floor(Date.now()/1e3)+NP,r=HP.parse(e),n=eg.parse({...r,id:vf()});return new Xh(n).setProtectedHeader({alg:mt,typ:"JWT"}).setIssuer(nt).setAudience(pt).setIssuedAt().setExpirationTime(t).sign(await ng())}o(ag,"signBrowserConnectTicket");async function Gi(e){try{let{payload:t}=await Yh(e,await ng(),{algorithms:[mt],issuer:nt,audience:pt});return LP.parse(t)}catch(t){throw t instanceof Wh.JWTExpired?new E({message:"Browser connect ticket has expired",extensionMembers:{[T]:"oauth_state_expired"}},{cause:t}):new E({message:"Browser connect ticket could not be verified",extensionMembers:{[T]:"oauth_state_invalid"}},{cause:t})}}o(Gi,"verifyBrowserConnectTicket");async function Vi(e){if((await Y().consumeBrowserConnectTicket({id:e.id,expiresAt:oe(new Date(e.exp*1e3)),now:oe(new Date)})).kind==="consumed")throw new E({message:"Browser connect ticket has already been used",extensionMembers:{[T]:"oauth_state_reused"}})}o(Vi,"consumeBrowserConnectTicket");function BP(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(BP,"buildConnectRequiredMessage");async function ig(e){let t=le(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 ag({...Fo(e),purpose:"browser_connect"})),r.toString()}o(ig,"buildGatewayBrowserTicketUrl");function GP(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(GP,"buildGatewayConnectPath");async function Qu(e){return ig({...e,path:GP(e.upstreamServerId),redirect:!0})}o(Qu,"buildGatewayConnectUrl");async function sg(e){return ig({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(sg,"buildGatewayAppPasswordCaptureUrl");async function Lt(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 Qu(t),message:BP(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(Lt,"buildRedirectConnectRequiredResponse");function Wn(e){return cg({...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(Wn,"buildAdminConnectRequiredResponse");function cg(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(cg,"buildAdminSetupRequiredResponse");function ug(e){return cg({...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(ug,"buildAdminStaticSecretRequiredResponse");de();import{base64url as Mr}from"jose";var VP="SHA-256",Xn="AES-GCM",FP=12,td="zuplo-secret",rd=1,dg="generated:auth_private_key:token-encryption",ZP=u.object({version:u.literal(rd),keyId:u.literal(dg),algorithm:u.literal(Xn),iv:u.string().min(1),ciphertext:u.string().min(1)}).strict();function Yn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Yn,"copyToArrayBuffer");async function ed(){return Ht({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(VP,Yn(e));return crypto.subtle.importKey("raw",t,{name:Xn},!1,["encrypt","decrypt"])},"derive")})}o(ed,"getEncryptionKey");function lg(e){return Yn(new TextEncoder().encode(`${td}:v${e.version}:${e.keyId}`))}o(lg,"getAssociatedData");function KP(e){return`${td}:v${e.version}:${Mr.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(KP,"encodeEnvelope");function JP(e){let t=`${td}:v${rd}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(Mr.decode(r));return ZP.parse(JSON.parse(n))}o(JP,"decodeEnvelope");async function sn(e){let t=await ed(),r=crypto.getRandomValues(new Uint8Array(FP)),n={version:rd,keyId:dg},a=await crypto.subtle.encrypt({name:Xn,iv:r,additionalData:lg(n)},t,new TextEncoder().encode(e));return KP({...n,algorithm:Xn,iv:Mr.encode(r),ciphertext:Mr.encode(new Uint8Array(a))})}o(sn,"encryptSecret");async function sr(e){let t=JP(e);if(t){let s=await ed(),c=await crypto.subtle.decrypt({name:Xn,iv:Yn(Mr.decode(t.iv)),additionalData:lg(t)},s,Yn(Mr.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw new K("Encrypted payload is malformed");let a=await ed(),i=await crypto.subtle.decrypt({name:Xn,iv:Yn(Mr.decode(r))},a,Yn(Mr.decode(n)));return new TextDecoder().decode(i)}o(sr,"decryptSecret");function WP(e,t){let r=Ur({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-secret")throw new q(`Upstream server "${e}" does not use tenant static credentials. Select the shared-secret auth mode for this upstream connection or remove the tenant static credential route.`);return r.secret}o(WP,"requireTenantStaticSecretConfig");function pg(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(pg,"hasUsableTenantStaticSecret");async function YP(e){if(!pg(e.connection))throw new K("Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await sr(e.connection.metadata.encryptedStaticSecret)}}o(YP,"resolveTenantStaticSecretCredential");async function mg(e){let t=Ge(e.upstreamServerId);WP(e.upstreamServerId,e.authProfileId);let r="preloadedConnection"in e?e.preloadedConnection:(await Y().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(pg(r))return{kind:"authorized",credential:await YP({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:ug(n)}}o(mg,"resolveTenantStaticSecretCredentialForRequest");de();async function nd(e){return Y().upsertUpstreamConnection({id:Ti(),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(nd,"upsertStaticSecretConnection");var XP=u.string().trim().min(1).max(320),QP=u.string().min(1).max(4096),ex=u.string().trim().min(1).max(4096);function od(e,t){let r=Ur({upstreamServerId:e,authProfileId:t});if(r.mode!=="user-secret")throw new q(`Upstream server "${e}" does not use user static credentials. Select the user-secret auth mode for this upstream connection or remove the user static credential route.`);return r.secret}o(od,"requireUserStaticSecretConfig");function tx(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o(tx,"encodeBase64Utf8");function rx(e){return`Basic ${tx(`${e.username}:${e.appPassword}`)}`}o(rx,"buildBasicAuthHeader");function fg(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(fg,"hasEncryptedUserStaticSecret");async function nx(e){if(!fg(e.connection))throw new K("Stored user static credential is incomplete.");if(e.connection.metadata.staticSecretKind==="bearer_token")return{type:"bearer_token",token:await sr(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:rx({username:e.connection.metadata.staticSecretUsername,appPassword:await sr(e.connection.metadata.encryptedStaticSecret)})}};throw new K("Stored user static credential kind is unsupported.")}o(nx,"resolveUserStaticSecretCredential");async function hg(e){if(od(e.upstreamServerId,e.authProfileId).kind!=="basic_auth_app_password")throw new K("This upstream does not use username and app-password credentials.");if(e.owner.mode!=="user")throw new K("User static credentials must be stored under a user-owned connection.");let r=XP.parse(e.username),n=QP.parse(e.appPassword);return nd({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await sn(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(hg,"saveUserStaticSecretCredential");async function Fi(e){let t=od(e.upstreamServerId,e.authProfileId);if(t.kind!=="bearer_token")throw new K("This upstream does not use bearer token credentials.");if(e.owner.mode!=="user")throw new K("User static credentials must be stored under a user-owned connection.");let r=ex.parse(e.token);return nd({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await sn(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(Fi,"saveUserStaticBearerTokenCredential");function ad(e,t){return od(e,t)}o(ad,"readUserStaticSecretCaptureConfig");async function gg(e){let t=Ge(e.upstreamServerId);if(e.owner.mode!=="user")throw new K("User static credential flow resolved a non-user owner.");let r="preloadedConnection"in e?e.preloadedConnection:(await Y().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(fg(r))return{kind:"authorized",credential:await nx({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 Lt(n)}}o(gg,"resolveUserStaticSecretCredentialForRequest");function yg(e){if(e.owner.mode!=="user")throw new K("User static credential capture requires a user-owned connection.");return sg({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(yg,"buildUserStaticSecretConnectUrl");var id;id=globalThis.crypto;async function ox(e){return(await id).getRandomValues(new Uint8Array(e))}o(ox,"getRandomValues");async function ax(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await ox(e-n.length);for(let i of a)i<r&&(n+=t[i%t.length])}return n}o(ax,"random");async function ix(e){return await ax(e)}o(ix,"generateVerifier");async function sx(e){let t=await(await id).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(sx,"generateChallenge");async function sd(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ix(e),r=await sx(t);return{code_verifier:t,code_challenge:r}}o(sd,"pkceChallenge");de();var Ne=mm().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ym.custom,message:"URL must be parseable",fatal:!0}),lm}).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"}),Zi=Pe({resource:f().url(),authorization_servers:R(Ne).optional(),jwks_uri:f().url().optional(),scopes_supported:R(f()).optional(),bearer_methods_supported:R(f()).optional(),resource_signing_alg_values_supported:R(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:ue().optional(),authorization_details_types_supported:R(f()).optional(),dpop_signing_alg_values_supported:R(f()).optional(),dpop_bound_access_tokens_required:ue().optional()}),Yo=Pe({issuer:f(),authorization_endpoint:Ne,token_endpoint:Ne,registration_endpoint:Ne.optional(),scopes_supported:R(f()).optional(),response_types_supported:R(f()),response_modes_supported:R(f()).optional(),grant_types_supported:R(f()).optional(),token_endpoint_auth_methods_supported:R(f()).optional(),token_endpoint_auth_signing_alg_values_supported:R(f()).optional(),service_documentation:Ne.optional(),revocation_endpoint:Ne.optional(),revocation_endpoint_auth_methods_supported:R(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:R(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:R(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:R(f()).optional(),code_challenge_methods_supported:R(f()).optional(),client_id_metadata_document_supported:ue().optional()}),cx=Pe({issuer:f(),authorization_endpoint:Ne,token_endpoint:Ne,userinfo_endpoint:Ne.optional(),jwks_uri:Ne,registration_endpoint:Ne.optional(),scopes_supported:R(f()).optional(),response_types_supported:R(f()),response_modes_supported:R(f()).optional(),grant_types_supported:R(f()).optional(),acr_values_supported:R(f()).optional(),subject_types_supported:R(f()),id_token_signing_alg_values_supported:R(f()),id_token_encryption_alg_values_supported:R(f()).optional(),id_token_encryption_enc_values_supported:R(f()).optional(),userinfo_signing_alg_values_supported:R(f()).optional(),userinfo_encryption_alg_values_supported:R(f()).optional(),userinfo_encryption_enc_values_supported:R(f()).optional(),request_object_signing_alg_values_supported:R(f()).optional(),request_object_encryption_alg_values_supported:R(f()).optional(),request_object_encryption_enc_values_supported:R(f()).optional(),token_endpoint_auth_methods_supported:R(f()).optional(),token_endpoint_auth_signing_alg_values_supported:R(f()).optional(),display_values_supported:R(f()).optional(),claim_types_supported:R(f()).optional(),claims_supported:R(f()).optional(),service_documentation:f().optional(),claims_locales_supported:R(f()).optional(),ui_locales_supported:R(f()).optional(),claims_parameter_supported:ue().optional(),request_parameter_supported:ue().optional(),request_uri_parameter_supported:ue().optional(),require_request_uri_registration:ue().optional(),op_policy_uri:Ne.optional(),op_tos_uri:Ne.optional(),client_id_metadata_document_supported:ue().optional()}),Ki=C({...cx.shape,...Yo.pick({code_challenge_methods_supported:!0}).shape}),Xo=C({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:Sm.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),_g=C({error:f(),error_description:f().optional(),error_uri:f().optional()}),Sg=Ne.optional().or(O("").transform(()=>{})),ux=C({redirect_uris:R(Ne),token_endpoint_auth_method:f().optional(),grant_types:R(f()).optional(),response_types:R(f()).optional(),client_name:f().optional(),client_uri:Ne.optional(),logo_uri:Sg,scope:f().optional(),contacts:R(f()).optional(),tos_uri:Sg,policy_uri:f().optional(),jwks_uri:Ne.optional(),jwks:hm().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),cd=C({client_id:f(),client_secret:f().optional(),client_id_issued_at:ne().optional(),client_secret_expires_at:ne().optional()}).strip(),Qo=ux.merge(cd),KL=C({error:f(),error_description:f().optional()}).strip(),JL=C({token:f(),token_type_hint:f().optional()}).strip();function vg(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(vg,"resourceUrlFromServerUrl");function wg({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(wg,"checkResourceAllowed");var Ce=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}},ea=class extends Ce{static{o(this,"InvalidRequestError")}};ea.errorCode="invalid_request";var cn=class extends Ce{static{o(this,"InvalidClientError")}};cn.errorCode="invalid_client";var un=class extends Ce{static{o(this,"InvalidGrantError")}};un.errorCode="invalid_grant";var dn=class extends Ce{static{o(this,"UnauthorizedClientError")}};dn.errorCode="unauthorized_client";var ta=class extends Ce{static{o(this,"UnsupportedGrantTypeError")}};ta.errorCode="unsupported_grant_type";var ra=class extends Ce{static{o(this,"InvalidScopeError")}};ra.errorCode="invalid_scope";var na=class extends Ce{static{o(this,"AccessDeniedError")}};na.errorCode="access_denied";var cr=class extends Ce{static{o(this,"ServerError")}};cr.errorCode="server_error";var oa=class extends Ce{static{o(this,"TemporarilyUnavailableError")}};oa.errorCode="temporarily_unavailable";var aa=class extends Ce{static{o(this,"UnsupportedResponseTypeError")}};aa.errorCode="unsupported_response_type";var ia=class extends Ce{static{o(this,"UnsupportedTokenTypeError")}};ia.errorCode="unsupported_token_type";var sa=class extends Ce{static{o(this,"InvalidTokenError")}};sa.errorCode="invalid_token";var ca=class extends Ce{static{o(this,"MethodNotAllowedError")}};ca.errorCode="method_not_allowed";var ua=class extends Ce{static{o(this,"TooManyRequestsError")}};ua.errorCode="too_many_requests";var ln=class extends Ce{static{o(this,"InvalidClientMetadataError")}};ln.errorCode="invalid_client_metadata";var da=class extends Ce{static{o(this,"InsufficientScopeError")}};da.errorCode="insufficient_scope";var la=class extends Ce{static{o(this,"InvalidTargetError")}};la.errorCode="invalid_target";var bg={[ea.errorCode]:ea,[cn.errorCode]:cn,[un.errorCode]:un,[dn.errorCode]:dn,[ta.errorCode]:ta,[ra.errorCode]:ra,[na.errorCode]:na,[cr.errorCode]:cr,[oa.errorCode]:oa,[aa.errorCode]:aa,[ia.errorCode]:ia,[sa.errorCode]:sa,[ca.errorCode]:ca,[ua.errorCode]:ua,[ln.errorCode]:ln,[da.errorCode]:da,[la.errorCode]:la};var xt=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function dx(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(dx,"isClientAuthMethod");var ud="code",dd="S256";function lx(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&dx(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(lx,"selectClientAuthMethod");function px(e,t,r,n){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":mx(a,i,r);return;case"client_secret_post":fx(a,i,n);return;case"none":hx(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(px,"applyClientAuthentication");function mx(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(mx,"applyBasicAuth");function fx(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(fx,"applyPostAuth");function hx(e,t){t.set("client_id",e)}o(hx,"applyPublicAuth");async function Cg(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=_g.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:s}=n,c=bg[a]||cr;return new c(i||"",s)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new cr(a)}}o(Cg,"parseErrorResponse");async function zr(e,t){try{return await ld(e,t)}catch(r){if(r instanceof cn||r instanceof dn)return await e.invalidateCredentials?.("all"),await ld(e,t);if(r instanceof un)return await e.invalidateCredentials?.("tokens"),await ld(e,t);throw r}}o(zr,"auth");async function ld(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 Pg(d,{fetchFn:i}),!c)try{c=await Ig(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 b=await wx(t,{resourceMetadataUrl:l,fetchFn:i});d=b.authorizationServerUrl,p=b.authorizationServerMetadata,c=b.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let m=await gx(t,e,c),h=n||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,g=await Promise.resolve(e.clientInformation());if(!g){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let b=p?.client_id_metadata_document_supported===!0,N=e.clientMetadataUrl;if(N&&!md(N))throw new ln(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${N}`);if(b&&N)g={client_id:N},await e.saveClientInformation?.(g);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Be=await Px(d,{metadata:p,clientMetadata:e.clientMetadata,scope:h,fetchFn:i});await e.saveClientInformation(Be),g=Be}}let S=!e.redirectUrl;if(r!==void 0||S){let b=await Ix(e,d,{metadata:p,resource:m,authorizationCode:r,fetchFn:i});return await e.saveTokens(b),"AUTHORIZED"}let y=await e.tokens();if(y?.refresh_token)try{let b=await Cx(d,{metadata:p,clientInformation:g,refreshToken:y.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Ce)||b instanceof cr))throw b}let _=e.state?await e.state():void 0,{authorizationUrl:v,codeVerifier:w}=await bx(d,{metadata:p,clientInformation:g,state:_,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(w),await e.redirectToAuthorization(v),"REDIRECT"}o(ld,"authInternal");function md(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(md,"isHttpsUrl");async function gx(e,t,r){let n=vg(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!wg({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(gx,"selectResourceURL");function fd(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=pd(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let s=pd(e,"scope")||void 0,c=pd(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}o(fd,"extractWWWAuthenticateParams");function pd(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(pd,"extractFieldFromWwwAuth");async function Ig(e,t,r=fetch){let n=await _x(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 Zi.parse(await n.json())}o(Ig,"discoverOAuthProtectedResourceMetadata");async function hd(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?hd(e,void 0,r):void 0;throw n}}o(hd,"fetchWithCorsRetry");function yx(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(yx,"buildWellKnownPath");async function Rg(e,t,r=fetch){return await hd(e,{"MCP-Protocol-Version":t},r)}o(Rg,"tryMetadataDiscovery");function Sx(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(Sx,"shouldAttemptFallback");async function _x(e,t,r,n){let a=new URL(e),i=n?.protocolVersion??br,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let d=yx(t,a.pathname);s=new URL(d,n?.metadataServerUrl??a),s.search=a.search}let c=await Rg(s,i,r);if(!n?.metadataUrl&&Sx(c,a.pathname)){let d=new URL(`/.well-known/${t}`,a);c=await Rg(d,i,r)}return c}o(_x,"discoverMetadataWithFallback");function vx(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(vx,"buildDiscoveryUrls");async function Pg(e,{fetchFn:t=fetch,protocolVersion:r=br}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=vx(e);for(let{url:i,type:s}of a){let c=await hd(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"?Yo.parse(await c.json()):Ki.parse(await c.json())}}}o(Pg,"discoverAuthorizationServerMetadata");async function wx(e,t){let r,n;try{r=await Ig(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 Pg(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o(wx,"discoverOAuthServerInfo");async function bx(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(ud))throw new Error(`Incompatible auth server: does not support response type ${ud}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(dd))throw new Error(`Incompatible auth server: does not support code challenge method ${dd}`)}else c=new URL("/authorize",e);let d=await sd(),p=d.code_verifier,l=d.code_challenge;return c.searchParams.set("response_type",ud),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",l),c.searchParams.set("code_challenge_method",dd),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(bx,"startAuthorization");function Rx(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(Rx,"prepareAuthorizationCodeRequest");async function xg(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=lx(n,l);px(m,n,d,r)}let p=await(s??fetch)(c,{method:"POST",headers:d,body:r});if(!p.ok)throw await Cg(p);return Xo.parse(await p.json())}o(xg,"executeTokenRequest");async function Cx(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 xg(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:s});return{refresh_token:n,...d}}o(Cx,"refreshAuthorization");async function Ix(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=Rx(a,p,e.redirectUrl)}let d=await e.clientInformation();return xg(t,{metadata:r,tokenRequestParams:c,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}o(Ix,"fetchToken");async function Px(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 Cg(s);return Qo.parse(await s.json())}o(Px,"registerClient");de();function gd(e){return`Zuplo MCP Gateway - ${e}`}o(gd,"buildGatewayOAuthClientName");function kg(e,t){let r=new URL(e,le(t));return ke(r)&&nr(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(kg,"buildGatewayOAuthRedirectUri");function yd(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(yd,"buildOAuthClientMetadataDocumentUrl");function Ag(e){return le(e)}o(Ag,"requireOAuthClientMetadataOrigin");function Tg(e,t,r){let n=Ge(t),a=an(t,r);return{client_id:yd({origin:e,upstreamServerId:t,authProfileId:r}),client_name:gd(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(Tg,"buildOAuthClientMetadataDocument");var xx=u.union([Qo,cd]),kx=u.object({authorizationServerUrl:u.url(),resourceMetadataUrl:u.url().optional(),resourceMetadata:Zi.optional(),authorizationServerMetadata:u.union([Yo,Ki]).optional()}).passthrough(),Ax="Bearer",Tx="__zuplo_refresh_only_upstream_access_token__";function Ex(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(Ex,"splitScopes");function Ux(e){return Ri.parse(e)}o(Ux,"parsePkceCodeVerifier");function Ox(e){if(typeof e.expires_in=="number")return oe(new Date(Date.now()+e.expires_in*1e3))}o(Ox,"readTokenExpiry");async function Eg(e){if(e!==void 0)return sn(JSON.stringify(e))}o(Eg,"encryptJson");async function Ug(e,t){if(!e)return;let r=await sr(e);try{return t.parse(JSON.parse(r))}catch(n){throw new E({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[T]:"oauth_state_invalid"}},{cause:n})}}o(Ug,"decryptJson");function Mx(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(Mx,"toOAuthDiscoveryState");function zx(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(zx,"clientInformationAllowsRedirectUri");function $x(e,t,r){let n=Ge(e),a=an(e,t),i;return a.scopes.length>0&&(i=a.scopes.join(a.scopeDelimiter)),{client_name:gd(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($x,"buildOAuthClientMetadata");function qx(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new q(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return Qo.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(qx,"buildManualOAuthClientInformation");function Nx(e,t,r){let n=yd({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return md(n)?n:void 0}o(Nx,"buildClientMetadataUrl");function Og(e){for(let t of e)if(t!==void 0)return t}o(Og,"firstDefined");function Dx(e){let t=an(e.target.upstreamServerId,e.target.authProfileId),r=$x(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:qx({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=Nx(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(Dx,"buildInitialOAuthClientSetup");function jx(e,t){if(t===void 0)return Og([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(jx,"readEncryptedClientInformation");function Hx(e){return Og([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(Hx,"readEncryptedDiscoveryState");var pn=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=Dx({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=jx(t,this.configuredClientInformation),this.encryptedDiscoveryState=Hx(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return og({id:t.id,...Fo({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 Eg(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Eg(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Xo.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??Ti(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await sn(r.access_token),encryptedRefreshToken:r.refresh_token?await sn(r.refresh_token):void 0,scopes:Ex(r.scope??this.clientMetadataValue.scope),expiresAt:Ox(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await Y().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Ux(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new E({message:"OAuth code verifier is missing",extensionMembers:{[T]:"oauth_state_invalid"}});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:_f(),...Fo({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:oe(new Date(Date.now()+tg)),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 Y().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 Ug(this.encryptedClientInformation,xx)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!zx(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=Mx(await Ug(this.encryptedDiscoveryState,kx))}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||this.connection.status!=="active")return;let t=this.connection.encryptedAccessToken?await sr(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await sr(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let n=Xo.parse({access_token:t??Tx,token_type:Ax,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=n,n}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 Y().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var Lx=3e4,Bx=256*1024,Gx=2;function Vx(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(Vx,"hasUsableAccessToken");var Fx="does not support dynamic client registration";function Zx(e){return e instanceof Error&&e.message.includes(Fx)}o(Zx,"isDynamicClientRegistrationUnsupported");function Kx(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(Kx,"readOAuthFetchRequest");function Jx(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(Jx,"responseLooksJson");function Mg(e){return async(t,r)=>{let n=Kx(t),a=await Jn(t,r,{maxRedirects:Gx,maxResponseBytes:Bx,problemCode:"upstream_token_exchange_failed",timeoutMs:Lx}),i=await a.clone().text();if(!Jx(a,i))return a;try{JSON.parse(i)}catch(s){throw new E({message:`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[T]:"upstream_token_exchange_failed"}},{cause:s})}return a}}o(Mg,"createUpstreamOAuthFetch");async function zg(e,t){try{return await zr(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Mg(t.upstreamServerId)})}catch(r){throw Zx(r)?new E({message:`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.`,extensionMembers:{[T]:"upstream_client_registration_required"}},{cause:r}):r}}o(zg,"runUpstreamOAuth");async function Wx(e,t){return zr(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Mg(t.upstreamServerId)})}o(Wx,"exchangeUpstreamAuthorizationCode");async function $g(e,t){let r=await zg(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new E({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}}):new E({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}})}o($g,"requireUpstreamAuthorizationRedirect");async function qg(e){if(Vx(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await zg(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 new E({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new E({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await tk({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(qg,"authorizeUpstreamOAuthSession");async function Yx(e){let t=await Bi(e.stateToken),r=await Y().consumeUpstreamOAuthState({id:t.id,now:oe(new Date)}),n=Xx(r);return Qx({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),ek(n),n}o(Yx,"consumeStoredCallbackState");function Xx(e){switch(e.kind){case"consumed":throw new E({message:"OAuth state has already been used",extensionMembers:{[T]:"oauth_state_reused"}});case"missing":throw new E({message:"OAuth state is missing or expired",extensionMembers:{[T]:"oauth_state_expired"}});case"available":return e.record}}o(Xx,"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 new E({message:"OAuth callback did not match the initiating request",extensionMembers:{[T]:"oauth_callback_mismatch"}})}o(Qx,"assertStoredCallbackStateMatches");function ek(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new E({message:"OAuth state has expired",extensionMembers:{[T]:"oauth_state_expired"}})}o(ek,"assertStoredCallbackStateFresh");async function tk(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),Wn(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),Lt(t)}o(tk,"buildOAuthConnectRequiredResponse");async function Ng(e){let t=await Yx({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Bn(t),[n]=await Y().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 pn(a),s=await Wx(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"?new E({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}}):new E({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[T]:"upstream_token_exchange_failed"}})}o(Ng,"finishUpstreamOAuthCallback");async function Dg(e){let t=Ge(e.upstreamServerId),r=an(e.upstreamServerId,e.authProfileId),n=kg(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await Y().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:le(e.request.url)}}}o(Dg,"prepareUpstreamOAuthRequest");async function jg(e){let t=await Dg(e),r=new pn({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return $g(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(jg,"startUpstreamConnect");async function Hg(e){let t=await Dg(e),r=new pn({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return qg({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(Hg,"authorizeUpstreamRequest");function rk(e,t){switch(e.kind){case"bearer_token":{if(!e.token)throw new q(`Static bearer token is not configured for upstream "${t}". Set the env var that backs the token or update the upstream connection policy to use a configured secret.`);return{type:"bearer_token",token:e.token}}case"headers":{let r={};for(let n of e.headers){if(!n.value)throw new q(`Static header "${n.name}" is not configured for upstream "${t}". Set the env var that backs the header or mark the header optional.`);r[n.name]=n.value}return{type:"headers",headers:r}}}}o(rk,"resolveStaticSecretCredential");async function Ji(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Hg({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 mg({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=Ur({upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId});if(n.mode!=="static-secret")throw new K(`Resolved static-secret credential context loaded ${n.mode} config.`);return{kind:"authorized",credential:rk(n.secret,t.upstreamServerId)}}case"user-secret":return gg({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}})}let r=t;throw new K(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}o(Ji,"resolveUpstreamCredentialForRoute");async function Lg(e){let t=Tr(e.principal.subjectId),r=rt().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 Fi({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o(Lg,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function Bg(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=jt(e.connectRequest.authMode);switch(n.connectSupport){case"oauth_authorization":t=await jg(r);break;case"user_secret_capture":t=await yg(r);break;case"none":throw new K(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(Bg,"startUpstreamConnectForRequest");async function Gg(e){let r=(await Bi(e.callbackRequest.state)).authProfileId,n=Ur({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(jt(n.mode).callbackSupport!=="authorization_code")throw new K(`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return Ng({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Ge(e.callbackRequest.upstreamServerId)})}o(Gg,"finishUpstreamCallbackForRequest");var Sd=new $t("route-upstream-bindings");function Vg(e){return`${e.upstreamServerId}:${e.authProfileId}`}o(Vg,"buildRouteBindingDuplicateKey");function _d(e,t){let r=Sd.get(e)??[],n=Vg(t);if(r.find(i=>Vg(i)===n)!==void 0)throw new K(`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.push(t),Sd.set(e,r)}o(_d,"appendResolvedUpstreamBindingContext");function Wi(e){return Sd.get(e)??[]}o(Wi,"readResolvedUpstreamBindingContexts");var nk=new Set(["authorization","connection","content-length","cookie","cookie2","host","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),ok=3e4,ak=2*1024*1024,ik=2,Yi="upstream_capability_invocation_failed",sk="upstream_capability_unavailable",ck="application/json";function uk(e){if(!e.authUrl)return{code:k.InvalidRequest,message:e.message};let t=new Ct([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message);return{code:t.code,message:t.message,data:t.data}}o(uk,"buildUrlElicitationError");async function dk(e){try{let t=await e.clone().json();return typeof t.id=="string"||typeof t.id=="number"?t.id:null}catch{return null}}o(dk,"readJsonRpcRequestId");async function Fg(e,t){return Response.json({jsonrpc:"2.0",id:await dk(e),error:uk(t)},{status:200,headers:{"content-type":ck}})}o(Fg,"connectRequiredMcpResponse");async function lk(e){let{routeBinding:t}=e;if(t.ownerMode!=="none")return t.owner.mode==="shared"?Wn({upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,upstreamDisplayName:t.upstreamDisplayName,virtualServerId:t.virtualServerId,requiresReconsent:!0}):Lt({requestUrl:e.request.url,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,upstreamDisplayName:t.upstreamDisplayName,virtualServerId:t.virtualServerId,subject:"virtual server",requiresReconsent:!0,...t.returnTo===void 0?{}:{returnTo:t.returnTo}})}o(lk,"buildReconsentPayload");function pk(e){return e.kind!=="authorized"||e.credential.type!=="headers"?[]:Object.keys(e.credential.headers)}o(pk,"readCredentialHeaderNames");function mk(e){let t=e.headers.get("retry-after");if(t!==null)return{"retry-after":t}}o(mk,"readRetryAfterHeaders");function fk(e,t,r){let n=mk(r),a=hk(r.status),i={code:a,detail:Qe[a].publicDetail};switch(a){case"authentication_required":return Ae.unauthorized(e,t,i,n);case"forbidden":return Ae.forbidden(e,t,i,n);case"not_found":return Ae.notFound(e,t,i,n);case"too_many_requests":return Ae.tooManyRequests(e,t,i,n);case"upstream_capability_unavailable":return Ae.serviceUnavailable(e,t,i,n);default:return Ae.badGateway(e,t,i,n)}}o(fk,"proxyUpstreamErrorResponse");function hk(e){switch(e){case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";case 429:return"too_many_requests";case 503:return sk;default:return"upstream_capability_invocation_failed"}}o(hk,"readProxyProblemCode");async function gk(e,t){zt("handler.mcp-upstream");let r=Wi(t);if(r.length!==1)throw new q(`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"),Fg(e,a.payload);let i=Ge(n.upstreamServerId),s=i.transport.baseUrl,c=new Headers;for(let[h,g]of e.headers.entries())nk.has(h.toLowerCase())||c.set(h,g);let d=[];for(let h of i.transport.requestHeaders??[]){if(h.value===void 0){if(h.required)throw new q(`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,g]of Object.entries(p.headers))c.set(h,g);break;case"mcp_oauth_provider":{let h=await p.provider.tokens();if(!h){t.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:n.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens");let g=await lk({request:e,routeBinding:n});return g!==void 0?Fg(e,g):Response.json({error:"no_upstream_tokens"},{status:401})}c.set("authorization",`${h.token_type??"Bearer"} ${h.access_token}`);break}}let l=[...d,...pk(a)],m={method:e.method,headers:c,body:e.method==="GET"||e.method==="HEAD"?void 0:e.body,duplex:"half"};t.log.info({event:"mcp_upstream_handler_proxy",upstreamServerId:n.upstreamServerId,upstreamUrl:s,method:e.method},"MCP upstream proxy: forwarding request");try{let h=await Jn(s,m,{additionalCrossOriginStrippedHeaders:l,context:t,maxRedirects:ik,maxResponseBytes:ak,problemCode:Yi,timeoutMs:ok});return h.ok?h:fk(e,t,h)}catch(h){if(!(h instanceof E)||h.extensionMembers?.[T]!==Yi)throw h;return Ae.badGateway(e,t,{code:Yi,detail:Qe[Yi].publicDetail})}}o(gk,"mcpUpstreamHandler");rb();function $r(e){return!!e._zod}o($r,"isZ4Schema");function Ke(e,t){return $r(e)?wc(e,t):e.safeParse(t)}o(Ke,"safeParse");function Qn(e){if(!e)return;let t;if($r(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}o(Qn,"getObjectShape");function Zg(e){if($r(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(Zg,"getLiteralValue");function qr(e){return e==="completed"||e==="failed"||e==="cancelled"}o(qr,"isTerminal");var Sk=Symbol("Let zodToJsonSchema decide on which parser to use");var IG=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function vd(e){let r=Qn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zg(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(vd,"getMethodLiteral");function wd(e,t){let r=Ke(e,t);if(!r.success)throw r.error;return r.data}o(wd,"parseWithCompat");var Ck=6e4,eo=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(si,r=>{this._oncancel(r)}),this.setNotificationHandler(li,r=>{this._onprogress(r)}),this.setRequestHandler(di,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(pi,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new I(k.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(fi,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 I(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 I(k.InvalidParams,`Task not found: ${i}`);if(!qr(s.status))return await this._waitForTaskUpdate(i,n.signal),await a();if(qr(s.status)){let c=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[Cr]:{taskId:i}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(hi,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 I(k.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(yi,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new I(k.InvalidParams,`Task not found: ${r.params.taskId}`);if(qr(a.status))throw new I(k.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 I(k.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(a){throw a instanceof I?a:new I(k.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),I.fromError(k.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),It(i)||Mn(i)?this._onresponse(i):qt(i)?this._onrequest(i,s):Pm(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=I.fromError(k.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?.[Cr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:k.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=Rm(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 I(k.ConnectionClosed,"Request was cancelled");let g={...h,relatedRequestId:t.id};i&&!g.relatedTask&&(g.relatedTask={taskId:i});let S=g.relatedTask?.taskId??i;return S&&d&&await d.updateTaskStatus(S,"input_required"),await this.request(l,m,g)},"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:k.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),It(t))n(t);else{let s=new I(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(It(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),It(t))a(t);else{let s=I.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 I?s:new I(k.InternalError,String(s))}}return}let i;try{let s=await this.request(t,rr,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new I(k.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},qr(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new I(k.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new I(k.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 I?s:new I(k.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(w=>{l(w)},"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(w){m(w);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,g={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),g.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),c&&(g.params={...g.params,task:c}),d&&(g.params={...g.params,_meta:{...g.params?._meta||{},[Cr]:d}});let S=o(w=>{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(w)}},{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(N=>this._onerror(new Error(`Failed to send cancellation: ${N}`)));let b=w instanceof I?w:new I(k.RequestTimeout,String(w));l(b)},"cancel");this._responseHandlers.set(h,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return l(w);try{let b=Ke(r,w.result);b.success?p(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{S(n?.signal?.reason)});let y=n?.timeout??Ck,_=o(()=>S(I.fromError(k.RequestTimeout,"Request timed out",{timeout:y})),"timeoutHandler");this._setupTimeout(h,y,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let v=d?.taskId;if(v){let w=o(b=>{let N=this._responseHandlers.get(h);N?N(b):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))},"responseResolver");this._requestResolvers.set(h,w),this._enqueueTaskMessage(v,{type:"request",message:g,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(h),l(b)})}else this._transport.send(g,{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(w=>{this._cleanupTimeout(h),l(w)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},mi,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},gi,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},km,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||{},[Cr]: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||{},[Cr]: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||{},[Cr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=vd(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,i)=>{let s=wd(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=vd(t);this._notificationHandlers.set(n,a=>{let i=wd(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"&&qt(a.message)){let i=a.message.id,s=this._requestResolvers.get(i);s?(s(new I(k.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 I(k.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new I(k.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 I(k.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=qo.parse({method:"notifications/tasks/status",params:c});await this.notification(d),qr(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 I(k.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(qr(c.status))throw new I(k.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=qo.parse({method:"notifications/tasks/status",params:d});await this.notification(p),qr(d.status)&&this._cleanupTaskProgressHandler(a)}},"updateTaskStatus"),listTasks:o(a=>n.listTasks(a,r),"listTasks")}}};function Kg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Kg,"isPlainObject");function Xi(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];Kg(s)&&Kg(i)?r[a]={...s,...i}:r[a]=i}return r}o(Xi,"mergeCapabilities");var M_=cm(ip(),1),z_=cm(O_(),1);function fO(){let e=new M_.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,z_.default)(e),e}o(fO,"createDefaultAjvInstance");var So=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??fO()}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 zs=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},tn,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 $s(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($s,"assertToolsCallTaskCapability");function qs(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(qs,"assertClientRequestTaskCapability");var Ns=class extends eo{static{o(this,"Server")}constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(jo.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 So,this.setRequestHandler(ci,n=>this._oninitialize(n)),this.setNotificationHandler(ui,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Yc,async(n,a)=>{let i=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,c=jo.safeParse(s);return c.success&&this._loggingLevels.set(i,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new zs(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Xi(this._capabilities,t)}setRequestHandler(t,r){let a=Qn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if($r(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=Ke(Do,d);if(!l.success){let S=l.error instanceof Error?l.error.message:String(l.error);throw new I(k.InvalidParams,`Invalid tools/call request: ${S}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let S=Ke(rr,h);if(!S.success){let y=S.error instanceof Error?S.error.message:String(S.error);throw new I(k.InvalidParams,`Invalid task creation result: ${y}`)}return S.data}let g=Ke(Ir,h);if(!g.success){let S=g.error instanceof Error?g.error.message:String(g.error);throw new I(k.InvalidParams,`Invalid tools/call result: ${S}`)}return g.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){qs(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&$s(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:Rr.includes(r)?r:br,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"},tr)}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},Ho,r):this.request({method:"sampling/createMessage",params:t},tn,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 I(k.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(s){throw s instanceof I?s:new I(k.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},tu,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 Ds=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}
39
39
  data:
40
40
 
41
41
  `;this._retryInterval!==void 0&&(s=`id: ${i}
@@ -46,17 +46,17 @@ data:
46
46
  `;return a&&(i+=`id: ${a}
47
47
  `),i+=`data: ${JSON.stringify(n)}
48
48
 
49
- `,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=>Wr.parse(v)):c=[Wr.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(du);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 w=this.validateProtocolVersion(t);if(w)return w}if(!c.some(Mt)){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=>du(v)),h=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??Xf;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:o(()=>{this._streamMapping.delete(l)},"cleanup")});for(let w of c)Mt(w)&&this._requestToStreamMapping.set(w.id,l);for(let w of c)this.onmessage?.(w,{authInfo:r?.authInfo,requestInfo:i})});let g=new TextEncoder,S,y=new ReadableStream({start:o(v=>{S=v},"start"),cancel:o(()=>{this._streamMapping.delete(l)},"cancel")}),_={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(_["mcp-session-id"]=this.sessionId);for(let v of c)Mt(v)&&(this._streamMapping.set(l,{controller:S,encoder:g,cleanup:o(()=>{this._streamMapping.delete(l);try{S.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(v.id,l));await this.writePrimingEvent(S,g,l,h);for(let v of c){let w,b;Mt(v)&&this._eventStore&&h>="2025-11-25"&&(w=o(()=>{this.closeSSEStream(v.id)},"closeSSEStream"),b=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i,closeSSEStream:w,closeStandaloneSSEStream:b})}return new Response(y,{status:200,headers:_})}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&&!vr.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${vr.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${vr.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((It(t)||Hn(t))&&(n=t.id),n===void 0){if(It(t)||Hn(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(It(t)||Hn(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 ho(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(!ho(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(!ho(e[s],t[s]))return!1;return!0}return e===t}o(ho,"deepCompareStrict");function dt(e){return encodeURI(QU(e))}o(dt,"encodePointer");function QU(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(QU,"escapePointer");var eO={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},tO={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},rO={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},nO=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 ur(e,t=Object.create(null),r=nO,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:ur(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(rO[i])continue;let s=`${n}/${dt(i)}`,c=e[i];if(Array.isArray(c)){if(eO[i]){let d=c.length;for(let p=0;p<d;p++)ur(c[p],t,r,`${s}/${p}`)}}else if(tO[i])for(let d in c)ur(c[d],t,r,`${s}/${dt(d)}`);else ur(c,t,r,s)}return t}o(ur,"dereference");var oO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,aO=[0,31,28,31,30,31,30,31,31,30,31,30,31],iO=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,sO=/^(?=.{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,cO=/^(?:[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,uO=/^(?:(?:[^\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,dO=/^(?:(?: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,lO=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,pO=/^(?:\/(?:[^~/]|~0|~1)*)*$/,mO=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,fO=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,hO=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"),gO=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,yO=/^((([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,SO=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 Gt(e){return e.test.bind(e)}o(Gt,"bind");var mp={date:k_,time:T_.bind(void 0,!1),"date-time":wO,duration:SO,uri:CO,"uri-reference":Gt(cO),"uri-template":Gt(uO),url:Gt(dO),email:hO,hostname:Gt(sO),ipv4:Gt(gO),ipv6:Gt(yO),regex:PO,uuid:Gt(lO),"json-pointer":Gt(pO),"json-pointer-uri-fragment":Gt(mO),"relative-json-pointer":Gt(fO)};function _O(e){return e%4===0&&(e%100!==0||e%400===0)}o(_O,"isLeapYear");function k_(e){let t=e.match(oO);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&_O(r)?29:aO[n])}o(k_,"date");function T_(e,t){let r=t.match(iO);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(T_,"time");var vO=/t|\s/i;function wO(e){let t=e.split(vO);return t.length==2&&k_(t[0])&&T_(!0,t[1])}o(wO,"date_time");var bO=/\/|:/,RO=/^(?:[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 CO(e){return bO.test(e)&&RO.test(e)}o(CO,"uri");var IO=/[^\\]\\Z/;function PO(e){if(IO.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(PO,"regex");var E_;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(E_||(E_={}));function U_(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(U_,"ucs2length");function Se(e,t,r="2019-09",n=ur(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:g,type:S,const:y,enum:_,required:v,not:w,anyOf:b,allOf:N,oneOf:j,if:He,then:lt,else:An,format:fr,properties:Ft,patternProperties:Gr,additionalProperties:wo,unevaluatedProperties:bo,minProperties:Ro,maxProperties:uc,propertyNames:Qp,dependentRequired:dc,dependentSchemas:lc,dependencies:pc,prefixItems:mc,items:Co,additionalItems:em,unevaluatedItems:tm,contains:rm,minContains:Zt,maxContains:Ja,minItems:fc,maxItems:hc,uniqueItems:Vw,minimum:Vr,maximum:Fr,exclusiveMinimum:Io,exclusiveMaximum:Po,multipleOf:Wa,minLength:Ya,maxLength:Xa,pattern:nm,__absolute_ref__:Qa,__absolute_recursive_ref__:Fw}=t,k=[];if(g===!0&&i===null&&(i=t),h==="#"){let H=i===null?n[Fw]:i,z=`${c}/$recursiveRef`,V=Se(e,i===null?t:i,r,n,a,H,s,z,d);V.valid||k.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:z,error:"A subschema had errors."},...V.errors)}if(m!==void 0){let z=n[Qa||m];if(z===void 0){let P=`Unresolved $ref "${m}".`;throw Qa&&Qa!==m&&(P+=` Absolute URI "${Qa}".`),P+=`
49
+ `,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=>en.parse(v)):c=[en.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(kc);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 w=this.validateProtocolVersion(t);if(w)return w}if(!c.some(qt)){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=>kc(v)),h=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??vm;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(l,{resolveJson:v,cleanup:o(()=>{this._streamMapping.delete(l)},"cleanup")});for(let w of c)qt(w)&&this._requestToStreamMapping.set(w.id,l);for(let w of c)this.onmessage?.(w,{authInfo:r?.authInfo,requestInfo:i})});let g=new TextEncoder,S,y=new ReadableStream({start:o(v=>{S=v},"start"),cancel:o(()=>{this._streamMapping.delete(l)},"cancel")}),_={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(_["mcp-session-id"]=this.sessionId);for(let v of c)qt(v)&&(this._streamMapping.set(l,{controller:S,encoder:g,cleanup:o(()=>{this._streamMapping.delete(l);try{S.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(v.id,l));await this.writePrimingEvent(S,g,l,h);for(let v of c){let w,b;qt(v)&&this._eventStore&&h>="2025-11-25"&&(w=o(()=>{this.closeSSEStream(v.id)},"closeSSEStream"),b=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:i,closeSSEStream:w,closeStandaloneSSEStream:b})}return new Response(y,{status:200,headers:_})}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&&!Rr.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Rr.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Rr.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((It(t)||Mn(t))&&(n=t.id),n===void 0){if(It(t)||Mn(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(It(t)||Mn(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 _o(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(!_o(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(!_o(e[s],t[s]))return!1;return!0}return e===t}o(_o,"deepCompareStrict");function ft(e){return encodeURI(hO(e))}o(ft,"encodePointer");function hO(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(hO,"escapePointer");var gO={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},yO={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},SO={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},_O=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 hr(e,t=Object.create(null),r=_O,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:hr(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(SO[i])continue;let s=`${n}/${ft(i)}`,c=e[i];if(Array.isArray(c)){if(gO[i]){let d=c.length;for(let p=0;p<d;p++)hr(c[p],t,r,`${s}/${p}`)}}else if(yO[i])for(let d in c)hr(c[d],t,r,`${s}/${ft(d)}`);else hr(c,t,r,s)}return t}o(hr,"dereference");var vO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,wO=[0,31,28,31,30,31,30,31,31,30,31,30,31],bO=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,RO=/^(?=.{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,CO=/^(?:[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,IO=/^(?:(?:[^\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,PO=/^(?:(?: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,xO=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,kO=/^(?:\/(?:[^~/]|~0|~1)*)*$/,AO=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,TO=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,EO=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"),UO=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,OO=/^((([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,MO=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 Jt(e){return e.test.bind(e)}o(Jt,"bind");var fp={date:$_,time:q_.bind(void 0,!1),"date-time":qO,duration:MO,uri:jO,"uri-reference":Jt(CO),"uri-template":Jt(IO),url:Jt(PO),email:EO,hostname:Jt(RO),ipv4:Jt(UO),ipv6:Jt(OO),regex:LO,uuid:Jt(xO),"json-pointer":Jt(kO),"json-pointer-uri-fragment":Jt(AO),"relative-json-pointer":Jt(TO)};function zO(e){return e%4===0&&(e%100!==0||e%400===0)}o(zO,"isLeapYear");function $_(e){let t=e.match(vO);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&zO(r)?29:wO[n])}o($_,"date");function q_(e,t){let r=t.match(bO);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(q_,"time");var $O=/t|\s/i;function qO(e){let t=e.split($O);return t.length==2&&$_(t[0])&&q_(!0,t[1])}o(qO,"date_time");var NO=/\/|:/,DO=/^(?:[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 jO(e){return NO.test(e)&&DO.test(e)}o(jO,"uri");var HO=/[^\\]\\Z/;function LO(e){if(HO.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(LO,"regex");var N_;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(N_||(N_={}));function D_(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(D_,"ucs2length");function Se(e,t,r="2019-09",n=hr(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:g,type:S,const:y,enum:_,required:v,not:w,anyOf:b,allOf:N,oneOf:j,if:Be,then:ht,else:En,format:wr,properties:Qt,patternProperties:Yr,additionalProperties:Io,unevaluatedProperties:Po,minProperties:xo,maxProperties:lc,propertyNames:tm,dependentRequired:pc,dependentSchemas:mc,dependencies:fc,prefixItems:hc,items:ko,additionalItems:rm,unevaluatedItems:nm,contains:om,minContains:er,maxContains:Ya,minItems:gc,maxItems:yc,uniqueItems:eb,minimum:Xr,maximum:Qr,exclusiveMinimum:Ao,exclusiveMaximum:To,multipleOf:Xa,minLength:Qa,maxLength:ei,pattern:am,__absolute_ref__:ti,__absolute_recursive_ref__:tb}=t,A=[];if(g===!0&&i===null&&(i=t),h==="#"){let H=i===null?n[tb]:i,z=`${c}/$recursiveRef`,V=Se(e,i===null?t:i,r,n,a,H,s,z,d);V.valid||A.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:z,error:"A subschema had errors."},...V.errors)}if(m!==void 0){let z=n[ti||m];if(z===void 0){let P=`Unresolved $ref "${m}".`;throw ti&&ti!==m&&(P+=` Absolute URI "${ti}".`),P+=`
50
50
  Known schemas:
51
51
  - ${Object.keys(n).join(`
52
- - `)}`,new Error(P)}let V=`${c}/$ref`,U=Se(e,z,r,n,a,i,s,V,d);if(U.valid||k.push({instanceLocation:s,keyword:"$ref",keywordLocation:V,error:"A subschema had errors."},...U.errors),r==="4"||r==="7")return{valid:k.length===0,errors:k}}if(Array.isArray(S)){let H=S.length,z=!1;for(let V=0;V<H;V++)if(l===S[V]||S[V]==="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 "${S.join('", "')}".`})}else S==="integer"?(l!=="number"||e%1||e!==e)&&k.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${S}".`}):S!==void 0&&l!==S&&k.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${S}".`});if(y!==void 0&&(l==="object"||l==="array"?ho(e,y)||k.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&k.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),_!==void 0&&(l==="object"||l==="array"?_.some(H=>ho(e,H))||k.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`}):_.some(H=>e===H)||k.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`})),w!==void 0){let H=`${c}/not`;Se(e,w,r,n,a,i,s,H).valid&&k.push({instanceLocation:s,keyword:"not",keywordLocation:H,error:'Instance matched "not" schema.'})}let ei=[];if(b!==void 0){let H=`${c}/anyOf`,z=k.length,V=!1;for(let U=0;U<b.length;U++){let P=b[U],B=Object.create(d),L=Se(e,P,r,n,a,g===!0?i:null,s,`${H}/${U}`,B);k.push(...L.errors),V=V||L.valid,L.valid&&ei.push(B)}V?k.length=z:k.splice(z,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:H,error:"Instance does not match any subschemas."})}if(N!==void 0){let H=`${c}/allOf`,z=k.length,V=!0;for(let U=0;U<N.length;U++){let P=N[U],B=Object.create(d),L=Se(e,P,r,n,a,g===!0?i:null,s,`${H}/${U}`,B);k.push(...L.errors),V=V&&L.valid,L.valid&&ei.push(B)}V?k.length=z:k.splice(z,0,{instanceLocation:s,keyword:"allOf",keywordLocation:H,error:"Instance does not match every subschema."})}if(j!==void 0){let H=`${c}/oneOf`,z=k.length,V=j.filter((U,P)=>{let B=Object.create(d),L=Se(e,U,r,n,a,g===!0?i:null,s,`${H}/${P}`,B);return k.push(...L.errors),L.valid&&ei.push(B),L.valid}).length;V===1?k.length=z:k.splice(z,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:H,error:`Instance does not match exactly one subschema (${V} matches).`})}if((l==="object"||l==="array")&&Object.assign(d,...ei),He!==void 0){let H=`${c}/if`;if(Se(e,He,r,n,a,i,s,H,d).valid){if(lt!==void 0){let V=Se(e,lt,r,n,a,i,s,`${c}/then`,d);V.valid||k.push({instanceLocation:s,keyword:"if",keywordLocation:H,error:'Instance does not match "then" schema.'},...V.errors)}}else if(An!==void 0){let V=Se(e,An,r,n,a,i,s,`${c}/else`,d);V.valid||k.push({instanceLocation:s,keyword:"if",keywordLocation:H,error:'Instance does not match "else" schema.'},...V.errors)}}if(l==="object"){if(v!==void 0)for(let U of v)U in e||k.push({instanceLocation:s,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${U}".`});let H=Object.keys(e);if(Ro!==void 0&&H.length<Ro&&k.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${Ro} properties.`}),uc!==void 0&&H.length>uc&&k.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${uc} properties.`}),Qp!==void 0){let U=`${c}/propertyNames`;for(let P in e){let B=`${s}/${dt(P)}`,L=Se(P,Qp,r,n,a,i,B,U);L.valid||k.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:U,error:`Property name "${P}" does not match schema.`},...L.errors)}}if(dc!==void 0){let U=`${c}/dependantRequired`;for(let P in dc)if(P in e){let B=dc[P];for(let L of B)L in e||k.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:U,error:`Instance has "${P}" but does not have "${L}".`})}}if(lc!==void 0)for(let U in lc){let P=`${c}/dependentSchemas`;if(U in e){let B=Se(e,lc[U],r,n,a,i,s,`${P}/${dt(U)}`,d);B.valid||k.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:P,error:`Instance has "${U}" but does not match dependant schema.`},...B.errors)}}if(pc!==void 0){let U=`${c}/dependencies`;for(let P in pc)if(P in e){let B=pc[P];if(Array.isArray(B))for(let L of B)L in e||k.push({instanceLocation:s,keyword:"dependencies",keywordLocation:U,error:`Instance has "${P}" but does not have "${L}".`});else{let L=Se(e,B,r,n,a,i,s,`${U}/${dt(P)}`);L.valid||k.push({instanceLocation:s,keyword:"dependencies",keywordLocation:U,error:`Instance has "${P}" but does not match dependant schema.`},...L.errors)}}}let z=Object.create(null),V=!1;if(Ft!==void 0){let U=`${c}/properties`;for(let P in Ft){if(!(P in e))continue;let B=`${s}/${dt(P)}`,L=Se(e[P],Ft[P],r,n,a,i,B,`${U}/${dt(P)}`);if(L.valid)d[P]=z[P]=!0;else if(V=a,k.push({instanceLocation:s,keyword:"properties",keywordLocation:U,error:`Property "${P}" does not match schema.`},...L.errors),V)break}}if(!V&&Gr!==void 0){let U=`${c}/patternProperties`;for(let P in Gr){let B=new RegExp(P,"u"),L=Gr[P];for(let Je in e){if(!B.test(Je))continue;let om=`${s}/${dt(Je)}`,am=Se(e[Je],L,r,n,a,i,om,`${U}/${dt(P)}`);am.valid?d[Je]=z[Je]=!0:(V=a,k.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:U,error:`Property "${Je}" matches pattern "${P}" but does not match associated schema.`},...am.errors))}}}if(!V&&wo!==void 0){let U=`${c}/additionalProperties`;for(let P in e){if(z[P])continue;let B=`${s}/${dt(P)}`,L=Se(e[P],wo,r,n,a,i,B,U);L.valid?d[P]=!0:(V=a,k.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:U,error:`Property "${P}" does not match additional properties schema.`},...L.errors))}}else if(!V&&bo!==void 0){let U=`${c}/unevaluatedProperties`;for(let P in e)if(!d[P]){let B=`${s}/${dt(P)}`,L=Se(e[P],bo,r,n,a,i,B,U);L.valid?d[P]=!0:k.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:U,error:`Property "${P}" does not match unevaluated properties schema.`},...L.errors)}}}else if(l==="array"){hc!==void 0&&e.length>hc&&k.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${hc}).`}),fc!==void 0&&e.length<fc&&k.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${fc}).`});let H=e.length,z=0,V=!1;if(mc!==void 0){let U=`${c}/prefixItems`,P=Math.min(mc.length,H);for(;z<P;z++){let B=Se(e[z],mc[z],r,n,a,i,`${s}/${z}`,`${U}/${z}`);if(d[z]=!0,!B.valid&&(V=a,k.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:U,error:"Items did not match schema."},...B.errors),V))break}}if(Co!==void 0){let U=`${c}/items`;if(Array.isArray(Co)){let P=Math.min(Co.length,H);for(;z<P;z++){let B=Se(e[z],Co[z],r,n,a,i,`${s}/${z}`,`${U}/${z}`);if(d[z]=!0,!B.valid&&(V=a,k.push({instanceLocation:s,keyword:"items",keywordLocation:U,error:"Items did not match schema."},...B.errors),V))break}}else for(;z<H;z++){let P=Se(e[z],Co,r,n,a,i,`${s}/${z}`,U);if(d[z]=!0,!P.valid&&(V=a,k.push({instanceLocation:s,keyword:"items",keywordLocation:U,error:"Items did not match schema."},...P.errors),V))break}if(!V&&em!==void 0){let P=`${c}/additionalItems`;for(;z<H;z++){let B=Se(e[z],em,r,n,a,i,`${s}/${z}`,P);d[z]=!0,B.valid||(V=a,k.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:P,error:"Items did not match additional items schema."},...B.errors))}}}if(rm!==void 0)if(H===0&&Zt===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(Zt!==void 0&&H<Zt)k.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${H}) than minContains (${Zt}).`});else{let U=`${c}/contains`,P=k.length,B=0;for(let L=0;L<H;L++){let Je=Se(e[L],rm,r,n,a,i,`${s}/${L}`,U);Je.valid?(d[L]=!0,B++):k.push(...Je.errors)}B>=(Zt||0)&&(k.length=P),Zt===void 0&&Ja===void 0&&B===0?k.splice(P,0,{instanceLocation:s,keyword:"contains",keywordLocation:U,error:"Array does not contain item matching schema."}):Zt!==void 0&&B<Zt?k.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${Zt} items matching schema. Only ${B} items were found.`}):Ja!==void 0&&B>Ja&&k.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${Ja} items matching schema. ${B} items were found.`})}if(!V&&tm!==void 0){let U=`${c}/unevaluatedItems`;for(z;z<H;z++){if(d[z])continue;let P=Se(e[z],tm,r,n,a,i,`${s}/${z}`,U);d[z]=!0,P.valid||k.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:U,error:"Items did not match unevaluated items schema."},...P.errors)}}if(Vw)for(let U=0;U<H;U++){let P=e[U],B=typeof P=="object"&&P!==null;for(let L=0;L<H;L++){if(U===L)continue;let Je=e[L];(P===Je||B&&(typeof Je=="object"&&Je!==null)&&ho(P,Je))&&(k.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${U} and ${L}.`}),U=Number.MAX_SAFE_INTEGER,L=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(Vr!==void 0&&(Io===!0&&e<=Vr||e<Vr)&&k.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Io?"or equal to ":""} ${Vr}.`}),Fr!==void 0&&(Po===!0&&e>=Fr||e>Fr)&&k.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${Po?"or equal to ":""} ${Fr}.`})):(Vr!==void 0&&e<Vr&&k.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Vr}.`}),Fr!==void 0&&e>Fr&&k.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${Fr}.`}),Io!==void 0&&e<=Io&&k.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${Io}.`}),Po!==void 0&&e>=Po&&k.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Po}.`})),Wa!==void 0){let H=e%Wa;Math.abs(0-H)>=11920929e-14&&Math.abs(Wa-H)>=11920929e-14&&k.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Wa}.`})}}else if(l==="string"){let H=Ya===void 0&&Xa===void 0?0:U_(e);Ya!==void 0&&H<Ya&&k.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${H} < ${Ya}).`}),Xa!==void 0&&H>Xa&&k.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${H} > ${Xa}).`}),nm!==void 0&&!new RegExp(nm,"u").test(e)&&k.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),fr!==void 0&&mp[fr]&&!mp[fr](e)&&k.push({instanceLocation:s,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${fr}".`})}return{valid:k.length===0,errors:k}}o(Se,"validate");var Ns=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=ur(t)}validate(t){return Se(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),ur(t,this.lookup)}};var go=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let r=new Ns(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 xO,context as Ds,propagation as M_,SpanKind as z_,SpanStatusCode as fp,trace as Na}from"@opentelemetry/api";var AO="mcp-gateway",kO="mcp-gateway",TO=Zr,EO="2.0",$_=Na.getTracer(AO),hp=xO.getMeter(kO),UO=hp.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),OO=hp.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),MO=hp.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),zO=["traceparent","tracestate","baggage"];function gp(){return performance.now()/1e3}o(gp,"nowSeconds");function q_(e,t){t(Math.max(gp()-e,0))}o(q_,"recordDurationSeconds");function O_(e){return e===void 0?void 0:String(e)}o(O_,"stringifyAttribute");function je(e,t,r){r!==void 0&&(e[t]=r)}o(je,"assignAttribute");function $O(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o($O,"readTargetName");function N_(e){let t=$O({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(N_,"buildMcpOperationSpanName");function yp(e){let t={"mcp.method.name":e.methodName};return je(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??EO),je(t,"jsonrpc.request.id",O_(e.jsonRpcRequestId)),je(t,"mcp.protocol.version",e.mcpProtocolVersion??TO),je(t,"mcp.session.id",e.mcpSessionId),je(t,"mcp.resource.uri",e.resourceUri),je(t,"rpc.response.status_code",O_(e.rpcResponseStatusCode)),je(t,"error.type",e.errorType),e.capabilityType==="tool"&&(je(t,"gen_ai.operation.name","execute_tool"),je(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&je(t,"gen_ai.prompt.name",e.capabilityName),je(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),je(t,"network.protocol.version",e.networkProtocolVersion),je(t,"network.transport",e.networkTransport),je(t,"server.address",e.serverAddress),je(t,"server.port",e.serverPort),je(t,"client.address",e.clientAddress),je(t,"client.port",e.clientPort),t}o(yp,"buildMcpOperationAttributes");function qO(e){let t=yp({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(qO,"buildMcpSessionAttributes");function D_(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:fp.ERROR}),t instanceof Error&&e.recordException(t)}o(D_,"setSpanError");function j_(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o(j_,"readErrorType");function NO(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?Ds.active():M_.extract(Ds.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(NO,"readServerParentContext");function DO(e){let t=Na.getSpanContext(Ds.active()),r=Na.getSpanContext(e);if(!(!t||!Na.isSpanContextValid(t))&&!(r&&Na.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(DO,"readAmbientSpanLink");function H_(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(H_,"readResultErrorType");async function Dr(e,t){let r=gp(),n=yp({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return $_.startActiveSpan(N_(e),{kind:z_.CLIENT,attributes:n},async a=>{try{let i=await t(),s=H_(i);return s&&(a.setAttribute("error.type",s),a.setStatus({code:fp.ERROR}),n["error.type"]=s),i}catch(i){let s=e.errorType??j_(i);throw n["error.type"]=s,D_(a,i,s),i}finally{q_(r,i=>{UO.record(i,n)}),a.end()}})}o(Dr,"runMcpClientOperation");async function jr(e,t){let r=gp(),n=NO(e.params),a=yp({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),i=DO(n);return $_.startActiveSpan(N_(e),{kind:z_.SERVER,attributes:a,...i?{links:i}:{}},n,async s=>{try{let c=await t(),d=H_(c);return d&&(s.setAttribute("error.type",d),s.setStatus({code:fp.ERROR}),a["error.type"]=d),c}catch(c){let d=e.errorType??j_(c);throw a["error.type"]=d,D_(s,c,d),c}finally{q_(r,c=>{OO.record(c,a)}),s.end()}})}o(jr,"runMcpServerOperation");function L_(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return M_.inject(Ds.active(),t._meta,{set(r,n,a){zO.includes(n)&&(r[n]=a)}}),t}o(L_,"injectMcpTraceContextIntoParams");function B_(e,t){let r=qO({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});MO.record(Math.max(t,0),r)}o(B_,"recordMcpClientSessionDuration");var js=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=br,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 I(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 I(E.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof I){yield{type:"error",error:l};return}yield{type:"error",error:new I(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 Hs(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&&Hs(i,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Hs(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Hs(r,t)}}o(Hs,"applyElicitationDefaults");function jO(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(jO,"getSupportedElicitationModes");var Ls=class extends Wn{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 fo,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Uu,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",ku,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",vu,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new js(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Wi(this._capabilities,t)}setRequestHandler(t,r){let a=Jn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(kr(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=Fe(zu,d);if(!l.success){let w=l.error instanceof Error?l.error.message:String(l.error);throw new I(E.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:m}=l.data;m.mode=m.mode??"form";let{supportsFormMode:h,supportsUrlMode:g}=jO(this._capabilities.elicitation);if(m.mode==="form"&&!h)throw new I(E.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!g)throw new I(E.InvalidParams,"Client does not support URL-mode elicitation requests");let S=await Promise.resolve(r(d,p));if(m.task){let w=Fe(er,S);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new I(E.InvalidParams,`Invalid task creation result: ${b}`)}return w.data}let y=Fe(Rr,S);if(!y.success){let w=y.error instanceof Error?y.error.message:String(y.error);throw new I(E.InvalidParams,`Invalid elicitation result: ${w}`)}let _=y.data,v=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&_.action==="accept"&&_.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Hs(v,_.content)}catch{}return _},"wrappedHandler");return super.setRequestHandler(t,c)}if(s==="sampling/createMessage"){let c=o(async(d,p)=>{let l=Fe(Mu,d);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new I(E.InvalidParams,`Invalid sampling request: ${_}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let _=Fe(er,h);if(!_.success){let v=_.error instanceof Error?_.error.message:String(_.error);throw new I(E.InvalidParams,`Invalid task creation result: ${v}`)}return _.data}let S=m.tools||m.toolChoice?Vo:Yr,y=Fe(S,h);if(!y.success){let _=y.error instanceof Error?y.error.message:String(y.error);throw new I(E.InvalidParams,`Invalid sampling result: ${_}`)}return y.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:_r,capabilities:this._capabilities,clientInfo:this._clientInfo}},lu,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!vr.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){Ms(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&zs(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Qt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},$u,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Qt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Au,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},bu,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},fu,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},gu,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},_u,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Qt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Qt,r)}async callTool(t,r=br,n){if(this.isToolTaskRequired(t.name))throw new I(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 I(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 I(E.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof I?s:new I(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},Eu,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let i=ph.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 Bs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o(Bs,"normalizeHeaders");function G_(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...Bs(t.headers),...Bs(n.headers)}:t.headers};return e(r,a)}:e}o(G_,"createFetchWithInit");var Gs=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 Sp(e){}o(Sp,"noop");function V_(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=Sp,onError:r=Sp,onRetry:n=Sp,onComment:a}=e,i="",s=!0,c,d="",p="";function l(y){let _=s?y.replace(/^\xEF\xBB\xBF/,""):y,[v,w]=HO(`${i}${_}`);for(let b of v)m(b);i=w,s=!1}o(l,"feed");function m(y){if(y===""){g();return}if(y.startsWith(":")){a&&a(y.slice(y.startsWith(": ")?2:1));return}let _=y.indexOf(":");if(_!==-1){let v=y.slice(0,_),w=y[_+1]===" "?2:1,b=y.slice(_+w);h(v,b,y);return}h(y,"",y)}o(m,"parseLine");function h(y,_,v){switch(y){case"event":p=_;break;case"data":d=`${d}${_}
53
- `;break;case"id":c=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new Gs(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:v}));break;default:r(new Gs(`Unknown field "${y.length>20?`${y.slice(0,20)}\u2026`:y}"`,{type:"unknown-field",field:y,value:_,line:v}));break}}o(h,"processField");function g(){d.length>0&&t({id:c,event:p||void 0,data:d.endsWith(`
54
- `)?d.slice(0,-1):d}),c=void 0,d="",p=""}o(g,"dispatchEvent");function S(y={}){i&&y.consume&&m(i),s=!0,c=void 0,d="",p="",i=""}return o(S,"reset"),{feed:l,reset:S}}o(V_,"createParser");function HO(e){let t=[],r="",n=0;for(;n<e.length;){let a=e.indexOf("\r",n),i=e.indexOf(`
52
+ - `)}`,new Error(P)}let V=`${c}/$ref`,U=Se(e,z,r,n,a,i,s,V,d);if(U.valid||A.push({instanceLocation:s,keyword:"$ref",keywordLocation:V,error:"A subschema had errors."},...U.errors),r==="4"||r==="7")return{valid:A.length===0,errors:A}}if(Array.isArray(S)){let H=S.length,z=!1;for(let V=0;V<H;V++)if(l===S[V]||S[V]==="integer"&&l==="number"&&e%1===0&&e===e){z=!0;break}z||A.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${S.join('", "')}".`})}else S==="integer"?(l!=="number"||e%1||e!==e)&&A.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${S}".`}):S!==void 0&&l!==S&&A.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${S}".`});if(y!==void 0&&(l==="object"||l==="array"?_o(e,y)||A.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&A.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),_!==void 0&&(l==="object"||l==="array"?_.some(H=>_o(e,H))||A.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`}):_.some(H=>e===H)||A.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`})),w!==void 0){let H=`${c}/not`;Se(e,w,r,n,a,i,s,H).valid&&A.push({instanceLocation:s,keyword:"not",keywordLocation:H,error:'Instance matched "not" schema.'})}let ri=[];if(b!==void 0){let H=`${c}/anyOf`,z=A.length,V=!1;for(let U=0;U<b.length;U++){let P=b[U],B=Object.create(d),L=Se(e,P,r,n,a,g===!0?i:null,s,`${H}/${U}`,B);A.push(...L.errors),V=V||L.valid,L.valid&&ri.push(B)}V?A.length=z:A.splice(z,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:H,error:"Instance does not match any subschemas."})}if(N!==void 0){let H=`${c}/allOf`,z=A.length,V=!0;for(let U=0;U<N.length;U++){let P=N[U],B=Object.create(d),L=Se(e,P,r,n,a,g===!0?i:null,s,`${H}/${U}`,B);A.push(...L.errors),V=V&&L.valid,L.valid&&ri.push(B)}V?A.length=z:A.splice(z,0,{instanceLocation:s,keyword:"allOf",keywordLocation:H,error:"Instance does not match every subschema."})}if(j!==void 0){let H=`${c}/oneOf`,z=A.length,V=j.filter((U,P)=>{let B=Object.create(d),L=Se(e,U,r,n,a,g===!0?i:null,s,`${H}/${P}`,B);return A.push(...L.errors),L.valid&&ri.push(B),L.valid}).length;V===1?A.length=z:A.splice(z,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:H,error:`Instance does not match exactly one subschema (${V} matches).`})}if((l==="object"||l==="array")&&Object.assign(d,...ri),Be!==void 0){let H=`${c}/if`;if(Se(e,Be,r,n,a,i,s,H,d).valid){if(ht!==void 0){let V=Se(e,ht,r,n,a,i,s,`${c}/then`,d);V.valid||A.push({instanceLocation:s,keyword:"if",keywordLocation:H,error:'Instance does not match "then" schema.'},...V.errors)}}else if(En!==void 0){let V=Se(e,En,r,n,a,i,s,`${c}/else`,d);V.valid||A.push({instanceLocation:s,keyword:"if",keywordLocation:H,error:'Instance does not match "else" schema.'},...V.errors)}}if(l==="object"){if(v!==void 0)for(let U of v)U in e||A.push({instanceLocation:s,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${U}".`});let H=Object.keys(e);if(xo!==void 0&&H.length<xo&&A.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${xo} properties.`}),lc!==void 0&&H.length>lc&&A.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${lc} properties.`}),tm!==void 0){let U=`${c}/propertyNames`;for(let P in e){let B=`${s}/${ft(P)}`,L=Se(P,tm,r,n,a,i,B,U);L.valid||A.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:U,error:`Property name "${P}" does not match schema.`},...L.errors)}}if(pc!==void 0){let U=`${c}/dependantRequired`;for(let P in pc)if(P in e){let B=pc[P];for(let L of B)L in e||A.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:U,error:`Instance has "${P}" but does not have "${L}".`})}}if(mc!==void 0)for(let U in mc){let P=`${c}/dependentSchemas`;if(U in e){let B=Se(e,mc[U],r,n,a,i,s,`${P}/${ft(U)}`,d);B.valid||A.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:P,error:`Instance has "${U}" but does not match dependant schema.`},...B.errors)}}if(fc!==void 0){let U=`${c}/dependencies`;for(let P in fc)if(P in e){let B=fc[P];if(Array.isArray(B))for(let L of B)L in e||A.push({instanceLocation:s,keyword:"dependencies",keywordLocation:U,error:`Instance has "${P}" but does not have "${L}".`});else{let L=Se(e,B,r,n,a,i,s,`${U}/${ft(P)}`);L.valid||A.push({instanceLocation:s,keyword:"dependencies",keywordLocation:U,error:`Instance has "${P}" but does not match dependant schema.`},...L.errors)}}}let z=Object.create(null),V=!1;if(Qt!==void 0){let U=`${c}/properties`;for(let P in Qt){if(!(P in e))continue;let B=`${s}/${ft(P)}`,L=Se(e[P],Qt[P],r,n,a,i,B,`${U}/${ft(P)}`);if(L.valid)d[P]=z[P]=!0;else if(V=a,A.push({instanceLocation:s,keyword:"properties",keywordLocation:U,error:`Property "${P}" does not match schema.`},...L.errors),V)break}}if(!V&&Yr!==void 0){let U=`${c}/patternProperties`;for(let P in Yr){let B=new RegExp(P,"u"),L=Yr[P];for(let Ye in e){if(!B.test(Ye))continue;let im=`${s}/${ft(Ye)}`,sm=Se(e[Ye],L,r,n,a,i,im,`${U}/${ft(P)}`);sm.valid?d[Ye]=z[Ye]=!0:(V=a,A.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:U,error:`Property "${Ye}" matches pattern "${P}" but does not match associated schema.`},...sm.errors))}}}if(!V&&Io!==void 0){let U=`${c}/additionalProperties`;for(let P in e){if(z[P])continue;let B=`${s}/${ft(P)}`,L=Se(e[P],Io,r,n,a,i,B,U);L.valid?d[P]=!0:(V=a,A.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:U,error:`Property "${P}" does not match additional properties schema.`},...L.errors))}}else if(!V&&Po!==void 0){let U=`${c}/unevaluatedProperties`;for(let P in e)if(!d[P]){let B=`${s}/${ft(P)}`,L=Se(e[P],Po,r,n,a,i,B,U);L.valid?d[P]=!0:A.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:U,error:`Property "${P}" does not match unevaluated properties schema.`},...L.errors)}}}else if(l==="array"){yc!==void 0&&e.length>yc&&A.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${yc}).`}),gc!==void 0&&e.length<gc&&A.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${gc}).`});let H=e.length,z=0,V=!1;if(hc!==void 0){let U=`${c}/prefixItems`,P=Math.min(hc.length,H);for(;z<P;z++){let B=Se(e[z],hc[z],r,n,a,i,`${s}/${z}`,`${U}/${z}`);if(d[z]=!0,!B.valid&&(V=a,A.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:U,error:"Items did not match schema."},...B.errors),V))break}}if(ko!==void 0){let U=`${c}/items`;if(Array.isArray(ko)){let P=Math.min(ko.length,H);for(;z<P;z++){let B=Se(e[z],ko[z],r,n,a,i,`${s}/${z}`,`${U}/${z}`);if(d[z]=!0,!B.valid&&(V=a,A.push({instanceLocation:s,keyword:"items",keywordLocation:U,error:"Items did not match schema."},...B.errors),V))break}}else for(;z<H;z++){let P=Se(e[z],ko,r,n,a,i,`${s}/${z}`,U);if(d[z]=!0,!P.valid&&(V=a,A.push({instanceLocation:s,keyword:"items",keywordLocation:U,error:"Items did not match schema."},...P.errors),V))break}if(!V&&rm!==void 0){let P=`${c}/additionalItems`;for(;z<H;z++){let B=Se(e[z],rm,r,n,a,i,`${s}/${z}`,P);d[z]=!0,B.valid||(V=a,A.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:P,error:"Items did not match additional items schema."},...B.errors))}}}if(om!==void 0)if(H===0&&er===void 0)A.push({instanceLocation:s,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(er!==void 0&&H<er)A.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${H}) than minContains (${er}).`});else{let U=`${c}/contains`,P=A.length,B=0;for(let L=0;L<H;L++){let Ye=Se(e[L],om,r,n,a,i,`${s}/${L}`,U);Ye.valid?(d[L]=!0,B++):A.push(...Ye.errors)}B>=(er||0)&&(A.length=P),er===void 0&&Ya===void 0&&B===0?A.splice(P,0,{instanceLocation:s,keyword:"contains",keywordLocation:U,error:"Array does not contain item matching schema."}):er!==void 0&&B<er?A.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${er} items matching schema. Only ${B} items were found.`}):Ya!==void 0&&B>Ya&&A.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${Ya} items matching schema. ${B} items were found.`})}if(!V&&nm!==void 0){let U=`${c}/unevaluatedItems`;for(z;z<H;z++){if(d[z])continue;let P=Se(e[z],nm,r,n,a,i,`${s}/${z}`,U);d[z]=!0,P.valid||A.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:U,error:"Items did not match unevaluated items schema."},...P.errors)}}if(eb)for(let U=0;U<H;U++){let P=e[U],B=typeof P=="object"&&P!==null;for(let L=0;L<H;L++){if(U===L)continue;let Ye=e[L];(P===Ye||B&&(typeof Ye=="object"&&Ye!==null)&&_o(P,Ye))&&(A.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${U} and ${L}.`}),U=Number.MAX_SAFE_INTEGER,L=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(Xr!==void 0&&(Ao===!0&&e<=Xr||e<Xr)&&A.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Ao?"or equal to ":""} ${Xr}.`}),Qr!==void 0&&(To===!0&&e>=Qr||e>Qr)&&A.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${To?"or equal to ":""} ${Qr}.`})):(Xr!==void 0&&e<Xr&&A.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Xr}.`}),Qr!==void 0&&e>Qr&&A.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${Qr}.`}),Ao!==void 0&&e<=Ao&&A.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${Ao}.`}),To!==void 0&&e>=To&&A.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${To}.`})),Xa!==void 0){let H=e%Xa;Math.abs(0-H)>=11920929e-14&&Math.abs(Xa-H)>=11920929e-14&&A.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Xa}.`})}}else if(l==="string"){let H=Qa===void 0&&ei===void 0?0:D_(e);Qa!==void 0&&H<Qa&&A.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${H} < ${Qa}).`}),ei!==void 0&&H>ei&&A.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${H} > ${ei}).`}),am!==void 0&&!new RegExp(am,"u").test(e)&&A.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),wr!==void 0&&fp[wr]&&!fp[wr](e)&&A.push({instanceLocation:s,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${wr}".`})}return{valid:A.length===0,errors:A}}o(Se,"validate");var js=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=hr(t)}validate(t){return Se(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),hr(t,this.lookup)}};var vo=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let r=new js(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 BO,context as Hs,propagation as H_,SpanKind as L_,SpanStatusCode as hp,trace as La}from"@opentelemetry/api";var GO="mcp-gateway",VO="mcp-gateway",FO=rn,ZO="2.0",B_=La.getTracer(GO),gp=BO.getMeter(VO),KO=gp.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),JO=gp.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),WO=gp.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),YO=["traceparent","tracestate","baggage"];function yp(){return performance.now()/1e3}o(yp,"nowSeconds");function G_(e,t){t(Math.max(yp()-e,0))}o(G_,"recordDurationSeconds");function j_(e){return e===void 0?void 0:String(e)}o(j_,"stringifyAttribute");function Le(e,t,r){r!==void 0&&(e[t]=r)}o(Le,"assignAttribute");function XO(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o(XO,"readTargetName");function V_(e){let t=XO({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(V_,"buildMcpOperationSpanName");function Sp(e){let t={"mcp.method.name":e.methodName};return Le(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??ZO),Le(t,"jsonrpc.request.id",j_(e.jsonRpcRequestId)),Le(t,"mcp.protocol.version",e.mcpProtocolVersion??FO),Le(t,"mcp.session.id",e.mcpSessionId),Le(t,"mcp.resource.uri",e.resourceUri),Le(t,"rpc.response.status_code",j_(e.rpcResponseStatusCode)),Le(t,"error.type",e.errorType),e.capabilityType==="tool"&&(Le(t,"gen_ai.operation.name","execute_tool"),Le(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&Le(t,"gen_ai.prompt.name",e.capabilityName),Le(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),Le(t,"network.protocol.version",e.networkProtocolVersion),Le(t,"network.transport",e.networkTransport),Le(t,"server.address",e.serverAddress),Le(t,"server.port",e.serverPort),Le(t,"client.address",e.clientAddress),Le(t,"client.port",e.clientPort),t}o(Sp,"buildMcpOperationAttributes");function QO(e){let t=Sp({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(QO,"buildMcpSessionAttributes");function F_(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:hp.ERROR}),t instanceof Error&&e.recordException(t)}o(F_,"setSpanError");function Z_(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o(Z_,"readErrorType");function eM(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?Hs.active():H_.extract(Hs.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(eM,"readServerParentContext");function tM(e){let t=La.getSpanContext(Hs.active()),r=La.getSpanContext(e);if(!(!t||!La.isSpanContextValid(t))&&!(r&&La.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(tM,"readAmbientSpanLink");function K_(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(K_,"readResultErrorType");async function Fr(e,t){let r=yp(),n=Sp({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return B_.startActiveSpan(V_(e),{kind:L_.CLIENT,attributes:n},async a=>{try{let i=await t(),s=K_(i);return s&&(a.setAttribute("error.type",s),a.setStatus({code:hp.ERROR}),n["error.type"]=s),i}catch(i){let s=e.errorType??Z_(i);throw n["error.type"]=s,F_(a,i,s),i}finally{G_(r,i=>{KO.record(i,n)}),a.end()}})}o(Fr,"runMcpClientOperation");async function Zr(e,t){let r=yp(),n=eM(e.params),a=Sp({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),i=tM(n);return B_.startActiveSpan(V_(e),{kind:L_.SERVER,attributes:a,...i?{links:i}:{}},n,async s=>{try{let c=await t(),d=K_(c);return d&&(s.setAttribute("error.type",d),s.setStatus({code:hp.ERROR}),a["error.type"]=d),c}catch(c){let d=e.errorType??Z_(c);throw a["error.type"]=d,F_(s,c,d),c}finally{G_(r,c=>{JO.record(c,a)}),s.end()}})}o(Zr,"runMcpServerOperation");function J_(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return H_.inject(Hs.active(),t._meta,{set(r,n,a){YO.includes(n)&&(r[n]=a)}}),t}o(J_,"injectMcpTraceContextIntoParams");function W_(e,t){let r=QO({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});WO.record(Math.max(t,0),r)}o(W_,"recordMcpClientSessionDuration");var Ls=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=Ir,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 I(k.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 I(k.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof I){yield{type:"error",error:l};return}yield{type:"error",error:new I(k.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 Bs(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&&Bs(i,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Bs(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Bs(r,t)}}o(Bs,"applyElicitationDefaults");function rM(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(rM,"getSupportedElicitationModes");var Gs=class extends eo{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 So,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Wc,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Zc,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Nc,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Ls(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Xi(this._capabilities,t)}setRequestHandler(t,r){let a=Qn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if($r(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=Ke(Qc,d);if(!l.success){let w=l.error instanceof Error?l.error.message:String(l.error);throw new I(k.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:m}=l.data;m.mode=m.mode??"form";let{supportsFormMode:h,supportsUrlMode:g}=rM(this._capabilities.elicitation);if(m.mode==="form"&&!h)throw new I(k.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!g)throw new I(k.InvalidParams,"Client does not support URL-mode elicitation requests");let S=await Promise.resolve(r(d,p));if(m.task){let w=Ke(rr,S);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new I(k.InvalidParams,`Invalid task creation result: ${b}`)}return w.data}let y=Ke(Pr,S);if(!y.success){let w=y.error instanceof Error?y.error.message:String(y.error);throw new I(k.InvalidParams,`Invalid elicitation result: ${w}`)}let _=y.data,v=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&_.action==="accept"&&_.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Bs(v,_.content)}catch{}return _},"wrappedHandler");return super.setRequestHandler(t,c)}if(s==="sampling/createMessage"){let c=o(async(d,p)=>{let l=Ke(Xc,d);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new I(k.InvalidParams,`Invalid sampling request: ${_}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let _=Ke(rr,h);if(!_.success){let v=_.error instanceof Error?_.error.message:String(_.error);throw new I(k.InvalidParams,`Invalid task creation result: ${v}`)}return _.data}let S=m.tools||m.toolChoice?Ho:tn,y=Ke(S,h);if(!y.success){let _=y.error instanceof Error?y.error.message:String(y.error);throw new I(k.InvalidParams,`Invalid sampling result: ${_}`)}return y.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:br,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ac,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Rr.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){$s(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&qs(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},tr,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},eu,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},tr,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Fc,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},jc,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},Uc,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},Mc,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},qc,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},tr,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},tr,r)}async callTool(t,r=Ir,n){if(this.isToolTaskRequired(t.name))throw new I(k.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 I(k.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 I(k.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof I?s:new I(k.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},Jc,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let i=Mm.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 Vs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o(Vs,"normalizeHeaders");function Y_(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...Vs(t.headers),...Vs(n.headers)}:t.headers};return e(r,a)}:e}o(Y_,"createFetchWithInit");var Fs=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 _p(e){}o(_p,"noop");function X_(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=_p,onError:r=_p,onRetry:n=_p,onComment:a}=e,i="",s=!0,c,d="",p="";function l(y){let _=s?y.replace(/^\xEF\xBB\xBF/,""):y,[v,w]=nM(`${i}${_}`);for(let b of v)m(b);i=w,s=!1}o(l,"feed");function m(y){if(y===""){g();return}if(y.startsWith(":")){a&&a(y.slice(y.startsWith(": ")?2:1));return}let _=y.indexOf(":");if(_!==-1){let v=y.slice(0,_),w=y[_+1]===" "?2:1,b=y.slice(_+w);h(v,b,y);return}h(y,"",y)}o(m,"parseLine");function h(y,_,v){switch(y){case"event":p=_;break;case"data":d=`${d}${_}
53
+ `;break;case"id":c=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new Fs(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:v}));break;default:r(new Fs(`Unknown field "${y.length>20?`${y.slice(0,20)}\u2026`:y}"`,{type:"unknown-field",field:y,value:_,line:v}));break}}o(h,"processField");function g(){d.length>0&&t({id:c,event:p||void 0,data:d.endsWith(`
54
+ `)?d.slice(0,-1):d}),c=void 0,d="",p=""}o(g,"dispatchEvent");function S(y={}){i&&y.consume&&m(i),s=!0,c=void 0,d="",p="",i=""}return o(S,"reset"),{feed:l,reset:S}}o(X_,"createParser");function nM(e){let t=[],r="",n=0;for(;n<e.length;){let a=e.indexOf("\r",n),i=e.indexOf(`
55
55
  `,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]===`
56
- `&&n++}}return[t,r]}o(HO,"splitLines");var Vs=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(i){a=V_({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 LO={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Hr=class extends Error{static{o(this,"StreamableHTTPError")}constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},Fs=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=G_(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??LO}async _authThenStart(){if(!this._authProvider)throw new Pt("No auth provider");let t;try{t=await Ar(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 Pt;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=Bs(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 Hr(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 Vs({onRetry:o(g=>{this._serverRetryMs=g},"onRetry")})).getReader();for(;;){let{value:g,done:S}=await l.read();if(S)break;if(g.id&&(s=g.id,c=!0,a?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let y=Wr.parse(JSON.parse(g.data));It(y)&&(d=!0,i!==void 0&&(y.id=i)),this.onmessage?.(y)}catch(y){this.onerror?.(y)}}(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(g){this.onerror?.(new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}},"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 Pt("No auth provider");if(await Ar(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Pt("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:Mt(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 Hr(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:S}=pd(c);if(this._resourceMetadataUrl=g,this._scope=S,await Ar(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Pt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:S,error:y}=pd(c);if(y==="insufficient_scope"){let _=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new Hr(403,"Server returned 403 after trying upscoping");if(S&&(this._scope=S),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=_??void 0,await Ar(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Pt;return this.send(t)}}throw new Hr(c.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),ah(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(),g=Array.isArray(h)?h.map(S=>Wr.parse(S)):[Wr.parse(h)];for(let S of g)this.onmessage?.(S)}else throw await c.body?.cancel(),new Hr(-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 Hr(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 F_(e=[]){let t={};for(let r of e){if(!r.value){if(r.required)throw new $(`Native MCP transport header "${r.name}" is required but has no value configured. Set the env var that backs the header or mark the header optional.`);continue}t[r.name]=r.value}return t}o(F_,"resolveNativeMcpRequestHeaders");var BO={name:"zuplo-mcp-gateway",version:"0.1.0"},GO=new go({draft:"7",shortcircuit:!1}),VO=5,FO=500,W_=3e4,ZO=2*1024*1024,KO=2,Da="upstream_capability_invocation_failed",Z_="upstream_import_failed";function K_(){return performance.now()/1e3}o(K_,"nowSeconds");function JO(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(JO,"readServerPort");function WO(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:JO(e)}}o(WO,"buildNativeMcpOperationContext");function yn(e){return L_(e)}o(yn,"withTraceMeta");function Zs(e){if(e>FO)throw new A({message:bt[Z_].publicDetail,extensionMembers:{[T]:Z_}},{cause:new Error("Upstream import exceeded the maximum allowed capability count.")})}o(Zs,"assertImportedCapabilityBudget");function J_(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(J_,"buildRequestInit");function YO(e){return(t,r)=>Fn(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:KO,maxResponseBytes:ZO,problemCode:Da,timeoutMs:W_})}o(YO,"createNativeMcpFetch");function XO(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(new A({message:bt[Da].publicDetail,extensionMembers:{[T]:Da}},{cause:new Error("Upstream MCP request exceeded the maximum allowed time.")}))},W_);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(XO,"withNativeMcpRequestTimeout");function QO(e,t=[]){let r=F_(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],i={fetch:YO(a)};if(!e)return{...i,...J_(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...i,...J_(r)};case"bearer_token":return{...i,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...i,requestInit:{headers:{...r,...e.headers}}}}}o(QO,"buildNativeMcpTransportOptions");async function Sn(e,t,r){let{transport:n}=Le(e),a=new URL(n.baseUrl),i=new Fs(a,QO(r,n.requestHeaders)),s=new Ls(BO,{capabilities:{},jsonSchemaValidator:GO});return XO((async()=>{let c=K_();await s.connect(i);let d=i.sessionId,p=WO(a,d);try{return await t(s,p)}finally{await s.close(),d&&B_(p,K_()-c)}})())}o(Sn,"withNativeMcpClient");async function eM(e,t,r){let n=[],a,i=0;do{if(i>=VO)throw new A({message:bt[Da].publicDetail,extensionMembers:{[T]:Da}},{cause:new Error(`${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(eM,"collectPaginatedSdkItems");async function Ks(e){return e.enabled?eM(e.label,e.fetchPage,e.readItems):[]}o(Ks,"listNativeMcpCapabilityItems");async function Y_(e){return Sn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Dr({methodName:"tools/list",...r},()=>Ks({enabled:!!n?.tools,label:"Tool list",fetchPage:o(i=>t.listTools(yn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.tools,"readItems")}));return Zs(a.length),{tools:a}},e.credential)}o(Y_,"listNativeMcpTools");async function X_(e){return Sn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Dr({methodName:"prompts/list",...r},()=>Ks({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(i=>t.listPrompts(yn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.prompts,"readItems")}));return Zs(a.length),{prompts:a}},e.credential)}o(X_,"listNativeMcpPrompts");async function Q_(e){return Sn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Dr({methodName:"resources/list",...r},()=>Ks({enabled:!!n?.resources,label:"Resource list",fetchPage:o(i=>t.listResources(yn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resources,"readItems")}));return Zs(a.length),{resources:a}},e.credential)}o(Q_,"listNativeMcpResources");async function ev(e){return Sn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Dr({methodName:"resources/templates/list",...r},()=>Ks({enabled:!!n?.resources,label:"Resource template list",fetchPage:o(i=>t.listResourceTemplates(yn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resourceTemplates,"readItems")}));return Zs(a.length),{resourceTemplates:a}},e.credential)}o(ev,"listNativeMcpResourceTemplates");async function tv(e){return Sn(e.upstreamServerId,(t,r)=>Dr({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(yn(e.params))),e.credential)}o(tv,"callNativeMcpTool");async function rv(e){return Sn(e.upstreamServerId,(t,r)=>Dr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(yn(e.params))),e.credential)}o(rv,"getNativeMcpPrompt");async function nv(e){return Sn(e.upstreamServerId,(t,r)=>Dr({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(yn(e.params))),e.credential)}o(nv,"readNativeMcpResource");var yo=class extends I{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(E.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}},ja=class extends I{static{o(this,"GatewayAuthorizationMcpError")}authorizationFailureKind;constructor(t){super(E.InvalidRequest,oM(t)),this.name="GatewayAuthorizationMcpError",this.authorizationFailureKind=t}};function tM(e){return{content:[{type:"text",text:e}],isError:!0}}o(tM,"buildToolErrorResult");function cv(e){return e.authUrl?new Xt([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new yo(e)}o(cv,"toConnectRequiredError");function rM(e){if(e.type!=="mcp_oauth_provider")return;let{provider:t}=e;if(!("authorizationUrl"in t))return;let{authorizationUrl:r}=t;return typeof r=="string"&&r.length>0?r:void 0}o(rM,"readOAuthAuthorizationUrl");function nM(e,t){return rM(t)===void 0?!1:e instanceof Pt||e instanceof Error&&e.message==="Unauthorized"}o(nM,"isOAuthRedirectUnauthorizedError");function oM(e){switch(e){case"resource_mismatch":return"Gateway access token was not issued for this MCP resource.";case"principal_mismatch":return"Gateway access token principal did not match the request.";default:return"Gateway access token is expired, revoked, or invalid."}}o(oM,"readCompositeAuthorizationFailureDetail");function aM(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(aM,"buildCredentialResolvedAttributes");function iM(e){K(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:aM(e.credential)})}o(iM,"emitCredentialResolvedAnalyticsEvent");function uv(e){if(K(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}}),e.payload.state==="reconsent_required")K(e.context,{eventType:F.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}});else{let t=sM(e.payload.state);K(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:t,reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}})}}o(uv,"emitCredentialMissingAnalyticsEvent");function sM(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required";default:{let t=e;return"connect_required"}}}o(sM,"connectRequiredReasonCode");function cM(e){return e.ownerMode==="none"?JSON.stringify(["none",e.upstreamServerId,e.authProfileId]):Sr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId})}o(cM,"readRouteBindingCredentialCacheKey");function wp(e){if(e.ownerMode!=="none")return{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}}o(wp,"readOwnedRouteBindingLookup");async function uM(e){let t=Qc(e.request);if(!t)return new Map;let r=new Map;for(let s of e.routeBindings){let c=wp(s);c!==void 0&&r.set(Sr(c),c)}if(r.size===0)return new Map;let n=[...r.values()],a=await W().authorizeAndLoadConnections({accessTokenHash:await fe(t),resource:gr(e.virtualServerId,e.request.url),virtualServerId:e.virtualServerId,upstreamConnectionKeys:n,now:oe(new Date)});if(a.kind!=="authorized")throw new ja(a.kind);let i=new Map;return a.upstreamConnections.forEach((s,c)=>{let d=n[c];d!==void 0&&i.set(Sr(d),s.connection)}),i}o(uM,"preloadCompositeAuthorizedConnections");function dM(e){let t=new Map;return r=>{let n=cM(r),a=t.get(n);if(a)return a;let i=(async()=>{let s=await e.preloadedConnections,c=wp(r),d=c===void 0?void 0:Sr(c),p=await Ki({request:e.request,routeAuth:r,...d!==void 0&&s.has(d)?{preloadedConnection:s.get(d)}:{}});if(p.kind==="connect_required")throw uv({context:e.context,payload:p.payload,routeBinding:r}),cv(p.payload);return iM({context:e.context,credential:p.credential,routeBinding:r}),p.credential})();return t.set(n,i),i}}o(dM,"createCredentialResolver");var ov=500;function bp(e){return e.length<=ov?e:`${e.slice(0,ov)}...`}o(bp,"truncateAnalyticsDetail");function lM(e){K(e.context,{eventType:F.MCP_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,latencyMs:e.latencyMs})}o(lM,"emitToolInvocationCompletedAnalyticsEvent");function _p(e){K(e.context,{eventType:F.MCP_CAPABILITY_INVOKED,outcome:"success",routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType})}o(_p,"emitCapabilityInvokedAnalyticsEvent");function av(e){let t={};typeof e.itemCount=="number"&&(t.itemCount=e.itemCount),e.errorDetail!==void 0&&(t.detail=bp(e.errorDetail)),K(e.context,{eventType:F.MCP_CAPABILITY_LISTED,outcome:e.outcome,...e.routeBinding?{routeBinding:e.routeBinding}:{},...e.virtualServerName?{virtualServerName:e.virtualServerName}:{},mcpMethod:e.mcpMethod,capabilityType:e.capabilityType,latencyMs:e.latencyMs,...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.reasonClass?{reasonClass:e.reasonClass}:{},...e.errorType?{errorType:e.errorType}:{},attributes:t})}o(av,"emitCapabilityListedAnalyticsEvent");function iv(e){K(e.context,{eventType:F.MCP_CAPABILITY_COMPLETED,outcome:"success",routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType,latencyMs:e.latencyMs})}o(iv,"emitCapabilityCompletedAnalyticsEvent");function sv(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=e.error instanceof Xt||e.error instanceof yo,n=e.error instanceof I&&e.error.code===E.InvalidParams,a=r?F.MCP_CAPABILITY_CONNECT_REQUIRED:F.MCP_CAPABILITY_FAILED,i=r?"connect_required":"failure",s=r?"connect_required":n?"invalid_capability_arguments":"upstream_capability_invocation_failed",c=r?"auth":n?"client":"upstream";K(e.context,{eventType:a,outcome:i,routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType,reasonCode:s,reasonClass:c,errorType:r?"connect_required":"capability_error",...n?{mcpErrorType:"InvalidParams"}:{},latencyMs:e.latencyMs,attributes:{detail:bp(t)}})}o(sv,"emitCapabilityFailedAnalyticsEvent");function pM(e){return e instanceof Xt||e instanceof yo?{eventType:F.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof ja?{eventType:F.MCP_CAPABILITY_FAILED,outcome:"denied",reasonCode:`gateway_access_token_${e.authorizationFailureKind}`,reasonClass:"auth",errorType:"auth_error",mcpErrorType:"InvalidRequest"}:e instanceof I&&e.code===E.InvalidParams?{eventType:F.MCP_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:F.MCP_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(pM,"classifyToolInvocationFailure");function mM(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=pM(e.error);K(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,latencyMs:e.latencyMs,attributes:{detail:bp(t)}})}o(mM,"emitToolInvocationFailedAnalyticsEvent");var fM=256*1024;function hM(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new I(E.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>fM)throw new I(E.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o(hM,"assertToolArgumentsWithinLimit");function vp(e,t){throw e instanceof I?e:new I(E.InternalError,bt[t].publicDetail)}o(vp,"throwSafeUpstreamMcpError");function Rp(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 I(E.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o(Rp,"findBindingForPublishedCapability");function _n(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new I(E.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(_n,"requireSingleTransparentBinding");function gM(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:_n(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new I(E.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Rp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(gM,"resolvePublishedToolRoute");function yM(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:_n(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new I(E.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Rp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(yM,"resolvePublishedPromptRoute");function SM(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:_n(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new I(E.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Rp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(SM,"resolvePublishedResourceRoute");function dv(e){let t=uM({request:e.request,routeBindings:e.routeBindings,virtualServerId:e.publishedVirtualServer.virtualServerId}),r=dM({context:e.context,preloadedConnections:t,request:e.request}),n=e.publishedVirtualServer.virtualServerId;async function a(c){if(!nM(c.error,c.credential)||c.routeBinding.ownerMode==="none")return;let d=wp(c.routeBinding);if(d===void 0)return;let l=(await t).get(Sr(d))?.id,m=c.routeBinding.owner.mode==="shared"?Gi({upstreamServerId:c.routeBinding.upstreamServerId,authProfileId:c.routeBinding.authProfileId,upstreamDisplayName:c.routeBinding.upstreamDisplayName,virtualServerId:c.routeBinding.virtualServerId,...l===void 0?{}:{connectionId:l},requiresReconsent:!0}):await Pr({requestUrl:e.request.url,owner:c.routeBinding.owner,initiatedBySubjectId:c.routeBinding.initiatedBySubjectId,upstreamServerId:c.routeBinding.upstreamServerId,authProfileId:c.routeBinding.authProfileId,upstreamDisplayName:c.routeBinding.upstreamDisplayName,virtualServerId:c.routeBinding.virtualServerId,subject:"tool",...l===void 0?{}:{connectionId:l},requiresReconsent:!0,...c.routeBinding.returnTo===void 0?{}:{returnTo:c.routeBinding.returnTo}});return uv({context:e.context,payload:m,routeBinding:c.routeBinding}),cv(m)}o(a,"buildForwardingConnectRequiredError");async function i(c){let d=await r(c.routeBinding);try{return await c.invoke(d)}catch(p){let l=await a({credential:d,error:p,routeBinding:c.routeBinding});throw l!==void 0?l:p}}o(i,"invokeNativeMcpWithCredential");async function s(c){let d=Date.now();try{let p=await c.invoke();return av({context:e.context,routeBinding:c.routeBinding,virtualServerName:n,capabilityType:c.capabilityType,mcpMethod:c.mcpMethod,outcome:"success",itemCount:c.countItems(p),latencyMs:Date.now()-d}),p}catch(p){let l=p instanceof Error?p.message:String(p);if(av({context:e.context,routeBinding:c.routeBinding,virtualServerName:n,capabilityType:c.capabilityType,mcpMethod:c.mcpMethod,outcome:"failure",latencyMs:Date.now()-d,reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",errorType:"capability_list_error",errorDetail:l}),c.routeBinding===void 0)throw p;vp(p,"upstream_import_failed")}}return o(s,"listCapability"),{async listTools(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return s({capabilityType:"tool",mcpMethod:"tools/list",invoke:o(async()=>({tools:e.publishedVirtualServer.catalog.tools.filter(d=>d.enabled!==!1).map(Mi)}),"invoke"),countItems:o(d=>d.tools.length,"countItems")});let c=_n(e);return s({capabilityType:"tool",mcpMethod:"tools/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>Y_({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.tools.length,"countItems")})},async callTool(c){let d=gM({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:c.name});_p({context:e.context,routeBinding:d.binding,capabilityType:"tool",capabilityName:c.name,mcpMethod:"tools/call"});let p=Date.now();try{hM(c);let l=await i({routeBinding:d.binding,invoke:o(m=>tv({upstreamServerId:d.binding.upstreamServerId,params:{...c,name:d.upstreamName},credential:m}),"invoke")});return lM({context:e.context,routeBinding:d.binding,toolName:c.name,result:l,latencyMs:Date.now()-p}),e.context.log.debug({event:"upstream_tool_invocation_succeeded",toolName:c.name,upstreamName:d.upstreamName,upstreamServerId:d.binding.upstreamServerId,authProfileId:d.binding.authProfileId,isError:l.isError===!0},"Upstream tool invocation completed"),l}catch(l){if(mM({context:e.context,routeBinding:d.binding,toolName:c.name,error:l,latencyMs:Date.now()-p}),l instanceof Xt||l instanceof yo)throw e.context.log.info({event:"upstream_tool_invocation_connect_required",toolName:c.name,upstreamServerId:d.binding.upstreamServerId,authProfileId:d.binding.authProfileId,ownerMode:d.binding.ownerMode,hasAuthUrl:l instanceof Xt},"Upstream tool invocation requires user to complete a connect flow"),l;if(l instanceof ja)throw e.context.log.warn({event:"upstream_tool_invocation_gateway_auth_denied",toolName:c.name,upstreamServerId:d.binding.upstreamServerId,authProfileId:d.binding.authProfileId,validationKind:l.authorizationFailureKind},"Gateway access token failed composite authorization; MCP tool invocation denied"),l;let m={event:"upstream_tool_invocation_failed",code:"upstream_capability_invocation_failed",toolName:c.name,upstreamName:d.upstreamName,upstreamServerId:d.binding.upstreamServerId,authProfileId:d.binding.authProfileId};return l instanceof I&&(m.mcpErrorCode=l.code),l instanceof Error?(m.errorName=l.name,m.errorMessage=l.message,l.cause instanceof Error&&(m.causeName=l.cause.name,m.causeMessage=l.cause.message)):m.errorMessage=String(l),e.context.log.warn(m,"Upstream tool invocation failed; returning generic gateway error to MCP client"),tM(bt.upstream_capability_invocation_failed.publicDetail)}},async listPrompts(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return s({capabilityType:"prompt",mcpMethod:"prompts/list",invoke:o(async()=>({prompts:e.publishedVirtualServer.catalog.prompts.filter(d=>d.enabled!==!1).map(zi)}),"invoke"),countItems:o(d=>d.prompts.length,"countItems")});let c=_n(e);return s({capabilityType:"prompt",mcpMethod:"prompts/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>X_({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.prompts.length,"countItems")})},async getPrompt(c){let d=yM({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:c.name});_p({context:e.context,routeBinding:d.binding,capabilityType:"prompt",capabilityName:c.name,mcpMethod:"prompts/get"});let p=Date.now();try{let l=await i({routeBinding:d.binding,invoke:o(m=>rv({upstreamServerId:d.binding.upstreamServerId,params:{...c,name:d.upstreamName},credential:m}),"invoke")});return iv({context:e.context,routeBinding:d.binding,capabilityType:"prompt",capabilityName:c.name,mcpMethod:"prompts/get",latencyMs:Date.now()-p}),l}catch(l){sv({context:e.context,routeBinding:d.binding,capabilityType:"prompt",capabilityName:c.name,mcpMethod:"prompts/get",error:l,latencyMs:Date.now()-p}),vp(l,"upstream_capability_invocation_failed")}},async listResources(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return s({capabilityType:"resource",mcpMethod:"resources/list",invoke:o(async()=>({resources:e.publishedVirtualServer.catalog.resources.filter(d=>d.enabled!==!1).map($i)}),"invoke"),countItems:o(d=>d.resources.length,"countItems")});let c=_n(e);return s({capabilityType:"resource",mcpMethod:"resources/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>Q_({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.resources.length,"countItems")})},async listResourceTemplates(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{resourceTemplates:[]};let c=_n(e);return s({capabilityType:"resource",mcpMethod:"resources/templates/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>ev({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.resourceTemplates.length,"countItems")})},async readResource(c){let d=SM({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:c.uri});_p({context:e.context,routeBinding:d.binding,capabilityType:"resource",capabilityName:c.uri,mcpMethod:"resources/read"});let p=Date.now();try{let l=await i({routeBinding:d.binding,invoke:o(m=>nv({upstreamServerId:d.binding.upstreamServerId,params:{...c,uri:d.upstreamUri},credential:m}),"invoke")});return iv({context:e.context,routeBinding:d.binding,capabilityType:"resource",capabilityName:c.uri,mcpMethod:"resources/read",latencyMs:Date.now()-p}),l}catch(l){sv({context:e.context,routeBinding:d.binding,capabilityType:"resource",capabilityName:c.uri,mcpMethod:"resources/read",error:l,latencyMs:Date.now()-p}),vp(l,"upstream_capability_invocation_failed")}}}}o(dv,"createCapabilityDispatcher");var _M="0.1.0",pv="POST",vM="POST, OPTIONS",wM=new go({draft:"7",shortcircuit:!1});function Cp(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:pv}})}o(Cp,"jsonRpcMethodNotAllowedResponse");function bM(e){let t={Allow:pv},r=e.headers.get("origin"),n=e.headers.get("access-control-request-method");if(r&&n){t["Access-Control-Allow-Methods"]=vM;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(bM,"buildOptionsResponse");function vn(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o(vn,"readJsonRpcRequestId");function Js(e){return e&&typeof e=="object"?e.params:void 0}o(Js,"readMcpRequestParams");function lv(e,t){return e.headers.get(t)??void 0}o(lv,"readMcpHeader");function RM(e){return{mcpProtocolVersion:lv(e,"mcp-protocol-version")??Zr,mcpSessionId:lv(e,"mcp-session-id")}}o(RM,"buildServerTelemetryBase");function CM(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(CM,"ensureProtocolVersionHeader");async function Ip(e,t){if(e.method==="OPTIONS")return bM(e);if(e.method==="GET")return Cp("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return Cp("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return Cp("Only POST is supported by this virtual MCP server.");let r=Tn(t),n=Kr(r.virtualServerId),a=Ji(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"),new $(`MCP virtual server route "${n.routePath}" requires exactly one upstream binding for upstream MCP mode; found ${a.length}. Check the route's upstream MCP binding policies and keep exactly one binding on this route.`);let i=RM(e),s=dv({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),c=ue(e.url),d=new qs({enableDnsRebindingProtection:!0,allowedOrigins:[c]}),p=new $s(n.catalog.serverInfo??{name:r.virtualServerId,version:_M},{capabilities:{prompts:{},resources:{},tools:{}},jsonSchemaValidator:wM});p.setRequestHandler(Tu,async m=>jr({methodName:"tools/list",params:Js(m),jsonRpcRequestId:vn(m),...i},()=>s.listTools())),p.setRequestHandler(Bo,async m=>jr({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:vn(m),...i},()=>s.callTool(m.params))),p.setRequestHandler(wu,async m=>jr({methodName:"prompts/list",params:Js(m),jsonRpcRequestId:vn(m),...i},()=>s.listPrompts())),p.setRequestHandler(Ru,async m=>jr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:vn(m),...i},()=>s.getPrompt(m.params))),p.setRequestHandler(mu,async m=>jr({methodName:"resources/list",params:Js(m),jsonRpcRequestId:vn(m),...i},()=>s.listResources())),p.setRequestHandler(hu,async m=>jr({methodName:"resources/templates/list",params:Js(m),jsonRpcRequestId:vn(m),...i},()=>s.listResourceTemplates())),p.setRequestHandler(Su,async m=>jr({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:vn(m),...i},()=>s.readResource(m.params))),await p.connect(d);let l=await d.handleRequest(e);return CM(l)}o(Ip,"virtualServerHandler");async function IM(e,t){return Ut("handler.mcp-virtual-server"),Ip(e,t)}o(IM,"McpVirtualServerHandler");function PM(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(PM,"buildRouteAuthBaseFromConnection");function fv(e){if(!e.connection.authProfiles[e.authMode])throw new $(`Upstream connection "${e.connection.id}" does not declare auth mode "${e.authMode}". Check the MCP upstream connection policy and use one of the auth modes declared in policies.json.`);let r=$t(e.authMode);return{upstreamServerId:e.connection.id,virtualServerId:e.virtualServerId,authProfileId:Gn(e.connection.id,e.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.authMode,ownerMode:r.ownerMode}}o(fv,"buildRouteAuthBaseFromPolicyOptions");function hv(e,t){let n=st().byVirtualServerId.get(t);if(!n)throw new $(`Unknown virtual server "${t}". Ensure routes.oas.json declares this MCP virtual server before starting an upstream connection flow.`);let a=n.connections.find(i=>i.upstreamServerId===e);if(!a)throw new $(`Virtual server "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream to this virtual server before starting an upstream connection flow.`);return PM({connection:a,virtualServerId:t})}o(hv,"resolveRouteAuthBase");function mv(e,t){switch(e){case"user":return yr(t.subjectId);case"shared":return mi()}}o(mv,"buildOwnerForPrincipal");function Ws(e,t){switch(e.ownerMode){case"shared":return{...e,owner:mv(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:mv(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(Ws,"resolveRouteAuthForPrincipal");function xM(e){let t=Object.keys(e.connection.authProfiles);if(t.length!==1)throw new te(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];if(r===void 0)throw new te(`Upstream policy ${e.policyName} does not declare an auth mode.`);return ri.parse(r)}o(xM,"readSingleAuthMode");async function Pp(e,t,r,n){let a=xM({policyName:n,connection:r}),i=Tn(t),s=fv({connection:r,virtualServerId:i.virtualServerId,authMode:a});if(s.ownerMode==="none")return yd(t,{...s,connectionPolicyName:n}),e;let c=Lm(t);return yd(t,{...Ws(s,c),connectionPolicyName:n}),e}o(Pp,"mcpUpstreamConnectionPolicy");var xp=class extends kn{static{o(this,"McpUpstreamConnectionInboundPolicy")}#t;constructor(t,r){let n=Oi(t,r);super(n,r),this.#t=n}async handler(t,r){return Ut("policy.inbound.mcp-upstream-connection"),Pp(t,r,this.#t,this.policyName)}};me();var gv="application/json",AM="application/x-www-form-urlencoded";function Ys(e,t){return new A({message:e,extensionMembers:{[T]:"invalid_request"}},t===void 0?void 0:{cause:t})}o(Ys,"invalidRequestError");function kM(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(kM,"normalizeContentType");function TM(e,t){return e===t?!0:t===gv&&e.endsWith("+json")}o(TM,"contentTypeMatches");function EM(e,t){if(!t||t.length===0)return;let r=kM(e.headers.get("content-type"));if(!t.some(n=>TM(r,n)))throw Ys(`Request body must be ${t.join(" or ")}.`)}o(EM,"assertExpectedContentType");function UM(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 Ys(`${r} exceeded the maximum allowed size.`)}o(UM,"assertContentLengthWithinLimit");async function yv(e,t){let r=t.label??"Request body";EM(e,t.expectedContentTypes),UM(e,t.maxBytes,r);let n=await Ni(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>Ys(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(yv,"readBoundedTextBody");async function Sv(e,t){let r=await yv(e,{...t,expectedContentTypes:[gv]});try{return JSON.parse(r)}catch(n){throw Ys("Request body must be valid JSON.",n)}}o(Sv,"readBoundedJsonBody");async function Xs(e,t){let r=await yv(e,{...t,expectedContentTypes:[AM]});return new URLSearchParams(r)}o(Xs,"readBoundedFormUrlEncodedBody");var _v=Symbol("Html");function OM(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(OM,"escapeHtml");function MM(e){return e===null||typeof e!="object"?!1:e[_v]===!0}o(MM,"isHtml");function vv(e){return e==null||e===!1?"":Array.isArray(e)?e.map(vv).join(""):MM(e)?e.value:OM(String(e))}o(vv,"renderValue");function dr(e){return{[_v]:!0,value:e}}o(dr,"trustedHtml");var Ha=dr("");function le(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=vv(t[n]),r+=e[n+1]??"";return dr(r)}o(le,"html");function Lr(e){return e.value}o(Lr,"renderHtml");var lr=dr('*,: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 pr(e){return le`<!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>
56
+ `&&n++}}return[t,r]}o(nM,"splitLines");var Zs=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(i){a=X_({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 oM={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}},Ks=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=Y_(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??oM}async _authThenStart(){if(!this._authProvider)throw new xt("No auth provider");let t;try{t=await zr(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=Vs(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 Zs({onRetry:o(g=>{this._serverRetryMs=g},"onRetry")})).getReader();for(;;){let{value:g,done:S}=await l.read();if(S)break;if(g.id&&(s=g.id,c=!0,a?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let y=en.parse(JSON.parse(g.data));It(y)&&(d=!0,i!==void 0&&(y.id=i)),this.onmessage?.(y)}catch(y){this.onerror?.(y)}}(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(g){this.onerror?.(new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}},"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 zr(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:qt(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:g,scope:S}=fd(c);if(this._resourceMetadataUrl=g,this._scope=S,await zr(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:g,scope:S,error:y}=fd(c);if(y==="insufficient_scope"){let _=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new Kr(403,"Server returned 403 after trying upscoping");if(S&&(this._scope=S),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=_??void 0,await zr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new xt;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(),xm(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(),g=Array.isArray(h)?h.map(S=>en.parse(S)):[en.parse(h)];for(let S of g)this.onmessage?.(S)}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 Q_(e=[]){let t={};for(let r of e){if(!r.value){if(r.required)throw new q(`Native MCP transport header "${r.name}" is required but has no value configured. Set the env var that backs the header or mark the header optional.`);continue}t[r.name]=r.value}return t}o(Q_,"resolveNativeMcpRequestHeaders");var aM={name:"zuplo-mcp-gateway",version:"0.1.0"},iM=new vo({draft:"7",shortcircuit:!1}),sM=5,cM=500,nv=3e4,uM=2*1024*1024,dM=2,Ba="upstream_capability_invocation_failed",ev="upstream_import_failed";function tv(){return performance.now()/1e3}o(tv,"nowSeconds");function lM(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(lM,"readServerPort");function pM(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:lM(e)}}o(pM,"buildNativeMcpOperationContext");function Rn(e){return J_(e)}o(Rn,"withTraceMeta");function Js(e){if(e>cM)throw new E({message:Qe[ev].publicDetail,extensionMembers:{[T]:ev}},{cause:new Error("Upstream import exceeded the maximum allowed capability count.")})}o(Js,"assertImportedCapabilityBudget");function rv(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(rv,"buildRequestInit");function mM(e){return(t,r)=>Jn(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:dM,maxResponseBytes:uM,problemCode:Ba,timeoutMs:nv})}o(mM,"createNativeMcpFetch");function fM(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(new E({message:Qe[Ba].publicDetail,extensionMembers:{[T]:Ba}},{cause:new Error("Upstream MCP request exceeded the maximum allowed time.")}))},nv);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(fM,"withNativeMcpRequestTimeout");function hM(e,t=[]){let r=Q_(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],i={fetch:mM(a)};if(!e)return{...i,...rv(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...i,...rv(r)};case"bearer_token":return{...i,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...i,requestInit:{headers:{...r,...e.headers}}}}}o(hM,"buildNativeMcpTransportOptions");async function Cn(e,t,r){let{transport:n}=Ge(e),a=new URL(n.baseUrl),i=new Ks(a,hM(r,n.requestHeaders)),s=new Gs(aM,{capabilities:{},jsonSchemaValidator:iM});return fM((async()=>{let c=tv();await s.connect(i);let d=i.sessionId,p=pM(a,d),l,m=!1,h;try{h=await t(s,p)}catch(S){m=!0,l=S}let g;try{await s.close()}catch(S){g=S}if(d&&W_(p,tv()-c),m)throw l;if(g!==void 0)throw g;return h})())}o(Cn,"withNativeMcpClient");async function gM(e,t,r){let n=[],a,i=0;do{if(i>=sM)throw new E({message:Qe[Ba].publicDetail,extensionMembers:{[T]:Ba}},{cause:new Error(`${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(gM,"collectPaginatedSdkItems");async function Ws(e){return e.enabled?gM(e.label,e.fetchPage,e.readItems):[]}o(Ws,"listNativeMcpCapabilityItems");async function ov(e){return Cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Fr({methodName:"tools/list",...r},()=>Ws({enabled:!!n?.tools,label:"Tool list",fetchPage:o(i=>t.listTools(Rn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.tools,"readItems")}));return Js(a.length),{tools:a}},e.credential)}o(ov,"listNativeMcpTools");async function av(e){return Cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Fr({methodName:"prompts/list",...r},()=>Ws({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(i=>t.listPrompts(Rn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.prompts,"readItems")}));return Js(a.length),{prompts:a}},e.credential)}o(av,"listNativeMcpPrompts");async function iv(e){return Cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Fr({methodName:"resources/list",...r},()=>Ws({enabled:!!n?.resources,label:"Resource list",fetchPage:o(i=>t.listResources(Rn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resources,"readItems")}));return Js(a.length),{resources:a}},e.credential)}o(iv,"listNativeMcpResources");async function sv(e){return Cn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Fr({methodName:"resources/templates/list",...r},()=>Ws({enabled:!!n?.resources,label:"Resource template list",fetchPage:o(i=>t.listResourceTemplates(Rn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resourceTemplates,"readItems")}));return Js(a.length),{resourceTemplates:a}},e.credential)}o(sv,"listNativeMcpResourceTemplates");async function cv(e){return Cn(e.upstreamServerId,(t,r)=>Fr({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(Rn(e.params))),e.credential)}o(cv,"callNativeMcpTool");async function uv(e){return Cn(e.upstreamServerId,(t,r)=>Fr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(Rn(e.params))),e.credential)}o(uv,"getNativeMcpPrompt");async function dv(e){return Cn(e.upstreamServerId,(t,r)=>Fr({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(Rn(e.params))),e.credential)}o(dv,"readNativeMcpResource");var wo=class extends I{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(k.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}},Ga=class extends I{static{o(this,"GatewayAuthorizationMcpError")}authorizationFailureKind;constructor(t){super(k.InvalidRequest,vM(t)),this.name="GatewayAuthorizationMcpError",this.authorizationFailureKind=t}};function yM(e){return{content:[{type:"text",text:e}],isError:!0}}o(yM,"buildToolErrorResult");function hv(e){return e.authUrl?new Ct([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new wo(e)}o(hv,"toConnectRequiredError");function SM(e){if(e.type!=="mcp_oauth_provider")return;let{provider:t}=e;if(!("authorizationUrl"in t))return;let{authorizationUrl:r}=t;return typeof r=="string"&&r.length>0?r:void 0}o(SM,"readOAuthAuthorizationUrl");function _M(e,t){return SM(t)===void 0?!1:e instanceof xt||e instanceof Error&&e.message==="Unauthorized"}o(_M,"isOAuthRedirectUnauthorizedError");function vM(e){switch(e){case"resource_mismatch":return"Gateway access token was not issued for this MCP resource.";case"principal_mismatch":return"Gateway access token principal did not match the request.";default:return"Gateway access token is expired, revoked, or invalid."}}o(vM,"readCompositeAuthorizationFailureDetail");function wM(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(wM,"buildCredentialResolvedAttributes");function bM(e){J(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:wM(e.credential)})}o(bM,"emitCredentialResolvedAnalyticsEvent");function gv(e){if(J(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}}),e.payload.state==="reconsent_required")J(e.context,{eventType:F.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}});else{let t=RM(e.payload.state);J(e.context,{eventType:F.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:t,reasonClass:"auth",attributes:{nextAction:e.payload.nextAction,state:e.payload.state}})}}o(gv,"emitCredentialMissingAnalyticsEvent");function RM(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required";default:{let t=e;return"connect_required"}}}o(RM,"connectRequiredReasonCode");function CM(e){return e.ownerMode==="none"?JSON.stringify(["none",e.upstreamServerId,e.authProfileId]):Er({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId})}o(CM,"readRouteBindingCredentialCacheKey");function bp(e){if(e.ownerMode!=="none")return{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}}o(bp,"readOwnedRouteBindingLookup");async function IM(e){let t=Uu(e.request);if(!t)return new Map;let r=new Map;for(let s of e.routeBindings){let c=bp(s);c!==void 0&&r.set(Er(c),c)}if(r.size===0)return new Map;let n=[...r.values()],a=await Y().authorizeAndLoadConnections({accessTokenHash:await fe(t),resource:Ar(e.virtualServerId,e.request.url),virtualServerId:e.virtualServerId,upstreamConnectionKeys:n,now:oe(new Date)});if(a.kind!=="authorized")throw new Ga(a.kind);let i=new Map;return a.upstreamConnections.forEach((s,c)=>{let d=n[c];d!==void 0&&i.set(Er(d),s.connection)}),i}o(IM,"preloadCompositeAuthorizedConnections");function PM(e){let t=new Map;return r=>{let n=CM(r),a=t.get(n);if(a)return a;let i=(async()=>{let s=await e.preloadedConnections,c=bp(r),d=c===void 0?void 0:Er(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 gv({context:e.context,payload:p.payload,routeBinding:r}),hv(p.payload);return bM({context:e.context,credential:p.credential,routeBinding:r}),p.credential})();return t.set(n,i),i}}o(PM,"createCredentialResolver");var lv=500;function Rp(e){return e.length<=lv?e:`${e.slice(0,lv)}...`}o(Rp,"truncateAnalyticsDetail");function xM(e){J(e.context,{eventType:F.MCP_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,latencyMs:e.latencyMs})}o(xM,"emitToolInvocationCompletedAnalyticsEvent");function vp(e){J(e.context,{eventType:F.MCP_CAPABILITY_INVOKED,outcome:"success",routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType})}o(vp,"emitCapabilityInvokedAnalyticsEvent");function pv(e){let t={};typeof e.itemCount=="number"&&(t.itemCount=e.itemCount),e.errorDetail!==void 0&&(t.detail=Rp(e.errorDetail)),J(e.context,{eventType:F.MCP_CAPABILITY_LISTED,outcome:e.outcome,...e.routeBinding?{routeBinding:e.routeBinding}:{},...e.virtualServerName?{virtualServerName:e.virtualServerName}:{},mcpMethod:e.mcpMethod,capabilityType:e.capabilityType,latencyMs:e.latencyMs,...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.reasonClass?{reasonClass:e.reasonClass}:{},...e.errorType?{errorType:e.errorType}:{},attributes:t})}o(pv,"emitCapabilityListedAnalyticsEvent");function mv(e){J(e.context,{eventType:F.MCP_CAPABILITY_COMPLETED,outcome:"success",routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType,latencyMs:e.latencyMs})}o(mv,"emitCapabilityCompletedAnalyticsEvent");function fv(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=e.error instanceof Ct||e.error instanceof wo,n=e.error instanceof I&&e.error.code===k.InvalidParams,a=r?F.MCP_CAPABILITY_CONNECT_REQUIRED:F.MCP_CAPABILITY_FAILED,i=r?"connect_required":"failure",s=r?"connect_required":n?"invalid_capability_arguments":"upstream_capability_invocation_failed",c=r?"auth":n?"client":"upstream";J(e.context,{eventType:a,outcome:i,routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType,reasonCode:s,reasonClass:c,errorType:r?"connect_required":"capability_error",...n?{mcpErrorType:"InvalidParams"}:{},latencyMs:e.latencyMs,attributes:{detail:Rp(t)}})}o(fv,"emitCapabilityFailedAnalyticsEvent");function kM(e){return e instanceof Ct||e instanceof wo?{eventType:F.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof Ga?{eventType:F.MCP_CAPABILITY_FAILED,outcome:"denied",reasonCode:`gateway_access_token_${e.authorizationFailureKind}`,reasonClass:"auth",errorType:"auth_error",mcpErrorType:"InvalidRequest"}:e instanceof I&&e.code===k.InvalidParams?{eventType:F.MCP_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:F.MCP_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(kM,"classifyToolInvocationFailure");function AM(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=kM(e.error);J(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,latencyMs:e.latencyMs,attributes:{detail:Rp(t)}})}o(AM,"emitToolInvocationFailedAnalyticsEvent");var TM=256*1024;function EM(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new I(k.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>TM)throw new I(k.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o(EM,"assertToolArgumentsWithinLimit");function wp(e,t){throw e instanceof I||e instanceof q||e instanceof K?e:new I(k.InternalError,Qe[t].publicDetail)}o(wp,"throwSafeUpstreamMcpError");function Cp(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 I(k.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o(Cp,"findBindingForPublishedCapability");function In(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new I(k.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(In,"requireSingleTransparentBinding");function UM(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:In(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new I(k.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Cp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(UM,"resolvePublishedToolRoute");function OM(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:In(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new I(k.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Cp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(OM,"resolvePublishedPromptRoute");function MM(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:In(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new I(k.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:Cp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(MM,"resolvePublishedResourceRoute");function yv(e){let t=IM({request:e.request,routeBindings:e.routeBindings,virtualServerId:e.publishedVirtualServer.virtualServerId}),r=PM({context:e.context,preloadedConnections:t,request:e.request}),n=e.publishedVirtualServer.virtualServerId;async function a(c){if(!_M(c.error,c.credential)||c.routeBinding.ownerMode==="none")return;let d=bp(c.routeBinding);if(d===void 0)return;let l=(await t).get(Er(d))?.id,m=c.routeBinding.owner.mode==="shared"?Wn({upstreamServerId:c.routeBinding.upstreamServerId,authProfileId:c.routeBinding.authProfileId,upstreamDisplayName:c.routeBinding.upstreamDisplayName,virtualServerId:c.routeBinding.virtualServerId,...l===void 0?{}:{connectionId:l},requiresReconsent:!0}):await Lt({requestUrl:e.request.url,owner:c.routeBinding.owner,initiatedBySubjectId:c.routeBinding.initiatedBySubjectId,upstreamServerId:c.routeBinding.upstreamServerId,authProfileId:c.routeBinding.authProfileId,upstreamDisplayName:c.routeBinding.upstreamDisplayName,virtualServerId:c.routeBinding.virtualServerId,subject:"tool",...l===void 0?{}:{connectionId:l},requiresReconsent:!0,...c.routeBinding.returnTo===void 0?{}:{returnTo:c.routeBinding.returnTo}});return gv({context:e.context,payload:m,routeBinding:c.routeBinding}),hv(m)}o(a,"buildForwardingConnectRequiredError");async function i(c){let d=await r(c.routeBinding);try{return await c.invoke(d)}catch(p){let l=await a({credential:d,error:p,routeBinding:c.routeBinding});throw l!==void 0?l:p}}o(i,"invokeNativeMcpWithCredential");async function s(c){let d=Date.now();try{let p=await c.invoke();return pv({context:e.context,routeBinding:c.routeBinding,virtualServerName:n,capabilityType:c.capabilityType,mcpMethod:c.mcpMethod,outcome:"success",itemCount:c.countItems(p),latencyMs:Date.now()-d}),p}catch(p){let l=p instanceof Error?p.message:String(p);if(pv({context:e.context,routeBinding:c.routeBinding,virtualServerName:n,capabilityType:c.capabilityType,mcpMethod:c.mcpMethod,outcome:"failure",latencyMs:Date.now()-d,reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",errorType:"capability_list_error",errorDetail:l}),c.routeBinding===void 0)throw p;wp(p,"upstream_import_failed")}}return o(s,"listCapability"),{async listTools(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return s({capabilityType:"tool",mcpMethod:"tools/list",invoke:o(async()=>({tools:e.publishedVirtualServer.catalog.tools.filter(d=>d.enabled!==!1).map($i)}),"invoke"),countItems:o(d=>d.tools.length,"countItems")});let c=In(e);return s({capabilityType:"tool",mcpMethod:"tools/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>ov({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.tools.length,"countItems")})},async callTool(c){let d=UM({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:c.name});vp({context:e.context,routeBinding:d.binding,capabilityType:"tool",capabilityName:c.name,mcpMethod:"tools/call"});let p=Date.now();try{EM(c);let l=await i({routeBinding:d.binding,invoke:o(m=>cv({upstreamServerId:d.binding.upstreamServerId,params:{...c,name:d.upstreamName},credential:m}),"invoke")});return xM({context:e.context,routeBinding:d.binding,toolName:c.name,result:l,latencyMs:Date.now()-p}),e.context.log.debug({event:"upstream_tool_invocation_succeeded",toolName:c.name,upstreamName:d.upstreamName,upstreamServerId:d.binding.upstreamServerId,authProfileId:d.binding.authProfileId,isError:l.isError===!0},"Upstream tool invocation completed"),l}catch(l){if(AM({context:e.context,routeBinding:d.binding,toolName:c.name,error:l,latencyMs:Date.now()-p}),l instanceof Ct||l instanceof wo)throw e.context.log.info({event:"upstream_tool_invocation_connect_required",toolName:c.name,upstreamServerId:d.binding.upstreamServerId,authProfileId:d.binding.authProfileId,ownerMode:d.binding.ownerMode,hasAuthUrl:l instanceof Ct},"Upstream tool invocation requires user to complete a connect flow"),l;if(l instanceof Ga)throw e.context.log.warn({event:"upstream_tool_invocation_gateway_auth_denied",toolName:c.name,upstreamServerId:d.binding.upstreamServerId,authProfileId:d.binding.authProfileId,validationKind:l.authorizationFailureKind},"Gateway access token failed composite authorization; MCP tool invocation denied"),l;let m={event:"upstream_tool_invocation_failed",code:"upstream_capability_invocation_failed",toolName:c.name,upstreamName:d.upstreamName,upstreamServerId:d.binding.upstreamServerId,authProfileId:d.binding.authProfileId};return l instanceof I&&(m.mcpErrorCode=l.code),l instanceof Error?(m.errorName=l.name,m.errorMessage=l.message,l.cause instanceof Error&&(m.causeName=l.cause.name,m.causeMessage=l.cause.message)):m.errorMessage=String(l),e.context.log.warn(m,"Upstream tool invocation failed; returning generic gateway error to MCP client"),yM(Qe.upstream_capability_invocation_failed.publicDetail)}},async listPrompts(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return s({capabilityType:"prompt",mcpMethod:"prompts/list",invoke:o(async()=>({prompts:e.publishedVirtualServer.catalog.prompts.filter(d=>d.enabled!==!1).map(qi)}),"invoke"),countItems:o(d=>d.prompts.length,"countItems")});let c=In(e);return s({capabilityType:"prompt",mcpMethod:"prompts/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>av({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.prompts.length,"countItems")})},async getPrompt(c){let d=OM({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:c.name});vp({context:e.context,routeBinding:d.binding,capabilityType:"prompt",capabilityName:c.name,mcpMethod:"prompts/get"});let p=Date.now();try{let l=await i({routeBinding:d.binding,invoke:o(m=>uv({upstreamServerId:d.binding.upstreamServerId,params:{...c,name:d.upstreamName},credential:m}),"invoke")});return mv({context:e.context,routeBinding:d.binding,capabilityType:"prompt",capabilityName:c.name,mcpMethod:"prompts/get",latencyMs:Date.now()-p}),l}catch(l){fv({context:e.context,routeBinding:d.binding,capabilityType:"prompt",capabilityName:c.name,mcpMethod:"prompts/get",error:l,latencyMs:Date.now()-p}),wp(l,"upstream_capability_invocation_failed")}},async listResources(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return s({capabilityType:"resource",mcpMethod:"resources/list",invoke:o(async()=>({resources:e.publishedVirtualServer.catalog.resources.filter(d=>d.enabled!==!1).map(Ni)}),"invoke"),countItems:o(d=>d.resources.length,"countItems")});let c=In(e);return s({capabilityType:"resource",mcpMethod:"resources/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>iv({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.resources.length,"countItems")})},async listResourceTemplates(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{resourceTemplates:[]};let c=In(e);return s({capabilityType:"resource",mcpMethod:"resources/templates/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>sv({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.resourceTemplates.length,"countItems")})},async readResource(c){let d=MM({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:c.uri});vp({context:e.context,routeBinding:d.binding,capabilityType:"resource",capabilityName:c.uri,mcpMethod:"resources/read"});let p=Date.now();try{let l=await i({routeBinding:d.binding,invoke:o(m=>dv({upstreamServerId:d.binding.upstreamServerId,params:{...c,uri:d.upstreamUri},credential:m}),"invoke")});return mv({context:e.context,routeBinding:d.binding,capabilityType:"resource",capabilityName:c.uri,mcpMethod:"resources/read",latencyMs:Date.now()-p}),l}catch(l){fv({context:e.context,routeBinding:d.binding,capabilityType:"resource",capabilityName:c.uri,mcpMethod:"resources/read",error:l,latencyMs:Date.now()-p}),wp(l,"upstream_capability_invocation_failed")}}}}o(yv,"createCapabilityDispatcher");var zM="0.1.0",_v="POST",$M="POST, OPTIONS",qM=new vo({draft:"7",shortcircuit:!1});function Ip(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:_v}})}o(Ip,"jsonRpcMethodNotAllowedResponse");function NM(e){let t={Allow:_v},r=e.headers.get("origin"),n=e.headers.get("access-control-request-method");if(r&&n){t["Access-Control-Allow-Methods"]=$M;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(NM,"buildOptionsResponse");function Pn(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o(Pn,"readJsonRpcRequestId");function Ys(e){return e&&typeof e=="object"?e.params:void 0}o(Ys,"readMcpRequestParams");function Sv(e,t){return e.headers.get(t)??void 0}o(Sv,"readMcpHeader");function DM(e){return{mcpProtocolVersion:Sv(e,"mcp-protocol-version")??rn,mcpSessionId:Sv(e,"mcp-session-id")}}o(DM,"buildServerTelemetryBase");function jM(e){if(e.headers.has("mcp-protocol-version"))return e;let t=new Headers(e.headers);return t.set("mcp-protocol-version",rn),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(jM,"ensureProtocolVersionHeader");async function Pp(e,t){if(e.method==="OPTIONS")return NM(e);if(e.method==="GET")return Ip("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return Ip("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return Ip("Only POST is supported by this virtual MCP server.");let r=qn(t),n=Nt(r.virtualServerId),a=Wi(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"),new q(`MCP virtual server route "${n.routePath}" requires exactly one upstream binding for upstream MCP mode; found ${a.length}. Check the route's upstream MCP binding policies and keep exactly one binding on this route.`);let i=DM(e),s=yv({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),c=le(e.url),d=new Ds({enableDnsRebindingProtection:!0,allowedOrigins:[c]}),p=new Ns(n.catalog.serverInfo??{name:r.virtualServerId,version:zM},{capabilities:{prompts:{},resources:{},tools:{}},jsonSchemaValidator:qM});p.setRequestHandler(Kc,async m=>Zr({methodName:"tools/list",params:Ys(m),jsonRpcRequestId:Pn(m),...i},()=>s.listTools())),p.setRequestHandler(Do,async m=>Zr({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:Pn(m),...i},()=>s.callTool(m.params))),p.setRequestHandler(Dc,async m=>Zr({methodName:"prompts/list",params:Ys(m),jsonRpcRequestId:Pn(m),...i},()=>s.listPrompts())),p.setRequestHandler(Hc,async m=>Zr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:Pn(m),...i},()=>s.getPrompt(m.params))),p.setRequestHandler(Ec,async m=>Zr({methodName:"resources/list",params:Ys(m),jsonRpcRequestId:Pn(m),...i},()=>s.listResources())),p.setRequestHandler(Oc,async m=>Zr({methodName:"resources/templates/list",params:Ys(m),jsonRpcRequestId:Pn(m),...i},()=>s.listResourceTemplates())),p.setRequestHandler($c,async m=>Zr({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:Pn(m),...i},()=>s.readResource(m.params))),await p.connect(d);let l=await d.handleRequest(e);return jM(l)}o(Pp,"virtualServerHandler");async function HM(e,t){return zt("handler.mcp-virtual-server"),Pp(e,t)}o(HM,"McpVirtualServerHandler");function LM(e){let t=jt(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(LM,"buildRouteAuthBaseFromConnection");function wv(e){if(!e.connection.authProfiles[e.authMode])throw new q(`Upstream connection "${e.connection.id}" does not declare auth mode "${e.authMode}". Check the MCP upstream connection policy and use one of the auth modes declared in policies.json.`);let r=jt(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(wv,"buildRouteAuthBaseFromPolicyOptions");function bv(e,t){let n=rt().byVirtualServerId.get(t);if(!n)throw new q(`Unknown virtual server "${t}". Ensure routes.oas.json declares this MCP virtual server before starting an upstream connection flow.`);let a=n.connections.find(i=>i.upstreamServerId===e);if(!a)throw new q(`Virtual server "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream to this virtual server before starting an upstream connection flow.`);return LM({connection:a,virtualServerId:t})}o(bv,"resolveRouteAuthBase");function vv(e,t){switch(e){case"user":return Tr(t.subjectId);case"shared":return Ai()}}o(vv,"buildOwnerForPrincipal");function Xs(e,t){switch(e.ownerMode){case"shared":return{...e,owner:vv(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:vv(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(Xs,"resolveRouteAuthForPrincipal");function BM(e){let t=Object.keys(e.connection.authProfiles);if(t.length!==1)throw new K(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];if(r===void 0)throw new K(`Upstream policy ${e.policyName} does not declare an auth mode.`);return vi.parse(r)}o(BM,"readSingleAuthMode");async function xp(e,t,r,n){let a=BM({policyName:n,connection:r}),i=qn(t),s=wv({connection:r,virtualServerId:i.virtualServerId,authMode:a});if(s.ownerMode==="none")return _d(t,{...s,connectionPolicyName:n}),e;let c=df(t);return _d(t,{...Xs(s,c),connectionPolicyName:n}),e}o(xp,"mcpUpstreamConnectionPolicy");var kp=class extends Un{static{o(this,"McpUpstreamConnectionInboundPolicy")}#t;constructor(t,r){let n=zi(t,r);super(n,r),this.#t=n}async handler(t,r){return zt("policy.inbound.mcp-upstream-connection"),xp(t,r,this.#t,this.policyName)}};de();var Rv=Symbol("Html");function GM(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}o(GM,"escapeHtml");function VM(e){return e===null||typeof e!="object"?!1:e[Rv]===!0}o(VM,"isHtml");function Cv(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Cv).join(""):VM(e)?e.value:GM(String(e))}o(Cv,"renderValue");function gr(e){return{[Rv]:!0,value:e}}o(gr,"trustedHtml");var xn=gr("");function se(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=Cv(t[n]),r+=e[n+1]??"";return gr(r)}o(se,"html");function Wt(e){return e.value}o(Wt,"renderHtml");function Iv(e){return se`<p data-gateway-error-code="${e.code}">${e.detail}</p>${e.guidance} ${e.action}`}o(Iv,"renderBrowserErrorPage");var Ot=gr('*,: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 Mt(e){return se`<!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>
57
57
  ${e.styles}
58
- </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(pr,"renderShell");var Ap="zuplo.com";function wv(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(wv,"s2FaviconHref");function zM(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(zM,"strictFaviconHref");var wn=wv(Ap);function bn(e){let t=e.toLowerCase();return t===Ap||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?wv(Ap):zM(e)}o(bn,"resolveIconHref");function Rn(e){return le`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}o(Rn,"renderShellIcon");function bv(e){return le`<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(bv,"renderActions");var D3=dr('<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 Rv(){return le`<p>The API key could not be verified. Start the authorization flow again to try
59
- once more.</p>`}o(Rv,"renderApiKeyLoginFailure");function Cv(e){return le`<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(Cv,"renderApiKeyLoginForm");var j3=dr('<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>'),H3=dr('<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 L3=dr('<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 $M="text/html; charset=utf-8";function Iv(e,t=200){return new Response(Lr(e),{status:t,headers:{"content-type":$M,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(Iv,"apiKeyLoginHtmlResponse");function kp(e,t=401){let r=bn(e);return Iv(pr({title:"Sign-in failed",iconHref:r,styles:lr,headerIcon:Rn({iconHref:r,fallbackIconHref:wn}),heading:"Sign-in failed",subhead:"",body:Rv(),footer:""}),t)}o(kp,"apiKeyLoginFailureResponse");function Pv(e,t){let r=bn(e);return Iv(pr({title:"Sign in",iconHref:r,styles:lr,headerIcon:Rn({iconHref:r,fallbackIconHref:wn}),heading:"Sign in",subhead:le`<p class="card__subtitle">Enter your API key to continue.</p>`,body:Cv({state:t}),footer:""}))}o(Pv,"renderApiKeyLoginForm");me();me();import{errors as Mv,jwtVerify as zv,SignJWT as $v}from"jose";me();import{errors as KM,jwtVerify as JM,SignJWT as WM}from"jose";function Br(e){let t=Te().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw D("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}o(Br,"requireBrowserLoginField");me();import{createRemoteJWKSet as NM,errors as La,jwtVerify as DM}from"jose";var jM=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()}),HM=u.object({error:u.string().min(1).optional(),error_description:u.string().min(1).optional(),error_uri:u.string().min(1).optional()});function LM(e){let t=HM.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(LM,"readIdpErrorFields");function BM(e){return e instanceof La.JWTExpired?"expired":e instanceof La.JWTClaimValidationFailed?"claim":e instanceof La.JWSSignatureVerificationFailed?"signature":e instanceof La.JWKSNoMatchingKey?"jwks_no_match":e instanceof La.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(BM,"readJwtFailureKind");var GM=u.object({sub:ve,nonce:u.string().min(1)}).catchall(u.unknown()),Tp;function VM(e){return e instanceof Error&&"cause"in e?e.cause:e}o(VM,"readErrorCause");function FM(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(FM,"readRuntimeGatewayCode");function ZM(){if(!Tp){let e=Te();Tp=NM(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Tp}o(ZM,"readFederatedJwks");async function xv(e){let t=Te(),r=Br("tokenUrl"),n=Br("clientId"),a=Br("clientSecret"),i=new URL("/oauth/callback",wt(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=LM(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"),D({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=jM.parse(d),l;try{({payload:l}=await DM(p.id_token,ZM(),{issuer:t.oidc.issuer,audience:n}))}catch(h){let g={};throw Xe(g,"error",h),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:BM(h),idpHost:mt(r),expectedIssuer:t.oidc.issuer,...g},"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"),D("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let m=GM.parse(l);return On({sub:m.sub,data:m},e.requestUrl)}catch(c){let d=Rt(c)??FM(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:D("browser_login_verification_failed","Federated browser login callback could not be verified.",VM(c))}}o(xv,"exchangeFederatedAuthorizationCode");var Up="zuplo_mcp_session",YM=u.object({purpose:u.literal("gateway_browser_session"),sub:ve,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 XM(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(XM,"parseCookieHeader");async function Av(){return qt({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"browser-session"),"derive")})}o(Av,"getBrowserSessionKey");function Ep(e){let t=new URL(ue(e)),r=[`${Up}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(Ep,"buildBrowserSessionEvictionCookie");function QM(e){let t=new URL(ue(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(QM,"serializeSessionCookie");function kv(e={}){return new URL(Br("url")).origin}o(kv,"readBrowserLoginOrigin");function Op(){return Te().browserLogin.stateTtlSeconds}o(Op,"readBrowserLoginStateTtlSeconds");function Tv(e){if(!e.user)throw D("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return On(e.user,e.url)}o(Tv,"resolveCurrentRequestPrincipal");async function Qs(e,t={}){let r=XM(e.headers.get("cookie")).get(Up);if(!r)return{};try{let{payload:n}=await JM(r,await Av(),{algorithms:[ut],issuer:Qe,audience:ct}),a=YM.parse(n);if(a.browserLoginOrigin!==kv(t))return{evictCookie:Ep(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 KM.JWTExpired?{evictCookie:Ep(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:Ep(e.url)})}}o(Qs,"readBrowserSession");async function Ba(e){let t=Te().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:kv({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new WM(r).setProtectedHeader({alg:ut,typ:"JWT"}).setIssuer(Qe).setAudience(ct).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await Av());return QM({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o(Ba,"createBrowserSessionCookie");async function Ev(e){throw D("forbidden","API-key browser login is not supported in this gateway.")}o(Ev,"resolveApiKeyBrowserLoginPrincipal");async function Uv(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await Qs(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 D("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");return xv({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(Uv,"resolveBrowserLoginCallbackPrincipal");function Ov(e){let t=Te().browserLogin,r=new URL(Br("url")),n=new URL("/oauth/callback",wt(e.requestUrl));return $m(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",Br("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(Ov,"buildBrowserLoginUrl");var ez={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},q=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=ez[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var tz=5*60,rz=u.object({purpose:u.literal("gateway_browser_login"),transactionId:at,stateId:ci,exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),nz=u.object({purpose:u.literal("gateway_authorization_setup"),transactionId:at,stateId:ci,exp:u.number().int().positive(),iat:u.number().int().positive().optional()});async function qv(){return qt({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"browser-login"),"derive")})}o(qv,"getBrowserLoginKey");async function Nv(){return qt({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Ir(e,"authorization-csrf"),"derive")})}o(Nv,"getCsrfKey");function Dv(e){return{now:e.now??new Date,ttlSeconds:Op()}}o(Dv,"readPendingTransactionDependencies");function oz(e,t){return e.subjectId===t.subjectId}o(oz,"principalsMatch");function jv(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(jv,"toPendingPrincipal");function Hv(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:oe(e.now),expiresAt:oe(Jt(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 D("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:jv(e.principal)}}o(Hv,"createTransactionRecord");async function Lv(e){let{id:t,...r}=e.record,n=await W().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw D("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new q("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new q("invalid_request","redirect_uri is not registered for the client.")}}o(Lv,"startPendingTransaction");async function az(e){return new $v({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:ut,typ:"JWT"}).setIssuer(Qe).setAudience(ct).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await qv())}o(az,"signBrowserLoginState");async function Bv(e){return new $v({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Mc()}).setProtectedHeader({alg:ut,typ:"JWT"}).setIssuer(Qe).setAudience(ct).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Nv())}o(Bv,"signCsrfToken");async function ec(e){try{let{payload:t}=await zv(e,await qv(),{algorithms:[ut],issuer:Qe,audience:ct}),r=rz.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof Mv.JWTExpired?D("oauth_state_expired","Browser login state has expired.",t):D("oauth_state_invalid","Browser login state could not be verified.",t)}}o(ec,"verifyBrowserLoginStateToken");async function tc(e){try{let{payload:t}=await zv(e,await Nv(),{algorithms:[ut],issuer:Qe,audience:ct});return{transactionId:nz.parse(t).transactionId}}catch(t){throw t instanceof Mv.JWTExpired?D("oauth_state_expired","Authorization setup state has expired.",t):D("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(tc,"verifyCsrfToken");function rc(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(rc,"pendingStateErrorCode");function Gv(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(Gv,"toPendingAuthorizationGetResult");function iz(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(iz,"toPendingAuthorizationAdvanceResult");function Mp(e){return e==="principal_mismatch"?"oauth_callback_mismatch":rc(e==="consumed_already"?"consumed_already":e)}o(Mp,"setupDecisionErrorCode");async function Vv(e){let t=e.now??new Date,r=await tc(e.csrfToken),n=await W().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await fe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:oe(t)});if(n.kind!=="marked")throw D(Mp(n.kind),"Authorization setup state is invalid, expired, or already used.");return Fv({kind:"available",record:n.transaction})}o(Vv,"markSetupApproved");function Fv(e){if(e.kind!=="available")throw D(rc(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw D("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(Fv,"requireAwaitingSetup");function sz(e){if(e.kind!=="available")throw D(rc(e.kind),"Browser login state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_login")throw D("oauth_state_invalid","Browser login state is not in the login phase.");return e.record}o(sz,"requireAwaitingLogin");function cz(e){if(!oz(e.currentBrowserPrincipal,e.transaction.principal))throw D("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(cz,"requireCurrentPrincipalMatches");async function Zv(e){let t=e.now??new Date,r=Op(),n=Oc(),a=Mc(),i=await az({transactionId:n,stateId:a,ttlSeconds:r}),s=Hv({id:n,transaction:e.transaction,currentStateHash:await fe(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw D("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await Lv({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw D("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:i,browserLoginUrl:Ov({state:i,nonce:a,virtualServerId:s.virtualServerId,requestUrl:e.requestUrl})}}o(Zv,"startAwaitingLogin");async function Kv(e){let{now:t,ttlSeconds:r}=Dv(e),n=Oc(),a=await Bv({transactionId:n,ttlSeconds:r}),i=Hv({id:n,transaction:e.transaction,currentStateHash:await fe(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw D("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await Lv({record:i,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw D("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:a}}o(Kv,"startAwaitingSetup");async function zp(e){let{now:t,ttlSeconds:r}=Dv(e),n=await ec(e.browserLoginStateToken),a=await Bv({transactionId:n.transactionId,ttlSeconds:r}),i=iz(await W().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await fe(e.browserLoginStateToken),nextStateHash:await fe(a),nextPhase:"awaiting_setup",principal:jv(e.principal),now:oe(t)}));if(i.kind!=="advanced")throw D(rc(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw D("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:a}}o(zp,"completeLogin");async function Jv(e){let t=e.now??new Date,r=await ec(e.browserLoginStateToken);return sz(Gv(await W().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await fe(e.browserLoginStateToken),now:oe(t)})))}o(Jv,"getAwaitingLogin");async function Wv(e){let t=await $p(e);return cz({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(Wv,"getSetup");async function $p(e){let t=e.now??new Date,r=await tc(e.csrfToken);return Fv(Gv(await W().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await fe(e.csrfToken),now:oe(t)})))}o($p,"getSetupTransaction");async function uz(e){let t=await tc(e.csrfToken),r=Yt(),n=oe(Jt(e.now,tz)),a=await W().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await fe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await fe(r),authorizationCodeExpiresAt:n,grantId:Mm(),now:oe(e.now)});if(a.kind!=="approved")throw D(a.kind==="cancelled"?"oauth_state_invalid":Mp(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(uz,"createAuthorizationCodeRedirectWithDecision");async function dz(e){let t=await tc(e.csrfToken),r=await W().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await fe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:oe(e.now)});if(r.kind!=="cancelled")throw D(r.kind==="approved"?"oauth_state_invalid":Mp(r.kind),"Authorization setup state is invalid, expired, or already used.");return lz({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}o(dz,"createCancelRedirectWithDecision");function lz(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(lz,"buildClientCancelRedirect");async function Yv(e){let t=e.now??new Date;return uz({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(Yv,"approve");async function Xv(e){let t=e.now??new Date;return dz({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(Xv,"cancel");me();var pz=1e4,mz=5*1024,fz=2,hz=90*24*60*60,qp=["authorization_code","refresh_token"],Np=["code"],gz=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(qp)).min(1).max(2).optional(),response_types:u.array(u.enum(Np)).min(1).max(1).optional(),scope:u.literal(_e).optional(),token_endpoint_auth_method:Em.default("none")});function yz(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&ke(t))&&t.pathname!=="/"}catch{return!1}}o(yz,"isCimdClientIdCandidate");function Ga(e,t="invalid_request"){if(Sz(e))throw new q(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new q(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new q(t,"redirect_uris must not include credentials or fragments.");if(!(r.protocol==="https:"||ke(r)))throw new q(t,"redirect_uris must use HTTPS except loopback HTTP redirects for local clients.")}o(Ga,"assertValidRedirectUri");function Sz(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(Sz,"hasForbiddenRawRedirectUriCharacter");async function _z(e){let{response:t,json:r}=await zh(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:fz,maxResponseBytes:mz,timeoutMs:pz});if(!t.ok)throw D("invalid_request","CIMD metadata could not be fetched.");let n=Om.parse(r);if(n.client_id!==e.clientId)throw D("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return n}o(_z,"fetchCimdMetadata");async function vz(e){let t=qi(e),r=await _z({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(vz,"resolveCimdClient");async function nc(e,t){let r=Ue.parse(e);if(yz(r)){if(!Te().gateway.cimdEnabled)throw new q("invalid_client","OAuth client is not registered.");try{return await vz(r)}catch{throw new q("invalid_client","OAuth client is not registered.")}}let n=await W().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 q("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(nc,"resolveClient");function Qv(e,t){if(!e.metadata.redirect_uris.some(r=>zm(r,t)))throw D("invalid_request","redirect_uri is not registered for the client.")}o(Qv,"assertRedirectRegistered");function wz(e){let t=ew(e.grant_types),r=e.response_types??[...Np];if(!bz(t))throw new q("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!Rz(r))throw new q("invalid_client_metadata","response_types must be code.");if(!Cz(e.scope))throw new q("invalid_client_metadata",`Only the ${_e} scope is supported.`)}o(wz,"assertSupportedDcrRequest");function ew(e){return e===void 0?[...qp]:Array.from(new Set(e))}o(ew,"normalizeGrantTypes");function bz(e){return e.length===0?!1:e.every(t=>qp.includes(t))}o(bz,"isSupportedGrantTypes");function Rz(e){return e.length===Np.length&&e[0]==="code"}o(Rz,"isSupportedResponseTypes");function Cz(e){return e===void 0||e===_e}o(Cz,"isSupportedDcrScope");function Va(e){if(e===void 0||e===_e)return _e;throw new q("invalid_request",`Only the ${_e} scope is supported.`)}o(Va,"assertSupportedOAuthScope");function So(e,t){let r;try{r=new URL(t)}catch{throw new q("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new q("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!ke(r))throw new q("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=ue(e),a=Ih(),i=a?[...a.byVirtualServerId.values()].find(s=>new URL(s.routePath,n).toString()===t):void 0;if(!i)throw new q("invalid_target","resource must match a published virtual MCP server.");return i}o(So,"resolveResource");async function tw(e){let t;try{t=gz.parse(e)}catch(l){if(l instanceof u.ZodError){let m=l.issues.some(h=>h.path[0]==="redirect_uris");throw new q(m?"invalid_redirect_uri":"invalid_client_metadata",l.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:l})}throw l}wz(t);for(let l of t.redirect_uris)Ga(l,"invalid_redirect_uri");let r=new Date,n=Ue.parse(`dcr:${crypto.randomUUID()}`),a=Jt(r,hz),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:_e,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:oe(r),clientExpiresAt:oe(a)};if(t.token_endpoint_auth_method!=="none"){let l=Yt();d.hashedClientSecret=await fe(l),d.clientSecretExpiresAt=oe(a),c.client_secret=l,c.client_secret_expires_at=s,c.client_secret_issued_at=i}if((await W().registerClient(d)).kind==="already_exists")throw D("invalid_request","OAuth client is already registered.");return c}o(tw,"registerDownstreamClient");var Iz="data:,",rw=le`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);"`,nw=le`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 Pz(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(Pz,"safeGatewayConnectHref");function xz(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(xz,"deriveMode");function Az(e){return bv({state:e.state,submitOnceAttrs:rw,authorizeAttrs:Ha})}o(Az,"renderActions");function Dp(e,t,r){for(let n of e){if(n.ownerMode!=="user"||n.status!==r)continue;let a=Pz(n.connectUrl,t);if(a)return a}}o(Dp,"firstUserConnectHref");function kz(e){let t=e.connectHref?le`<a class="button button--primary" href="${e.connectHref}" ${nw}>Connect</a>`:le`<button class="button button--primary" type="button" disabled aria-disabled="true">Connect</button>`;return le`<form class="actions" method="post" action="/oauth/setup" ${rw}><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(kz,"renderSetupActions");function Tz(e){return e?le`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${nw}>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>`:Ha}o(Tz,"renderReconnectAction");function jp(e){let t=xz(e.upstreams),r=Dp(e.upstreams,e.gatewayOrigin,"not_connected"),n=Dp(e.upstreams,e.gatewayOrigin,"reconsent_required"),a=Dp(e.upstreams,e.gatewayOrigin,"active"),i=t==="setup"?r??n:void 0,s=le`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.virtualServerDisplayName}</strong>' on your behalf?</p>`,c=t==="setup"?le`<footer class="card__footer">${kz({state:e.state,connectHref:i})}</footer>`:le`<footer class="card__footer">${Tz(a)}${Az({state:e.state})}</footer>`;return Lr(pr({title:`Authorize access \xB7 ${e.virtualServerDisplayName}`,iconHref:Iz,styles:lr,headerIcon:Ha,heading:"MCP Gateway",subhead:Ha,body:s,footer:c}))}o(jp,"renderConsentPage");function Ez(e){try{return new URL(e).host}catch{return}}o(Ez,"safeUrlHost");function Uz(e){if(e.mode==="user-oauth"||e.mode==="shared-oauth")return e.oauth.scopes}o(Uz,"readOAuthScopes");function Hp(e){return e!==void 0&&e.length>0}o(Hp,"hasItems");function Oz(e){let t=e.registeredConnection.config.serverInfo?.icons;if(Hp(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&Hp(r)?r:void 0}o(Oz,"readServerIcons");async function Mz(e){if(!(e.returnTo===void 0||!e.isUserOwned))return Yu({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(Mz,"readConnectUrl");function Cn(e,t){return t===void 0?{}:{[e]:t}}o(Cn,"optionalRequirementField");function zz(e){return e.isUserOwned?Wm(e.connection):{connected:!0,status:"active"}}o(zz,"readSetupConnectionStatus");function $z(e){let t=Uz(e);return Hp(t)?t:void 0}o($z,"readScopesRequested");function qz(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o(qz,"readUpdatedAt");function Nz(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(Mi),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(zi),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map($i)}}o(Nz,"readVirtualServerCapabilities");async function Dz(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:i}=e.registeredConnection,s=ji(r),c=s==="user",d=zz({connection:e.connection,isUserOwned:c}),p=await Mz({...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:Nz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...Cn("description",n.description),...Cn("transportHost",Ez(n.transport.baseUrl)),...Cn("scopesRequested",$z(t)),...Cn("serverIcons",Oz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...Cn("connectUrl",p),...Cn("updatedAt",qz({connectionStatus:d,isUserOwned:c})),...Cn("expiresAt",e.connection?.expiresAt)}}o(Dz,"buildSetupRequirement");function ow(e){let t=st().byVirtualServerId.get(e);if(!t)throw D("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(ow,"requireVirtualServer");async function Lp(e){let t=ow(e.transaction.virtualServerId),r=yr(e.transaction.principal.subjectId),n=[],a=new Map;for(let c of t.connections)ji(c.authMode)==="user"&&(a.set(c,n.length),n.push({owner:r,upstreamServerId:c.upstreamServerId,authProfileId:c.authProfileId}));let i=await W().batchGetUpstreamConnections(n),s=[];for(let c of t.connections){let d=ji(c.authMode)==="user",p=a.get(c);s.push(await Dz({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(Lp,"requirementsForSetup");function jz(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(jz,"readVirtualServerDisplayName");async function Bp(e){let t=ow(e.transaction.virtualServerId),r=jz({virtualServer:t}),n=await W().readClient({clientId:e.transaction.clientId}),a=n.kind==="found"?n.client:void 0,i={gatewayOrigin:ue(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(Bp,"consentContext");function Gp(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(Gp,"hasUnresolvedUserUpstream");var Hz=["mcp_user"],Lz="dev-browser-user",Bz=["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(" "),Gz=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:ii,state:u.string().min(1).optional(),scope:u.literal(_e).default(_e)}),Vz=u.enum(["continue","approve","cancel"]).default("continue"),Fz=u.object({state:u.string().min(1),decision:Vz}),Zz=u.object({state:u.string().min(1),apiKey:u.string().min(1)}),In=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 aw(e){return typeof e=="string"&&e.length>0?e:void 0}o(aw,"readQueryString");function Kz(e){let t=Array.from(st().byVirtualServerId.values());if(t.length!==1)return;let r=t[0];if(r!==void 0)return gr(r.virtualServerId,e.url)}o(Kz,"inferSingleVirtualServerResource");function Jz(e,t){let r=aw(e.query.resource);if(t===void 0){if(r!==void 0)return r;let a=Kz(e);if(a!==void 0)return a;throw new q("invalid_target",Bz)}let n=gr(t,e.url);if(r===void 0||r===n)return n;throw new q("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(Jz,"requireAuthorizeResource");async function Wz(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Qs(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let i=Tv(e);return{principal:i,setCookie:await Ba({principal:i,requestUrl:e.url,virtualServerId:t})}}o(Wz,"resolveBrowserPrincipal");async function Yz(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Qs(e,n);if(!a.principal)throw D("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(Yz,"requireSetupPrincipal");function iw(e){return`/oauth/setup?state=${encodeURIComponent(e)}`}o(iw,"buildSetupReturnTo");async function sw(e){let t=await Lp({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:iw(e.csrfToken)}),r=await Bp({transaction:e.transaction,requestUrl:e.requestUrl}),n={kind:"setup_page",html:jp({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(sw,"renderSetup");function Xz(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(Xz,"toAuthorizationTransactionClient");async function Vp(e,t={}){let r=Gz.parse({...e.query,resource:Jz(e,t.virtualServerId),state:aw(e.query.state)}),n=Va(r.scope);Ga(r.redirect_uri);let a=new Date,i=Ue.parse(r.client_id),s=await nc(r.client_id,a);Qv(s,r.redirect_uri);try{let c=So(e.url,r.resource),d=Xz(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"),t.context&&K(t.context,{eventType:F.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:c.virtualServerId,attributes:{clientId:i,scope:n,responseType:r.response_type}});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 Wz(e,c.virtualServerId,t.context);if(!l){let g=await Zv({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 S={kind:"redirect",location:g.browserLoginUrl};return m!==void 0&&(S.setCookie=m),S}let h=await Kv({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"),t.context&&K(t.context,{eventType:F.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.virtualServerId,attributes:{clientId:i,scope:n,responseType:r.response_type,subjectId:l.subjectId}}),sw({transaction:h.transaction,csrfToken:h.csrfToken,requestUrl:e.url,setCookie:m})}catch(c){throw Qz({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}o(Vp,"authorizeDownstreamClient");function Qz(e){if(e.cause instanceof In)return e.cause;let t=e$(e.cause);return t?new In({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(Qz,"toDownstreamAuthorizeRedirectError");function e$(e){if(e instanceof q)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(e$,"mapToOAuthRedirectError");async function cw(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"),D("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"),D("oauth_state_invalid","Browser login callback is missing state.");let a=await ec(n),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let s=await Uv(i),c=await zp({browserLoginStateToken:n,principal:s}),d=await sw({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return d.setCookie=await Ba({principal:s,requestUrl:e.url,virtualServerId:c.transaction.virtualServerId}),d}o(cw,"completeBrowserLoginCallback");async function uw(e){let t=Te(),r=new URL(e.url);if(!ke(r))throw D("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 D("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",ue(e.url)),i=new URL(ue(e.url)).origin;if(a.origin!==i||a.pathname!=="/oauth/callback")throw D("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");a.searchParams.set("state",n);let s={subjectId:ve.parse(Lz),roles:Hz};return{kind:"redirect",location:a,setCookie:await Ba({principal:s,requestUrl:e.url})}}o(uw,"completeLocalDevBrowserLogin");async function dw(e){let t=Zz.parse(e.body),r=await Jv({browserLoginStateToken:t.state}),n=await Ev({apiKey:t.apiKey,virtualServerId:r.virtualServerId}),a=await zp({browserLoginStateToken:t.state,principal:n});await $g({apiKey:t.apiKey,principal:n,virtualServerId:a.transaction.virtualServerId});let i=new URL("/oauth/setup",wt(e.request.url));return i.searchParams.set("state",a.csrfToken),{kind:"redirect",location:i,setCookie:await Ba({principal:n,requestUrl:e.request.url,virtualServerId:a.transaction.virtualServerId})}}o(dw,"completeApiKeyBrowserLogin");function t$(e){let t=e.method==="POST"?e.body:e.query;return Fz.parse(t)}o(t$,"readSetupContinueRequest");async function lw(e){let{state:t,decision:r}=t$({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,a=await $p({csrfToken:t,now:n}),i=await Yz(e.request,a.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await Xv({csrfToken:t,currentBrowserPrincipal:i,now:n})};let s=await Wv({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await Lp({transaction:s,requestUrl:e.request.url,returnTo:iw(t)});if(r==="approve"&&Gp(c)&&await Vv({csrfToken:t,currentBrowserPrincipal:i,now:n}),Gp(c)||r==="continue"&&s.setupApprovedAt===void 0){let d=await Bp({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:jp({state:t,virtualServerId:s.virtualServerId,upstreams:c,...d})}}return{kind:"redirect",location:await Yv({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(lw,"continueDownstreamAuthorizeSetup");me();import{createLocalJWKSet as r$,decodeJwt as n$,errors as Fa,jwtVerify as o$}from"jose";var a$=new Set(["authorization_code","refresh_token"]),i$="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",s$=1e4,c$=32*1024,u$=2,pw=u.object({client_id:u.string().min(1).optional(),client_secret:u.string().min(1).optional(),client_assertion_type:u.string().min(1).optional(),client_assertion:u.string().min(1).optional()}),d$=u.discriminatedUnion("grant_type",[pw.extend({grant_type:u.literal("authorization_code"),code:u.string().min(1),redirect_uri:u.string().min(1),code_verifier:si,resource:u.url().optional(),scope:u.literal(_e).optional()}),pw.extend({grant_type:u.literal("refresh_token"),refresh_token:u.string().min(1),resource:u.url().optional(),scope:u.literal(_e).optional()})]);function l$(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!a$.has(t)))throw new q("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(l$,"assertSupportedGrantType");var p$=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(),client_assertion_type:u.string().min(1).optional(),client_assertion:u.string().min(1).optional()}),m$=u.object({keys:u.array(u.record(u.string(),u.unknown())).min(1)}).passthrough();function mw(){return Te().gateway.accessTokenTtlSeconds}o(mw,"readAccessTokenTtlSeconds");function f$(){return Te().gateway.refreshTokenTtlSeconds}o(f$,"readRefreshTokenTtlSeconds");function h$(e,t){let r=mw(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:oe(Jt(e,a)),expiresIn:a}}o(h$,"calculateAccessTokenExpiresAt");function fw(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new q("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new q("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new q("invalid_client","Malformed HTTP Basic client authentication.")}}o(fw,"readBasicClientSecret");function hw(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new q("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=n$(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new q("invalid_client","Malformed private_key_jwt client assertion.")}throw new q("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new q("invalid_client","Client authentication or client_id is required.")}o(hw,"resolveAuthenticatedClientId");function g$(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new q("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(g$,"resolveClientSecretInput");function y$(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}o(y$,"hasClientAssertion");function S$(e){if(e.requestUrl===void 0)throw new q("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(e.pathname,e.requestUrl);return t.search="",t.hash="",t.toString()}o(S$,"buildEndpointAudience");function _$(e){return e instanceof Fa.JWTExpired?"expired":e instanceof Fa.JWTClaimValidationFailed?"claim":e instanceof Fa.JWSSignatureVerificationFailed?"signature":e instanceof Fa.JWKSNoMatchingKey?"jwks_no_match":e instanceof Fa.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(_$,"readJwtFailureKind");async function v$(e){let{response:t,json:r}=await $h(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:u$,maxResponseBytes:c$,timeoutMs:s$});if(!t.ok)throw new q("invalid_client","Client JWKS could not be fetched.");return m$.parse(r)}o(v$,"fetchClientJwks");async function w$(e){if(e.clientAssertionType!==i$||e.clientAssertion===void 0)throw new q("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=Ue.parse(e.clientId),r=await nc(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new q("invalid_client","Client is not registered for private_key_jwt authentication.");let n=r.metadata.jwks_uri;if(n===void 0)throw new q("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let a=S$({requestUrl:e.requestUrl,pathname:e.endpointPathname});try{let i=await v$({jwksUri:n,context:e.context});await o$(e.clientAssertion,r$(i),{issuer:t,subject:t,audience:a,currentDate:e.now})}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:_$(i)},"OAuth private_key_jwt client authentication failed"),new q("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}o(w$,"verifyPrivateKeyJwtClientAssertion");async function b$(e){let t=Ue.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 fe(e.clientSecret)}}o(b$,"buildRuntimeHttpClientAuth");async function gw(e){if(y$({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new q("invalid_request","Use only one client authentication method per request.");return w$(e)}let t=g$({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return b$({clientId:e.clientId,...t})}o(gw,"resolveRuntimeHttpClientAuth");async function yw(e){l$(e.body);let t=d$.parse(e.body),r=fw(e.authorizationHeader),n=hw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date,i=await gw({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/token",now:a,context:e.context});return R$({parsed:t,clientId:n,clientAuth:i,now:a,requestUrl:e.requestUrl,context:e.context})}o(yw,"exchangeDownstreamToken");async function R$(e){if(e.parsed.grant_type==="authorization_code"){Ga(e.parsed.redirect_uri),Va(e.parsed.scope),e.parsed.resource!==void 0&&So(e.requestUrl??e.parsed.resource,e.parsed.resource);let s=Yt(),c=Yt(),d=oe(Jt(e.now,f$())),p=h$(e.now,d),l=await W().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await fe(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await Gf(e.parsed.code_verifier),currentRefreshTokenHash:await fe(s),accessTokenHash:await fe(c),grantExpiresAt:d,accessTokenExpiresAt:p.expiresAt,now:oe(e.now)});if(l.kind==="invalid_client")throw new q("invalid_client","Client authentication failed.");if(l.kind==="resource_mismatch")throw new q("invalid_target","Token request resource must match the authorization code resource.");if(l.kind!=="exchanged")throw new q("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&K(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:c,token_type:"Bearer",expires_in:p.expiresIn,refresh_token:s,scope:l.grant.scope,resource:l.grant.resource}}Va(e.parsed.scope),e.parsed.resource!==void 0&&So(e.requestUrl??e.parsed.resource,e.parsed.resource);let t=Yt(),r=Yt(),n=oe(Jt(e.now,mw())),a=await W().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:await fe(e.parsed.refresh_token),nextRefreshTokenHash:await fe(t),accessTokenHash:await fe(r),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:n,now:oe(e.now)});if(a.kind==="invalid_client")throw new q("invalid_client","Client authentication failed.");if(a.kind==="resource_mismatch")throw new q("invalid_target","Token request resource must match the refresh token grant resource.");if(a.kind!=="rotated")throw new q("invalid_grant","Refresh token is invalid, expired, or revoked.");So(e.requestUrl??a.grant.resource,a.grant.resource);let i=a.accessToken.expiresAt;return e.context&&(K(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),K(e.context,{eventType:F.MCP_OAUTH_TOKEN_REFRESH_ROTATED,outcome:"success",attributes:{clientId:e.clientId}})),{access_token:r,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(i).getTime()-e.now.getTime())/1e3)),refresh_token:t,scope:a.grant.scope,resource:a.grant.resource}}o(R$,"exchangeDownstreamTokenWithRuntimeHttp");async function Sw(e){let t=p$.parse(e.body),r=fw(e.authorizationHeader),n=hw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date;if((await W().revokeOAuthToken({clientAuth:await gw({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/revoke",now:a,context:e.context}),tokenHash:await fe(t.token),now:oe(a)})).kind==="invalid_client")throw new q("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"),e.context&&K(e.context,{eventType:F.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}o(Sw,"revokeDownstreamToken");var C$=64*1024,I$=16*1024,P$="text/html; charset=utf-8";function x$(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(x$,"formDataToObject");async function A$(e){return Sv(e,{maxBytes:C$,label:"Request body"})}o(A$,"readJsonBody");async function oc(e){return x$(await Xs(e,{maxBytes:I$,label:"Request body"}))}o(oc,"readFormBody");async function ac(e,t,r){let n=Rt(r),a=r instanceof u.ZodError?_w(r):void 0,i={code:n??(r instanceof u.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(i.detail=a),Ct(e,t,i)}o(ac,"handleProblem");function Za(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(Za,"oauthErrorResponse");function k$(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(k$,"readOAuthProtocolHeaders");function T$(e,t){let r=ft("internal_server_error");return Za({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:k$(e,t)})}o(T$,"oauthProtocolErrorResponse");function E$(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(E$,"readZodOAuthErrorCode");function U$(e){let t={error:E$(e)},r=_w(e);return r!==void 0&&(t.errorDescription=r),Za(t)}o(U$,"oauthZodErrorResponse");function O$(e){let t=Rt(e);if(t===void 0)return;let r=ft(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:z$(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,Za(n)}o(O$,"oauthGatewayProblemResponse");function M$(){let t={error:"server_error",status:500,errorDescription:ft("internal_server_error").publicDetail};return Za(t)}o(M$,"oauthFallbackErrorResponse");function z$(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(z$,"readOAuthStatus");function _o(e,t={}){return e instanceof In?$$(e):e instanceof q?T$(e,t):e instanceof u.ZodError?U$(e):O$(e)??M$()}o(_o,"oauthProblemResponse");function Vt(e,t,r){let n={event:t},a=!1;if(r instanceof q)n.oauthError=r.errorCode,n.status=r.status,Xe(n,"error",r);else if(r instanceof In)n.oauthError=r.errorCode,Xe(n,"error",r);else if(r instanceof u.ZodError){n.code="invalid_request",Xe(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=Rt(r);if(i!==void 0){let s=ft(i);n.code=i,n.status=s.status,s.oauthError!==void 0&&(n.oauthError=s.oauthError),a=s.status>=500||s.oauthError==="server_error",Xe(n,"error",r)}else a=!0,Xe(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(Vt,"logUnexpectedOAuthHandlerError");function $$(e){let t;try{t=new URL(e.redirectUri)}catch{return Za({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($$,"downstreamAuthorizeRedirectErrorResponse");function _w(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(_w,"formatZodErrorDetail");function q$(e,t){let r={event:"browser_login_callback_failed",code:Rt(t)??"invalid_request"};Xe(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(q$,"logBrowserLoginCallbackFailure");function Fp(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(Fp,"redirectResultResponse");function ic(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":P$,"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 Fp(e)}o(ic,"authorizeResultResponse");async function vw(e,t){try{return Response.json($c(e.url))}catch(r){return Vt(t,"oauth_authorization_server_metadata_failed",r),ac(e,t,r)}}o(vw,"authorizationServerMetadataHandler");async function ww(e,t){try{let r=Ee.parse(e.params.virtualServerId),n=Kr(r);return Response.json(qm({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return Vt(t,"oauth_authorization_server_metadata_failed",r),ac(e,t,r)}}o(ww,"scopedAuthorizationServerMetadataHandler");async function bw(e,t){try{let r=await tw(await A$(e)),n=r,a=typeof n.client_id=="string"?n.client_id:void 0,i=typeof n.client_name=="string"?n.client_name:void 0,s=Array.isArray(n.redirect_uris)?n.redirect_uris.length:void 0,c=typeof n.token_endpoint_auth_method=="string"?n.token_endpoint_auth_method:void 0;return t.log.info({event:"oauth_dcr_client_registered",clientId:a,clientName:i,redirectUriCount:s,tokenEndpointAuthMethod:c},"OAuth Dynamic Client Registration completed"),K(t,{eventType:F.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:i,attributes:{clientId:a,redirectUriCount:s,tokenEndpointAuthMethod:c}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Vt(t,"oauth_register_failed",r),_o(r)}}o(bw,"registerHandler");async function Rw(e,t){try{return ic(await Vp(e,{context:t}))}catch(r){return Vt(t,"oauth_authorize_failed",r),_o(r,{includeInvalidClientChallenge:!1})}}o(Rw,"authorizeHandler");async function Cw(e,t){try{let r=Ee.parse(e.params.virtualServerId),n=Kr(r);return ic(await Vp(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return Vt(t,"oauth_authorize_scoped_failed",r),_o(r,{includeInvalidClientChallenge:!1})}}o(Cw,"scopedAuthorizeHandler");async function Iw(e,t){try{let r=await cw(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),ic(r)}catch(r){return q$(t,r),ac(e,t,r)}}o(Iw,"callbackHandler");async function Pw(e,t){try{return Fp(await uw(e))}catch(r){return Vt(t,"oauth_dev_login_failed",r),_o(r)}}o(Pw,"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?Pv(r,n):kp(r,400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):Fp(await dw({request:e,body:await oc(e)}))}catch(n){return Vt(t,"oauth_api_key_login_failed",n),kp(r)}}o(xw,"apiKeyLoginHandler");async function Aw(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 oc(e):void 0,context:t});return ic(r)}catch(r){return Vt(t,"oauth_setup_failed",r),ac(e,t,r)}}o(Aw,"setupHandler");async function kw(e,t){try{return Response.json(await yw({body:await oc(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Vt(t,"oauth_token_failed",r),_o(r)}}o(kw,"tokenHandler");async function Tw(e,t){try{return await Sw({body:await oc(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Vt(t,"oauth_revoke_failed",r),_o(r)}}o(Tw,"revokeHandler");var N$={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},Ew=new Ot("upstream-request");function D$(e){let t=Ew.get(e);if(!t)throw new te("Upstream request context has not been set");return t}o(D$,"readUpstreamRequestContext");function j$(e,t){return t.some(r=>r===e)}o(j$,"requestContextMatchesKind");function H$(e){return typeof e=="string"?[e]:e}o(H$,"toExpectedKinds");function Pn(e,t){Ew.set(e,t)}o(Pn,"setUpstreamRequestContext");function xn(e,t){let r=D$(e),n=H$(t);if(!j$(r.kind,n)){let a=N$[n[0]];throw new te(`${a} request context has not been set`)}return r}o(xn,"requireUpstreamRequestContext");function Uw(e){return le`<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
60
- configuration.</p><button class="button button--primary button--block form__submit" type="submit" >Connect</button></form>`}o(Uw,"renderAppPassword");function Ow(e){return le`<p data-gateway-error-code="${e.code}">${e.body}</p>`}o(Ow,"renderBrowserResult");var L$="text/html; charset=utf-8",B$="none";function Mw(e){let t=bn(e.host);return pr({title:e.title,iconHref:t,styles:lr,headerIcon:Rn({iconHref:t,fallbackIconHref:wn}),heading:e.title,subhead:"",body:Ow({body:e.body,code:e.code??B$}),footer:""})}o(Mw,"browserResultHtml");function zw(e,t=200){return new Response(Lr(e),{status:t,headers:{"content-type":L$,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(zw,"browserResultResponse");function sc(e){return zw(Mw(e))}o(sc,"browserConnectionSuccessResponse");function vo(e,t){let r=km(t);return zw(Mw({host:e,title:r.title,body:r.body,code:t}),400)}o(vo,"browserConnectionFailureResponse");function Zp(e){try{return new URL(e).host}catch{return""}}o(Zp,"safeHostFromUrl");var G$="text/html; charset=utf-8",V$=16*1024;function F$(e,t=200){return new Response(Lr(e),{status:t,headers:{"content-type":G$,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(F$,"htmlResponse");function Z$(e,t){return Response.redirect(new URL(t,e).toString(),302)}o(Z$,"safeRedirect");function K$(e){if(!e)throw new A({message:"App password capture requires a signed browser ticket.",extensionMembers:{[T]:"oauth_state_invalid"}});return e}o(K$,"requireBrowserTicket");function J$(e,t){return[e.ownerMode!=="user"||e.upstreamServerId!==t.upstreamServerId||t.virtualServerId!==void 0&&e.virtualServerId!==t.virtualServerId].every(n=>!n)}o(J$,"appPasswordTicketMatchesTarget");async function $w(e){let t=K$(e.browserTicket),r=await Li(t);if(!J$(r,e))throw new A({message:"App password capture ticket did not match the requested upstream flow.",extensionMembers:{[T]:"oauth_callback_mismatch"}});return{upstreamServerId:e.upstreamServerId,authProfileId:r.authProfileId,virtualServerId:r.virtualServerId,browserTicket:t,ticket:r}}o($w,"readAppPasswordTarget");function W$(e,t){let r=nd(e.upstreamServerId,e.authProfileId),n=`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`,a=bn(t),i=r.kind==="basic_auth_app_password"?le`<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">`:le`<label class="form__label" for="token">${r.label}</label><input class="form__input" id="token" name="token" type="password" required autocomplete="off">`;return F$(pr({title:"Connect upstream",iconHref:a,styles:lr,headerIcon:Rn({iconHref:a,fallbackIconHref:wn}),heading:"Connect upstream",subhead:le`<p class="card__subtitle">Enter the per-user credential for this approved upstream.</p>`,body:Uw({action:n,browserTicket:e.browserTicket,fields:i}),footer:""}))}o(W$,"renderCaptureForm");function cc(e,t){let r=e.get(t);if(typeof r!="string"||r.length===0)throw new A({message:`Missing form field: ${t}`,extensionMembers:{[T]:"invalid_request"}});return r}o(cc,"readRequiredFormValue");function Y$(e){return{upstreamServerId:e.upstreamServerId,...e.virtualServerId===void 0?{}:{virtualServerId:e.virtualServerId},...e.browserTicket===void 0?{}:{browserTicket:e.browserTicket}}}o(Y$,"readCaptureFormTargetInput");async function X$(e,t){return W$(await $w(Y$(e)),t)}o(X$,"handleCaptureFormRequest");async function Q$(e){let t=await Xs(e.request,{maxBytes:V$,label:"App password request body"});return{form:t,target:await $w({upstreamServerId:e.upstreamServerId,browserTicket:cc(t,"browserTicket")})}}o(Q$,"readSubmittedAppPasswordTarget");async function eq(e){let t=$n(e.target.ticket);if(await Bi(e.target.ticket),nd(e.target.upstreamServerId,e.target.authProfileId).kind==="bearer_token"){await Vi({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,token:cc(e.form,"token")});return}await ug({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,username:cc(e.form,"username"),appPassword:cc(e.form,"appPassword")})}o(eq,"saveSubmittedAppPasswordCredential");function tq(e,t){return t.ticket.returnTo?Z$(e,t.ticket.returnTo):sc({host:Zp(e),title:"Connection complete",body:"The upstream credential was saved. Return to your MCP client and retry the request."})}o(tq,"appPasswordSuccessResponse");async function rq(e){let t=await Q$({request:e.request,upstreamServerId:e.appPasswordRequest.upstreamServerId});return await eq(t),tq(e.request.url,t.target)}o(rq,"handleAppPasswordSubmission");function nq(){return new Response(null,{status:405,headers:{Allow:"GET, POST"}})}o(nq,"methodNotAllowedResponse");function oq(e,t,r,n){let a=n instanceof A?n.extensionMembers?.[T]:void 0;if(!oi(a)){if(a==="invalid_request")return pt.badRequest(e,t,{detail:n instanceof Error?n.message:void 0});throw n}return vo(r,a)}o(oq,"appPasswordFailureResponse");async function aq(e){let t=Zp(e.request.url);switch(e.request.method){case"GET":return X$(e.appPasswordRequest,t);case"POST":return rq(e);default:return nq()}}o(aq,"handleAppPasswordMethod");async function Kp(e,t){let r=xn(t,"app_password");try{return await aq({request:e,appPasswordRequest:r})}catch(n){return oq(e,t,Zp(e.url),n)}}o(Kp,"appPasswordHandler");var iq=["callback_authorization_code","callback_provider_error","callback_invalid"];function sq(e){return"cause"in e?e.cause:void 0}o(sq,"readErrorCause");function cq(e){return e.stack?.split(`
61
- `).slice(1,4).map(t=>t.trim()).join(" | ")}o(cq,"readFirstStackFrame");function qw(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=cq(r))}o(qw,"addErrorAttributes");function Nw(e){try{return new URL(e).host}catch{return""}}o(Nw,"safeHostFromUrl");function Jp(e){if(!(e instanceof A))return;let t=e.extensionMembers?.[T];return Wt(t)?t:void 0}o(Jp,"readRuntimeGatewayCode");function uq(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"),K(e,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),vo(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"),vo(r,"oauth_state_invalid");case"callback_authorization_code":return t}}o(uq,"requireAuthorizationCallbackRequest");function dq(e,t){K(e,{eventType:F.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(dq,"emitCallbackReceivedAnalyticsEvent");function lq(e,t){K(e,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(lq,"emitTokenExchangeSucceededAnalyticsEvent");function pq(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return sc({host:Nw(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(pq,"buildSuccessfulCallbackResponse");function mq(e){let t={detail:e instanceof Error?e.message:void 0};return qw(t,"error",e),e instanceof Error&&qw(t,"cause",sq(e)),t}o(mq,"buildTokenExchangeFailureAttributes");function fq(e){K(e.context,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Jp(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:mq(e.error)})}o(fq,"emitTokenExchangeFailedAnalyticsEvent");function hq(e,t){let r=Jp(t);return vo(e,oi(r)?r:"upstream_token_exchange_failed")}o(hq,"tokenExchangeFailureResponse");async function Wp(e,t){let r=xn(t,iq),n=Nw(e.url),a=uq(t,r,n);if(a instanceof Response)return a;dq(t,a);try{let i=await Ng({request:e,callbackRequest:a});return lq(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"),pq(e,i)}catch(i){let s={event:"upstream_oauth_token_exchange_failed",code:Jp(i)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return Xe(s,"error",i),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),fq({context:t,callbackRequest:a,error:i}),hq(n,i)}}o(Wp,"callbackHandler");function gq(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(gq,"clientMetadataProblemDetail");async function Dw(e,t){let r=xn(t,"connect"),n=await qg({request:e,connectRequest:r});if(K(t,{eventType:F.MCP_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 Pr({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(Dw,"connectHandler");async function jw(e,t){let r=xn(t,"client_metadata");try{let n=Rg(e.url),a=Cg(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){if(!(n instanceof $))throw n;let a=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:a},"Failed to serve OAuth client metadata document for upstream connection"),pt.notFound(e,t,{code:"not_found",detail:gq(n)})}}o(jw,"oauthClientMetadataHandler");function mr(e){if(typeof e=="string"&&e.length!==0)return e}o(mr,"readOptionalQueryString");function yq(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new te(`Validated path parameter ${t} is missing`);return r}o(yq,"requirePathString");function Hw(e){let t=mr(e);return t?Ee.parse(t):void 0}o(Hw,"readOptionalVirtualServerId");function Sq(e,t){let r=mr(e);return r?Ye.parse(r):Gn(t,"user-oauth")}o(Sq,"readOptionalAuthProfileId");function _q(e){let t=Hw(e);if(!t)throw new A({message:"virtualServerId query parameter is required.",extensionMembers:{[T]:"invalid_request"}});return t}o(_q,"readRequiredVirtualServerId");function vq(e){let t=mr(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(vq,"readOptionalBrowserTicket");function wq(e){let t=pi(mr(e));return t===void 0?{}:{returnTo:t}}o(wq,"readOptionalReturnTo");function bq(e){let t=Hw(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(bq,"readOptionalVirtualServerIdContext");function Rq(e){let t=mr(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o(Rq,"readOptionalProviderErrorDescription");function Cq(e){let t=$t(e.authMode);if(t.connectSupport!=="none")return e;throw new A({message:t.connectUnsupportedDetail??"This upstream does not support browser connection flows.",extensionMembers:{[T]:"invalid_request"}})}o(Cq,"requireConnectableRouteAuth");function Iq(e,t,r,n){let a=Ws(e,t);if(a.ownerMode==="none"||a.authMode==="shared-secret")throw new te("Static-secret upstreams do not support browser connection flows.");return{kind:"connect",...a,...n===void 0?{}:{returnTo:n},redirect:r}}o(Iq,"buildConnectContextForPrincipal");function Pq(e,t,r){let n=$n(t),a=$t(e.authMode);if(n.mode!==a.ownerMode)throw new A({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[T]:"oauth_callback_mismatch"}});return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:n,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}o(Pq,"buildConnectContextForTicket");async function xq(e,t){let r=Cq(hv(t,_q(e.query.virtualServerId))),n=e.query.redirect==="true",a=mr(e.query.browserTicket);if(e.user){if(a)throw new A({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[T]:"invalid_request"}});let s=On(e.user,e.url);return Iq(r,s,n,wq(e.query.returnTo).returnTo)}if(!a)throw new A({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[T]:"authentication_required"}});let i=await Li(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.virtualServerId!==r.virtualServerId)throw new A({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[T]:"oauth_callback_mismatch"}});return await Bi(i),Pq(r,i,n)}o(xq,"resolveConnectContext");async function Aq(e,t,r){let n=We.parse(yq(e,"connection"));switch(r){case"connect":Pn(t,await xq(e,n));return;case"app_password":Pn(t,{kind:"app_password",upstreamServerId:n,...bq(e),...vq(e)});return;case"callback":{let a=mr(e.query.error);if(a){Pn(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...Rq(e)});return}let i=mr(e.query.code),s=mr(e.query.state);if(i&&s){Pn(t,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:s});return}Pn(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":Pn(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:Sq(e.query.authProfileId,n)});return}}o(Aq,"resolveUpstreamRequestInbound");async function kq(e,t,r){try{await Aq(e,t,r);return}catch(n){let a=n instanceof A?n.extensionMembers?.[T]:void 0,i=n instanceof Error?n.message:void 0;switch(a){case"invalid_request":case"oauth_callback_mismatch":return pt.badRequest(e,t,{code:a,detail:i});case"authentication_required":return pt.unauthorized(e,t,{code:a,detail:i});default:throw n}}}o(kq,"applyUpstreamRequestContext");function Ka(e,t){return o(async(n,a)=>{let i=await kq(n,a,e);return i||t(n,a)},"wrapped")}o(Ka,"withUpstreamRequestContext");var Tq={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function Eq(){return new Response(null,{status:204,headers:Tq})}o(Eq,"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 Yp(e){return async(t,r)=>t.method==="OPTIONS"?Eq():Uq(await e(t,r))}o(Yp,"wrapWellKnownHandler");var Oq=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Yp(vw),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Yp(ww),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Yp(Nm),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:bw},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:Rw},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:Cw},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:Iw},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:Pw},{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:Aw},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:kw},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:Tw},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Ka("client_metadata",jw)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Ka("connect",Dw)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Ka("callback",Wp)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:Ka("app_password",Kp)}];function Lw(e){return e?.some(iu)??!1}o(Lw,"shouldRegisterMcpGatewayInternalRoutes");function Mq(e){let t=Yf(e.policies);if(!t){let r=[...au].map(n=>`\`${n}\``).join(", ");throw new $(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return Ch(Vu({routes:e.routes,policies:e.policies})),t.config}o(Mq,"initializeMcpGatewayState");function zq(e,t,r){return async(n,a)=>{let i=a;En(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(zq,"wrapInternalHandler");function Bw(e,t){let r,n=o(()=>(r===void 0&&(r=Mq(t)),r),"readOAuthConfig");for(let a of Oq){let i=zq(a.routeName,a.handler,n),s=o((c,d)=>i(c,d),"handler");e.addPluginRoute({path:a.path,methods:a.methods,handler:s,processors:[gc],corsPolicy:a.corsPolicy??"none"})}}o(Bw,"registerMcpGatewayInternalRoutes");function Gw(e){Rh(e)}o(Gw,"configureLazyMcpGatewayState");var Xp=class extends cm{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!Lw(r.policies))return;let n={routes:r.routes,policies:r.policies};Gw(n),Bw(t.router,n)}};export{ru as McpAuth0OAuthInboundPolicy,Xp as McpGatewayPlugin,nu as McpOAuthInboundPolicy,xp as McpUpstreamConnectionInboundPolicy,IM as McpVirtualServerHandler,eA as mcpUpstreamHandler};
58
+ </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(Mt,"renderShell");var Ap="zuplo.com";function Pv(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(Pv,"s2FaviconHref");function FM(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(FM,"strictFaviconHref");var yr=Pv(Ap);function Sr(e){let t=e.toLowerCase();return t===Ap||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Pv(Ap):FM(e)}o(Sr,"resolveIconHref");function _r(e){return se`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}o(_r,"renderShellIcon");var ZM="text/html; charset=utf-8";function Yt(e){try{return new URL(e).host}catch{return""}}o(Yt,"safeHostFromUrl");function Rt(e){let t=Sr(e.host),r=KM(e.kind??"authorization_failed");return new Response(Wt(Mt({title:e.title??r.title,iconHref:t,styles:Ot,headerIcon:_r({iconHref:t,fallbackIconHref:yr}),heading:e.title??r.title,subhead:"",body:Iv({code:e.code??"unknown",detail:e.detail,guidance:se`<p class="card__description">${r.guidance}</p>`,action:JM(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":ZM,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(Rt,"browserErrorPageResponse");function KM(e){switch(e){case"session_expired":return{title:"Authorization expired",guidance:"Return to your MCP client and reconnect. Expired authorization requests cannot be resumed."};case"access_denied":return{title:"Authorization canceled",guidance:"Return to your MCP client to retry if you want to grant access."};case"configuration_error":return{title:"Configuration needs attention",guidance:"Contact your workspace admin with this error code. The gateway or upstream configuration must be fixed before retrying."};case"connection_failed":return{title:"Connection failed",guidance:"Return to your MCP client and reconnect this upstream. If this keeps happening, contact your gateway administrator with this error code."};case"invalid_request":return{title:"Authorization request invalid",guidance:"Return to your MCP client and try connecting again. If this keeps happening, the client request may need to be fixed."};case"admin_required":return{title:"Admin setup required",guidance:"Contact your workspace admin with this error code. This connection cannot be completed until setup is finished."};case"internal_error":return{title:"Gateway error",guidance:"Try again later from your MCP client. If this keeps happening, contact your gateway administrator with this error code."};case"authorization_failed":return{title:"Authorization failed",guidance:"Return to your MCP client and start authorization again. If this keeps happening, contact your gateway administrator with this error code."}}}o(KM,"readBrowserErrorPagePresentation");function JM(e){return e===void 0?xn:se`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}o(JM,"renderAction");var xv="application/json",WM="application/x-www-form-urlencoded";function Qs(e,t){return new E({message:e,extensionMembers:{[T]:"invalid_request"}},t===void 0?void 0:{cause:t})}o(Qs,"invalidRequestError");function YM(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(YM,"normalizeContentType");function XM(e,t){return e===t?!0:t===xv&&e.endsWith("+json")}o(XM,"contentTypeMatches");function QM(e,t){if(!t||t.length===0)return;let r=YM(e.headers.get("content-type"));if(!t.some(n=>XM(r,n)))throw Qs(`Request body must be ${t.join(" or ")}.`)}o(QM,"assertExpectedContentType");function ez(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 Qs(`${r} exceeded the maximum allowed size.`)}o(ez,"assertContentLengthWithinLimit");async function kv(e,t){let r=t.label??"Request body";QM(e,t.expectedContentTypes),ez(e,t.maxBytes,r);let n=await ji(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>Qs(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(kv,"readBoundedTextBody");async function Av(e,t){let r=await kv(e,{...t,expectedContentTypes:[xv]});try{return JSON.parse(r)}catch(n){throw Qs("Request body must be valid JSON.",n)}}o(Av,"readBoundedJsonBody");async function ec(e,t){let r=await kv(e,{...t,expectedContentTypes:[WM]});return new URLSearchParams(r)}o(ec,"readBoundedFormUrlEncodedBody");function Tv(e){return se`<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(Tv,"renderActions");var vJ=gr('<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 Ev(){return se`<p>The API key could not be verified. Start the authorization flow again to try
59
+ once more.</p>`}o(Ev,"renderApiKeyLoginFailure");function Uv(e){return se`<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(Uv,"renderApiKeyLoginForm");var wJ=gr('<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>'),bJ=gr('<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 RJ=gr('<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 tz="text/html; charset=utf-8";function Ov(e,t=200){return new Response(Wt(e),{status:t,headers:{"content-type":tz,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(Ov,"apiKeyLoginHtmlResponse");function Tp(e,t=401){let r=Sr(e);return Ov(Mt({title:"Sign-in failed",iconHref:r,styles:Ot,headerIcon:_r({iconHref:r,fallbackIconHref:yr}),heading:"Sign-in failed",subhead:"",body:Ev(),footer:""}),t)}o(Tp,"apiKeyLoginFailureResponse");function Mv(e,t){let r=Sr(e);return Ov(Mt({title:"Sign in",iconHref:r,styles:Ot,headerIcon:_r({iconHref:r,fallbackIconHref:yr}),heading:"Sign in",subhead:se`<p class="card__subtitle">Enter your API key to continue.</p>`,body:Uv({state:t}),footer:""}))}o(Mv,"renderApiKeyLoginForm");de();de();import{errors as Lv,jwtVerify as Bv,SignJWT as Gv}from"jose";de();import{errors as mz,jwtVerify as fz,SignJWT as hz}from"jose";function Jr(e){let t=Te().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw D("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}o(Jr,"requireBrowserLoginField");de();import{createRemoteJWKSet as nz,errors as Va,jwtVerify as oz}from"jose";var az=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()}),iz=u.object({error:u.string().min(1).optional(),error_description:u.string().min(1).optional(),error_uri:u.string().min(1).optional()});function sz(e){let t=iz.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(sz,"readIdpErrorFields");function cz(e){return e instanceof Va.JWTExpired?"expired":e instanceof Va.JWTClaimValidationFailed?"claim":e instanceof Va.JWSSignatureVerificationFailed?"signature":e instanceof Va.JWKSNoMatchingKey?"jwks_no_match":e instanceof Va.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(cz,"readJwtFailureKind");var uz=u.object({sub:ve,nonce:u.string().min(1)}).catchall(u.unknown()),Ep;function dz(e){return e instanceof Error&&"cause"in e?e.cause:e}o(dz,"readErrorCause");function lz(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(lz,"readRuntimeGatewayCode");function pz(){if(!Ep){let e=Te();Ep=nz(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Ep}o(pz,"readFederatedJwks");async function zv(e){let t=Te(),r=Jr("tokenUrl"),n=Jr("clientId"),a=Jr("clientSecret"),i=new URL("/oauth/callback",Pt(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 jh(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=sz(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:St(r),idpStatus:c.status,...h},"Federated browser login token exchange returned non-2xx from the identity provider"),D({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=az.parse(d),l;try{({payload:l}=await oz(p.id_token,pz(),{issuer:t.oidc.issuer,audience:n}))}catch(h){let g={};throw Xe(g,"error",h),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:cz(h),idpHost:St(r),expectedIssuer:t.oidc.issuer,...g},"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:St(r),nonceMissingFromIdToken:l.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),D("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let m=uz.parse(l);return jn({sub:m.sub,data:m},e.requestUrl)}catch(c){let d=dt(c)??lz(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:D("browser_login_verification_failed","Federated browser login callback could not be verified.",dz(c))}}o(zv,"exchangeFederatedAuthorizationCode");var Op="zuplo_mcp_session",gz=u.object({purpose:u.literal("gateway_browser_session"),sub:ve,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 yz(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(yz,"parseCookieHeader");async function $v(){return Ht({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Or(e,"browser-session"),"derive")})}o($v,"getBrowserSessionKey");function Up(e){let t=new URL(le(e)),r=[`${Op}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(Up,"buildBrowserSessionEvictionCookie");function Sz(e){let t=new URL(le(e.requestUrl)),r=[`${Op}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(Sz,"serializeSessionCookie");function qv(e={}){return new URL(Jr("url")).origin}o(qv,"readBrowserLoginOrigin");function Mp(){return Te().browserLogin.stateTtlSeconds}o(Mp,"readBrowserLoginStateTtlSeconds");function Nv(e){if(!e.user)throw D("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return jn(e.user,e.url)}o(Nv,"resolveCurrentRequestPrincipal");async function tc(e,t={}){let r=yz(e.headers.get("cookie")).get(Op);if(!r)return{};try{let{payload:n}=await fz(r,await $v(),{algorithms:[mt],issuer:nt,audience:pt}),a=gz.parse(n);if(a.browserLoginOrigin!==qv(t))return{evictCookie:Up(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 mz.JWTExpired?{evictCookie:Up(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:Up(e.url)})}}o(tc,"readBrowserSession");async function Fa(e){let t=Te().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:qv({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new hz(r).setProtectedHeader({alg:mt,typ:"JWT"}).setIssuer(nt).setAudience(pt).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await $v());return Sz({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o(Fa,"createBrowserSessionCookie");async function Dv(e){throw D("forbidden","API-key browser login is not supported in this gateway.")}o(Dv,"resolveApiKeyBrowserLoginPrincipal");async function jv(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await tc(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 D("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");return zv({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(jv,"resolveBrowserLoginCallbackPrincipal");function Hv(e){let t=Te().browserLogin,r=new URL(Jr("url")),n=new URL("/oauth/callback",Pt(e.requestUrl));return nf(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",Jr("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(Hv,"buildBrowserLoginUrl");var _z={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},$=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=_z[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var vz=5*60,wz=u.object({purpose:u.literal("gateway_browser_login"),transactionId:lt,stateId:Ci,exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),bz=u.object({purpose:u.literal("gateway_authorization_setup"),transactionId:lt,stateId:Ci,exp:u.number().int().positive(),iat:u.number().int().positive().optional()});async function Vv(){return Ht({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Or(e,"browser-login"),"derive")})}o(Vv,"getBrowserLoginKey");async function Fv(){return Ht({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Or(e,"authorization-csrf"),"derive")})}o(Fv,"getCsrfKey");function Zv(e){return{now:e.now??new Date,ttlSeconds:Mp()}}o(Zv,"readPendingTransactionDependencies");function Rz(e,t){return e.subjectId===t.subjectId}o(Rz,"principalsMatch");function Kv(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(Kv,"toPendingPrincipal");function Jv(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:oe(e.now),expiresAt:oe(or(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 D("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:Kv(e.principal)}}o(Jv,"createTransactionRecord");async function Wv(e){let{id:t,...r}=e.record,n=await Y().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw D("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new $("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new $("invalid_request","redirect_uri is not registered for the client.")}}o(Wv,"startPendingTransaction");async function Cz(e){return new Gv({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:mt,typ:"JWT"}).setIssuer(nt).setAudience(pt).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Vv())}o(Cz,"signBrowserLoginState");async function Yv(e){return new Gv({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:mu()}).setProtectedHeader({alg:mt,typ:"JWT"}).setIssuer(nt).setAudience(pt).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Fv())}o(Yv,"signCsrfToken");async function rc(e){try{let{payload:t}=await Bv(e,await Vv(),{algorithms:[mt],issuer:nt,audience:pt}),r=wz.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof Lv.JWTExpired?D("oauth_state_expired","Browser login state has expired.",t):D("oauth_state_invalid","Browser login state could not be verified.",t)}}o(rc,"verifyBrowserLoginStateToken");async function nc(e){try{let{payload:t}=await Bv(e,await Fv(),{algorithms:[mt],issuer:nt,audience:pt});return{transactionId:bz.parse(t).transactionId}}catch(t){throw t instanceof Lv.JWTExpired?D("oauth_state_expired","Authorization setup state has expired.",t):D("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(nc,"verifyCsrfToken");function oc(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(oc,"pendingStateErrorCode");function Xv(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(Xv,"toPendingAuthorizationGetResult");function Iz(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(Iz,"toPendingAuthorizationAdvanceResult");function zp(e){return e==="principal_mismatch"?"oauth_callback_mismatch":oc(e==="consumed_already"?"consumed_already":e)}o(zp,"setupDecisionErrorCode");async function Qv(e){let t=e.now??new Date,r=await nc(e.csrfToken),n=await Y().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await fe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:oe(t)});if(n.kind!=="marked")throw D(zp(n.kind),"Authorization setup state is invalid, expired, or already used.");return ew({kind:"available",record:n.transaction})}o(Qv,"markSetupApproved");function ew(e){if(e.kind!=="available")throw D(oc(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw D("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(ew,"requireAwaitingSetup");function Pz(e){if(e.kind!=="available")throw D(oc(e.kind),"Browser login state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_login")throw D("oauth_state_invalid","Browser login state is not in the login phase.");return e.record}o(Pz,"requireAwaitingLogin");function xz(e){if(!Rz(e.currentBrowserPrincipal,e.transaction.principal))throw D("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(xz,"requireCurrentPrincipalMatches");async function tw(e){let t=e.now??new Date,r=Mp(),n=pu(),a=mu(),i=await Cz({transactionId:n,stateId:a,ttlSeconds:r}),s=Jv({id:n,transaction:e.transaction,currentStateHash:await fe(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw D("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await Wv({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw D("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:i,browserLoginUrl:Hv({state:i,nonce:a,virtualServerId:s.virtualServerId,requestUrl:e.requestUrl})}}o(tw,"startAwaitingLogin");async function rw(e){let{now:t,ttlSeconds:r}=Zv(e),n=pu(),a=await Yv({transactionId:n,ttlSeconds:r}),i=Jv({id:n,transaction:e.transaction,currentStateHash:await fe(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw D("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await Wv({record:i,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw D("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:a}}o(rw,"startAwaitingSetup");async function $p(e){let{now:t,ttlSeconds:r}=Zv(e),n=await rc(e.browserLoginStateToken),a=await Yv({transactionId:n.transactionId,ttlSeconds:r}),i=Iz(await Y().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await fe(e.browserLoginStateToken),nextStateHash:await fe(a),nextPhase:"awaiting_setup",principal:Kv(e.principal),now:oe(t)}));if(i.kind!=="advanced")throw D(oc(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw D("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:a}}o($p,"completeLogin");async function nw(e){let t=e.now??new Date,r=await rc(e.browserLoginStateToken);return Pz(Xv(await Y().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await fe(e.browserLoginStateToken),now:oe(t)})))}o(nw,"getAwaitingLogin");async function ow(e){let t=await qp(e);return xz({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(ow,"getSetup");async function qp(e){let t=e.now??new Date,r=await nc(e.csrfToken);return ew(Xv(await Y().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await fe(e.csrfToken),now:oe(t)})))}o(qp,"getSetupTransaction");async function kz(e){let t=await nc(e.csrfToken),r=ir(),n=oe(or(e.now,vz)),a=await Y().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await fe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await fe(r),authorizationCodeExpiresAt:n,grantId:tf(),now:oe(e.now)});if(a.kind!=="approved")throw D(a.kind==="cancelled"?"oauth_state_invalid":zp(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(kz,"createAuthorizationCodeRedirectWithDecision");async function Az(e){let t=await nc(e.csrfToken),r=await Y().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await fe(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:oe(e.now)});if(r.kind!=="cancelled")throw D(r.kind==="approved"?"oauth_state_invalid":zp(r.kind),"Authorization setup state is invalid, expired, or already used.");return Tz({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}o(Az,"createCancelRedirectWithDecision");function Tz(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(Tz,"buildClientCancelRedirect");async function aw(e){let t=e.now??new Date;return kz({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(aw,"approve");async function iw(e){let t=e.now??new Date;return Az({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(iw,"cancel");de();var Ez=1e4,Uz=5*1024,Oz=2,Mz=90*24*60*60,Np=["authorization_code","refresh_token"],Dp=["code"],zz=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(Np)).min(1).max(2).optional(),response_types:u.array(u.enum(Dp)).min(1).max(1).optional(),scope:u.literal(_e).optional(),token_endpoint_auth_method:Xm.default("none")});function $z(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&ke(t))&&t.pathname!=="/"}catch{return!1}}o($z,"isCimdClientIdCandidate");function bo(e,t="invalid_request",r="authorize"){if(qz(e))throw new $(t,"redirect_uris must not include raw whitespace or control characters.");let n;try{n=new URL(e)}catch{throw new $(t,"redirect_uris must be absolute URIs.")}if(n.hash||n.username||n.password)throw new $(t,"redirect_uris must not include credentials or fragments.");let a={source:r},i=Jm({url:n,context:a});if(i.kind!=="rejected"){i.mode!=="strict"&&void 0;return}throw new $(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}o(bo,"assertValidRedirectUri");function qz(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(qz,"hasForbiddenRawRedirectUriCharacter");async function Nz(e){let{response:t,json:r}=await Hh(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:Oz,maxResponseBytes:Uz,timeoutMs:Ez});if(!t.ok)throw D("invalid_request","CIMD metadata could not be fetched.");let n=ef.parse(r);for(let a of n.redirect_uris)bo(a,"invalid_request","cimd");if(n.client_id!==e.clientId)throw D("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return n}o(Nz,"fetchCimdMetadata");async function Dz(e){let t=Di(e),r=await Nz({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(Dz,"resolveCimdClient");async function ac(e,t){let r=Oe.parse(e);if($z(r)){if(!Te().gateway.cimdEnabled)throw new $("invalid_client","OAuth client is not registered.");try{return await Dz(r)}catch{throw new $("invalid_client","OAuth client is not registered.")}}let n=await Y().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 $("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(ac,"resolveClient");function sw(e,t){if(!e.metadata.redirect_uris.some(r=>rf(r,t)))throw D("invalid_request","redirect_uri is not registered for the client.")}o(sw,"assertRedirectRegistered");function jz(e){let t=cw(e.grant_types),r=e.response_types??[...Dp];if(!Hz(t))throw new $("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!Lz(r))throw new $("invalid_client_metadata","response_types must be code.");if(!Bz(e.scope))throw new $("invalid_client_metadata",`Only the ${_e} scope is supported.`)}o(jz,"assertSupportedDcrRequest");function cw(e){return e===void 0?[...Np]:Array.from(new Set(e))}o(cw,"normalizeGrantTypes");function Hz(e){return e.length===0?!1:e.every(t=>Np.includes(t))}o(Hz,"isSupportedGrantTypes");function Lz(e){return e.length===Dp.length&&e[0]==="code"}o(Lz,"isSupportedResponseTypes");function Bz(e){return e===void 0||e===_e}o(Bz,"isSupportedDcrScope");function Za(e){if(e===void 0||e===_e)return _e;throw new $("invalid_request",`Only the ${_e} scope is supported.`)}o(Za,"assertSupportedOAuthScope");function Ro(e,t){let r;try{r=new URL(t)}catch{throw new $("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new $("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!ke(r))throw new $("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=le(e),a=Eh(),i=a?[...a.byVirtualServerId.values()].find(s=>new URL(s.routePath,n).toString()===t):void 0;if(!i)throw new $("invalid_target","resource must match a published virtual MCP server.");return i}o(Ro,"resolveResource");async function uw(e){let t;try{t=zz.parse(e)}catch(l){if(l instanceof u.ZodError){let m=l.issues.some(h=>h.path[0]==="redirect_uris");throw new $(m?"invalid_redirect_uri":"invalid_client_metadata",l.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:l})}throw l}jz(t);for(let l of t.redirect_uris)bo(l,"invalid_redirect_uri","dcr");let r=new Date,n=Oe.parse(`dcr:${crypto.randomUUID()}`),a=or(r,Mz),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:cw(t.grant_types),response_types:["code"],scope:_e,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:oe(r),clientExpiresAt:oe(a)};if(t.token_endpoint_auth_method!=="none"){let l=ir();d.hashedClientSecret=await fe(l),d.clientSecretExpiresAt=oe(a),c.client_secret=l,c.client_secret_expires_at=s,c.client_secret_issued_at=i}if((await Y().registerClient(d)).kind==="already_exists")throw D("invalid_request","OAuth client is already registered.");return c}o(uw,"registerDownstreamClient");var Gz="data:,",dw=se`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);"`,lw=se`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 Vz(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(Vz,"safeGatewayConnectHref");function Fz(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(Fz,"deriveMode");function Zz(e){return Tv({state:e.state,submitOnceAttrs:dw,authorizeAttrs:xn})}o(Zz,"renderActions");function jp(e,t,r){for(let n of e){if(n.ownerMode!=="user"||n.status!==r)continue;let a=Vz(n.connectUrl,t);if(a)return a}}o(jp,"firstUserConnectHref");function Kz(e){let t=e.connectHref?se`<a class="button button--primary" href="${e.connectHref}" ${lw}>Connect</a>`:se`<button class="button button--primary" type="button" disabled aria-disabled="true">Connect</button>`;return se`<form class="actions" method="post" action="/oauth/setup" ${dw}><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(Kz,"renderSetupActions");function Jz(e){return e?se`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${lw}>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>`:xn}o(Jz,"renderReconnectAction");function Hp(e){let t=Fz(e.upstreams),r=jp(e.upstreams,e.gatewayOrigin,"not_connected"),n=jp(e.upstreams,e.gatewayOrigin,"reconsent_required"),a=jp(e.upstreams,e.gatewayOrigin,"active"),i=t==="setup"?r??n:void 0,s=se`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.virtualServerDisplayName}</strong>' on your behalf?</p>`,c=t==="setup"?se`<footer class="card__footer">${Kz({state:e.state,connectHref:i})}</footer>`:se`<footer class="card__footer">${Jz(a)}${Zz({state:e.state})}</footer>`;return Wt(Mt({title:`Authorize access \xB7 ${e.virtualServerDisplayName}`,iconHref:Gz,styles:Ot,headerIcon:xn,heading:"MCP Gateway",subhead:xn,body:s,footer:c}))}o(Hp,"renderConsentPage");function Wz(e){try{return new URL(e).host}catch{return}}o(Wz,"safeUrlHost");function Yz(e){if(e.mode==="user-oauth"||e.mode==="shared-oauth")return e.oauth.scopes}o(Yz,"readOAuthScopes");function Lp(e){return e!==void 0&&e.length>0}o(Lp,"hasItems");function Xz(e){let t=e.registeredConnection.config.serverInfo?.icons;if(Lp(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&Lp(r)?r:void 0}o(Xz,"readServerIcons");async function Qz(e){if(!(e.returnTo===void 0||!e.isUserOwned))return Qu({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(Qz,"readConnectUrl");function kn(e,t){return t===void 0?{}:{[e]:t}}o(kn,"optionalRequirementField");function e$(e){return e.isUserOwned?Sf(e.connection):{connected:!0,status:"active"}}o(e$,"readSetupConnectionStatus");function t$(e){let t=Yz(e);return Lp(t)?t:void 0}o(t$,"readScopesRequested");function r$(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o(r$,"readUpdatedAt");function n$(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($i),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(qi),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map(Ni)}}o(n$,"readVirtualServerCapabilities");async function o$(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:i}=e.registeredConnection,s=Li(r),c=s==="user",d=e$({connection:e.connection,isUserOwned:c}),p=await Qz({...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:n$({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...kn("description",n.description),...kn("transportHost",Wz(n.transport.baseUrl)),...kn("scopesRequested",t$(t)),...kn("serverIcons",Xz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...kn("connectUrl",p),...kn("updatedAt",r$({connectionStatus:d,isUserOwned:c})),...kn("expiresAt",e.connection?.expiresAt)}}o(o$,"buildSetupRequirement");function pw(e){let t=rt().byVirtualServerId.get(e);if(!t)throw D("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(pw,"requireVirtualServer");async function Bp(e){let t=pw(e.transaction.virtualServerId),r=Tr(e.transaction.principal.subjectId),n=[],a=new Map;for(let c of t.connections)Li(c.authMode)==="user"&&(a.set(c,n.length),n.push({owner:r,upstreamServerId:c.upstreamServerId,authProfileId:c.authProfileId}));let i=await Y().batchGetUpstreamConnections(n),s=[];for(let c of t.connections){let d=Li(c.authMode)==="user",p=a.get(c);s.push(await o$({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(Bp,"requirementsForSetup");function a$(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(a$,"readVirtualServerDisplayName");async function Gp(e){let t=pw(e.transaction.virtualServerId),r=a$({virtualServer:t}),n=await Y().readClient({clientId:e.transaction.clientId}),a=n.kind==="found"?n.client:void 0,i={gatewayOrigin:le(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(Gp,"consentContext");function Vp(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(Vp,"hasUnresolvedUserUpstream");var i$=["mcp_user"],s$="dev-browser-user",c$=["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(" "),u$=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:bi,state:u.string().min(1).optional(),scope:u.literal(_e).default(_e)}),d$=u.enum(["continue","approve","cancel"]).default("continue"),l$=u.object({state:u.string().min(1),decision:d$}),p$=u.object({state:u.string().min(1),apiKey:u.string().min(1)}),Wr=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 mw(e){return typeof e=="string"&&e.length>0?e:void 0}o(mw,"readQueryString");function m$(e){let t=Array.from(rt().byVirtualServerId.values());if(t.length!==1)return;let r=t[0];if(r!==void 0)return Ar(r.virtualServerId,e.url)}o(m$,"inferSingleVirtualServerResource");function f$(e,t){let r=mw(e.query.resource);if(t===void 0){if(r!==void 0)return r;let a=m$(e);if(a!==void 0)return a;throw new $("invalid_target",c$)}let n=Ar(t,e.url);if(r===void 0||r===n)return n;throw new $("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(f$,"requireAuthorizeResource");async function h$(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await tc(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let i=Nv(e);return{principal:i,setCookie:await Fa({principal:i,requestUrl:e.url,virtualServerId:t})}}o(h$,"resolveBrowserPrincipal");async function g$(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await tc(e,n);if(!a.principal)throw D("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(g$,"requireSetupPrincipal");function fw(e){return`/oauth/setup?state=${encodeURIComponent(e)}`}o(fw,"buildSetupReturnTo");async function hw(e){let t=await Bp({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:fw(e.csrfToken)}),r=await Gp({transaction:e.transaction,requestUrl:e.requestUrl}),n={kind:"setup_page",html:Hp({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(hw,"renderSetup");function y$(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(y$,"toAuthorizationTransactionClient");async function Fp(e,t={}){let r=u$.parse({...e.query,resource:f$(e,t.virtualServerId),state:mw(e.query.state)}),n=Za(r.scope);bo(r.redirect_uri,"invalid_request","authorize");let a=new Date,i=Oe.parse(r.client_id),s=await ac(r.client_id,a);sw(s,r.redirect_uri);try{let c=Ro(e.url,r.resource),d=y$(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"),t.context&&J(t.context,{eventType:F.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:c.virtualServerId,attributes:{clientId:i,scope:n,responseType:r.response_type}});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 h$(e,c.virtualServerId,t.context);if(!l){let g=await tw({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 S={kind:"redirect",location:g.browserLoginUrl};return m!==void 0&&(S.setCookie=m),S}let h=await rw({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"),t.context&&J(t.context,{eventType:F.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.virtualServerId,attributes:{clientId:i,scope:n,responseType:r.response_type,subjectId:l.subjectId}}),hw({transaction:h.transaction,csrfToken:h.csrfToken,requestUrl:e.url,setCookie:m})}catch(c){throw S$({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}o(Fp,"authorizeDownstreamClient");function S$(e){if(e.cause instanceof Wr)return e.cause;let t=_$(e.cause);return t?new Wr({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(S$,"toDownstreamAuthorizeRedirectError");function _$(e){if(e instanceof $)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(_$,"mapToOAuthRedirectError");async function gw(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"),D("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"),D("oauth_state_invalid","Browser login callback is missing state.");let a=await rc(n),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let s=await jv(i),c=await $p({browserLoginStateToken:n,principal:s}),d=await hw({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return d.setCookie=await Fa({principal:s,requestUrl:e.url,virtualServerId:c.transaction.virtualServerId}),d}o(gw,"completeBrowserLoginCallback");async function yw(e){let t=Te(),r=new URL(e.url);if(!ke(r))throw D("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 D("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",le(e.url)),i=new URL(le(e.url)).origin;if(a.origin!==i||a.pathname!=="/oauth/callback")throw D("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");a.searchParams.set("state",n);let s={subjectId:ve.parse(s$),roles:i$};return{kind:"redirect",location:a,setCookie:await Fa({principal:s,requestUrl:e.url})}}o(yw,"completeLocalDevBrowserLogin");async function Sw(e){let t=p$.parse(e.body),r=await nw({browserLoginStateToken:t.state}),n=await Dv({apiKey:t.apiKey,virtualServerId:r.virtualServerId}),a=await $p({browserLoginStateToken:t.state,principal:n});await Lg({apiKey:t.apiKey,principal:n,virtualServerId:a.transaction.virtualServerId});let i=new URL("/oauth/setup",Pt(e.request.url));return i.searchParams.set("state",a.csrfToken),{kind:"redirect",location:i,setCookie:await Fa({principal:n,requestUrl:e.request.url,virtualServerId:a.transaction.virtualServerId})}}o(Sw,"completeApiKeyBrowserLogin");function v$(e){let t=e.method==="POST"?e.body:e.query;return l$.parse(t)}o(v$,"readSetupContinueRequest");async function _w(e){let{state:t,decision:r}=v$({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,a=await qp({csrfToken:t,now:n}),i=await g$(e.request,a.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await iw({csrfToken:t,currentBrowserPrincipal:i,now:n})};let s=await ow({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await Bp({transaction:s,requestUrl:e.request.url,returnTo:fw(t)});if(r==="approve"&&Vp(c)&&await Qv({csrfToken:t,currentBrowserPrincipal:i,now:n}),Vp(c)){let d=await Gp({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:Hp({state:t,virtualServerId:s.virtualServerId,upstreams:c,...d})}}return{kind:"redirect",location:await aw({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(_w,"continueDownstreamAuthorizeSetup");de();import{createLocalJWKSet as w$,decodeJwt as b$,errors as Ka,jwtVerify as R$}from"jose";var C$=new Set(["authorization_code","refresh_token"]),I$="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",P$=1e4,x$=32*1024,k$=2,vw=u.object({client_id:u.string().min(1).optional(),client_secret:u.string().min(1).optional(),client_assertion_type:u.string().min(1).optional(),client_assertion:u.string().min(1).optional()}),A$=u.discriminatedUnion("grant_type",[vw.extend({grant_type:u.literal("authorization_code"),code:u.string().min(1),redirect_uri:u.string().min(1),code_verifier:Ri,resource:u.url().optional(),scope:u.literal(_e).optional()}),vw.extend({grant_type:u.literal("refresh_token"),refresh_token:u.string().min(1),resource:u.url().optional(),scope:u.literal(_e).optional()})]);function T$(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!C$.has(t)))throw new $("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(T$,"assertSupportedGrantType");var E$=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(),client_assertion_type:u.string().min(1).optional(),client_assertion:u.string().min(1).optional()}),U$=u.object({keys:u.array(u.record(u.string(),u.unknown())).min(1)}).passthrough();function ww(){return Te().gateway.accessTokenTtlSeconds}o(ww,"readAccessTokenTtlSeconds");function O$(){return Te().gateway.refreshTokenTtlSeconds}o(O$,"readRefreshTokenTtlSeconds");function M$(e,t){let r=ww(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:oe(or(e,a)),expiresIn:a}}o(M$,"calculateAccessTokenExpiresAt");function bw(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new $("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new $("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new $("invalid_client","Malformed HTTP Basic client authentication.")}}o(bw,"readBasicClientSecret");function Rw(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new $("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=b$(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new $("invalid_client","Malformed private_key_jwt client assertion.")}throw new $("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new $("invalid_client","Client authentication or client_id is required.")}o(Rw,"resolveAuthenticatedClientId");function z$(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new $("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(z$,"resolveClientSecretInput");function $$(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}o($$,"hasClientAssertion");function q$(e){if(e.requestUrl===void 0)throw new $("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(e.pathname,e.requestUrl);return t.search="",t.hash="",t.toString()}o(q$,"buildEndpointAudience");function N$(e){return e instanceof Ka.JWTExpired?"expired":e instanceof Ka.JWTClaimValidationFailed?"claim":e instanceof Ka.JWSSignatureVerificationFailed?"signature":e instanceof Ka.JWKSNoMatchingKey?"jwks_no_match":e instanceof Ka.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(N$,"readJwtFailureKind");async function D$(e){let{response:t,json:r}=await Lh(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:k$,maxResponseBytes:x$,timeoutMs:P$});if(!t.ok)throw new $("invalid_client","Client JWKS could not be fetched.");return U$.parse(r)}o(D$,"fetchClientJwks");async function j$(e){if(e.clientAssertionType!==I$||e.clientAssertion===void 0)throw new $("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=Oe.parse(e.clientId),r=await ac(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new $("invalid_client","Client is not registered for private_key_jwt authentication.");let n=r.metadata.jwks_uri;if(n===void 0)throw new $("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let a=q$({requestUrl:e.requestUrl,pathname:e.endpointPathname});try{let i=await D$({jwksUri:n,context:e.context});await R$(e.clientAssertion,w$(i),{issuer:t,subject:t,audience:a,currentDate:e.now})}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:N$(i)},"OAuth private_key_jwt client authentication failed"),new $("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}o(j$,"verifyPrivateKeyJwtClientAssertion");async function H$(e){let t=Oe.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 fe(e.clientSecret)}}o(H$,"buildRuntimeHttpClientAuth");async function Cw(e){if($$({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new $("invalid_request","Use only one client authentication method per request.");return j$(e)}let t=z$({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return H$({clientId:e.clientId,...t})}o(Cw,"resolveRuntimeHttpClientAuth");async function Iw(e){T$(e.body);let t=A$.parse(e.body),r=bw(e.authorizationHeader),n=Rw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date,i=await Cw({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/token",now:a,context:e.context});return L$({parsed:t,clientId:n,clientAuth:i,now:a,requestUrl:e.requestUrl,context:e.context})}o(Iw,"exchangeDownstreamToken");async function L$(e){if(e.parsed.grant_type==="authorization_code"){bo(e.parsed.redirect_uri,"invalid_request","token"),Za(e.parsed.scope),e.parsed.resource!==void 0&&Ro(e.requestUrl??e.parsed.resource,e.parsed.resource);let s=ir(),c=ir(),d=oe(or(e.now,O$())),p=M$(e.now,d),l=await Y().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await fe(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await lh(e.parsed.code_verifier),currentRefreshTokenHash:await fe(s),accessTokenHash:await fe(c),grantExpiresAt:d,accessTokenExpiresAt:p.expiresAt,now:oe(e.now)});if(l.kind==="invalid_client")throw new $("invalid_client","Client authentication failed.");if(l.kind==="resource_mismatch")throw new $("invalid_target","Token request resource must match the authorization code resource.");if(l.kind!=="exchanged")throw new $("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&J(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:c,token_type:"Bearer",expires_in:p.expiresIn,refresh_token:s,scope:l.grant.scope,resource:l.grant.resource}}Za(e.parsed.scope),e.parsed.resource!==void 0&&Ro(e.requestUrl??e.parsed.resource,e.parsed.resource);let t=ir(),r=ir(),n=oe(or(e.now,ww())),a=await Y().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:await fe(e.parsed.refresh_token),nextRefreshTokenHash:await fe(t),accessTokenHash:await fe(r),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:n,now:oe(e.now)});if(a.kind==="invalid_client")throw new $("invalid_client","Client authentication failed.");if(a.kind==="resource_mismatch")throw new $("invalid_target","Token request resource must match the refresh token grant resource.");if(a.kind!=="rotated")throw new $("invalid_grant","Refresh token is invalid, expired, or revoked.");Ro(e.requestUrl??a.grant.resource,a.grant.resource);let i=a.accessToken.expiresAt;return e.context&&(J(e.context,{eventType:F.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),J(e.context,{eventType:F.MCP_OAUTH_TOKEN_REFRESH_ROTATED,outcome:"success",attributes:{clientId:e.clientId}})),{access_token:r,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(i).getTime()-e.now.getTime())/1e3)),refresh_token:t,scope:a.grant.scope,resource:a.grant.resource}}o(L$,"exchangeDownstreamTokenWithRuntimeHttp");async function Pw(e){let t=E$.parse(e.body),r=bw(e.authorizationHeader),n=Rw({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date;if((await Y().revokeOAuthToken({clientAuth:await Cw({clientId:n,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/revoke",now:a,context:e.context}),tokenHash:await fe(t.token),now:oe(a)})).kind==="invalid_client")throw new $("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"),e.context&&J(e.context,{eventType:F.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}o(Pw,"revokeDownstreamToken");var B$=64*1024,G$=16*1024,V$="text/html; charset=utf-8";function F$(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(F$,"formDataToObject");async function Z$(e){return Av(e,{maxBytes:B$,label:"Request body"})}o(Z$,"readJsonBody");async function ic(e){return F$(await ec(e,{maxBytes:G$,label:"Request body"}))}o(ic,"readFormBody");async function xw(e,t,r){let n=dt(r),a=r instanceof u.ZodError?sc(r):void 0,i={code:n??(r instanceof u.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(i.detail=a),xr(e,t,i)}o(xw,"handleProblem");function Ja(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(Ja,"oauthErrorResponse");function K$(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(K$,"readOAuthProtocolHeaders");function J$(e,t){let r=Ee("internal_server_error");return Ja({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:K$(e,t)})}o(J$,"oauthProtocolErrorResponse");function kw(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(kw,"readZodOAuthErrorCode");function W$(e){let t={error:kw(e)},r=sc(e);return r!==void 0&&(t.errorDescription=r),Ja(t)}o(W$,"oauthZodErrorResponse");function Y$(e){let t=dt(e);if(t===void 0)return;let r=Ee(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:Q$(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,Ja(n)}o(Y$,"oauthGatewayProblemResponse");function X$(){let t={error:"server_error",status:500,errorDescription:Ee("internal_server_error").publicDetail};return Ja(t)}o(X$,"oauthFallbackErrorResponse");function Q$(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(Q$,"readOAuthStatus");function Zp(e,t={}){return e instanceof Wr?Ew(e):e instanceof $?J$(e,t):e instanceof u.ZodError?W$(e):Y$(e)??X$()}o(Zp,"oauthProblemResponse");function Kp(e,t){let r=Yt(e.url);if(t instanceof Wr)return Ew(t);if(t instanceof $){let i=Ee("internal_server_error");return Rt({host:r,kind:eq(t.errorCode),title:"Authorization failed",detail:t.errorCode==="server_error"?i.publicDetail:t.message,code:t.errorCode,status:t.status})}if(t instanceof u.ZodError)return Rt({host:r,kind:"invalid_request",detail:sc(t)??"The authorization request was invalid.",code:kw(t)});let n=dt(t);if(n!==void 0){let i=Ee(n);return Rt({host:r,kind:Tw(n),detail:i.status<500&&t instanceof Error?t.message:i.publicDetail,code:i.oauthError??n,status:i.status})}let a=Ee("internal_server_error");return Rt({host:r,kind:"internal_error",detail:a.publicDetail,code:"server_error",status:a.status})}o(Kp,"browserOAuthProblemResponse");function Aw(e,t){let r=Yt(e.url),n=dt(t);if(n!==void 0){let i=Ee(n);return Rt({host:r,kind:Tw(n),detail:i.status<500&&t instanceof Error?t.message:i.publicDetail,code:n,status:i.status})}if(t instanceof u.ZodError)return Rt({host:r,kind:"invalid_request",detail:sc(t)??"The authorization request was invalid.",code:"invalid_request"});let a=Ee("internal_server_error");return Rt({host:r,kind:"internal_error",detail:a.publicDetail,code:"internal_server_error",status:a.status})}o(Aw,"browserGatewayProblemResponse");function eq(e){return e==="server_error"?"internal_error":"invalid_request"}o(eq,"readOAuthBrowserErrorKind");function Tw(e){if(Ee(e).status>=500)return"internal_error";switch(e){case"virtual_server_not_enabled":case"unknown_upstream_server":case"unknown_virtual_server":case"unknown_auth_profile":case"virtual_server_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}o(Tw,"readGatewayBrowserErrorKind");function Xt(e,t,r){let n={event:t},a=!1;if(r instanceof $)n.oauthError=r.errorCode,n.status=r.status,Xe(n,"error",r);else if(r instanceof Wr)n.oauthError=r.errorCode,Xe(n,"error",r);else if(r instanceof u.ZodError){n.code="invalid_request",Xe(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=dt(r);if(i!==void 0){let s=Ee(i);n.code=i,n.status=s.status,s.oauthError!==void 0&&(n.oauthError=s.oauthError),a=s.status>=500||s.oauthError==="server_error",Xe(n,"error",r)}else a=!0,Xe(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(Xt,"logUnexpectedOAuthHandlerError");function Ew(e){let t;try{t=new URL(e.redirectUri)}catch{return Ja({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(Ew,"downstreamAuthorizeRedirectErrorResponse");function sc(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(sc,"formatZodErrorDetail");function tq(e,t){let r={event:"browser_login_callback_failed",code:dt(t)??"invalid_request"};Xe(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(tq,"logBrowserLoginCallbackFailure");function Jp(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(Jp,"redirectResultResponse");function cc(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":V$,"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 Jp(e)}o(cc,"authorizeResultResponse");async function Uw(e,t){try{return Response.json(hu(e.url))}catch(r){return Xt(t,"oauth_authorization_server_metadata_failed",r),xw(e,t,r)}}o(Uw,"authorizationServerMetadataHandler");async function Ow(e,t){try{let r=Ue.parse(e.params.virtualServerId),n=Nt(r);return Response.json(of({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return Xt(t,"oauth_authorization_server_metadata_failed",r),xw(e,t,r)}}o(Ow,"scopedAuthorizationServerMetadataHandler");async function Mw(e,t){try{let r=await uw(await Z$(e)),n=r,a=typeof n.client_id=="string"?n.client_id:void 0,i=typeof n.client_name=="string"?n.client_name:void 0,s=Array.isArray(n.redirect_uris)?n.redirect_uris.length:void 0,c=typeof n.token_endpoint_auth_method=="string"?n.token_endpoint_auth_method:void 0;return t.log.info({event:"oauth_dcr_client_registered",clientId:a,clientName:i,redirectUriCount:s,tokenEndpointAuthMethod:c},"OAuth Dynamic Client Registration completed"),J(t,{eventType:F.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:i,attributes:{clientId:a,redirectUriCount:s,tokenEndpointAuthMethod:c}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Xt(t,"oauth_register_failed",r),Zp(r)}}o(Mw,"registerHandler");async function zw(e,t){try{return cc(await Fp(e,{context:t}))}catch(r){return Xt(t,"oauth_authorize_failed",r),Kp(e,r)}}o(zw,"authorizeHandler");async function $w(e,t){try{let r=Ue.parse(e.params.virtualServerId),n=Nt(r);return cc(await Fp(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return Xt(t,"oauth_authorize_scoped_failed",r),Kp(e,r)}}o($w,"scopedAuthorizeHandler");async function qw(e,t){try{let r=await gw(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),cc(r)}catch(r){return tq(t,r),Aw(e,r)}}o(qw,"callbackHandler");async function Nw(e,t){try{return Jp(await yw(e))}catch(r){return Xt(t,"oauth_dev_login_failed",r),Kp(e,r)}}o(Nw,"devLoginHandler");async function Dw(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?Mv(r,n):Tp(r,400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):Jp(await Sw({request:e,body:await ic(e)}))}catch(n){return Xt(t,"oauth_api_key_login_failed",n),Tp(r)}}o(Dw,"apiKeyLoginHandler");async function jw(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await _w({request:e,body:e.method==="POST"?await ic(e):void 0,context:t});return cc(r)}catch(r){return Xt(t,"oauth_setup_failed",r),Aw(e,r)}}o(jw,"setupHandler");async function Hw(e,t){try{return Response.json(await Iw({body:await ic(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Xt(t,"oauth_token_failed",r),Zp(r)}}o(Hw,"tokenHandler");async function Lw(e,t){try{return await Pw({body:await ic(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Xt(t,"oauth_revoke_failed",r),Zp(r)}}o(Lw,"revokeHandler");var rq={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},Bw=new $t("upstream-request");function nq(e){let t=Bw.get(e);if(!t)throw new K("Upstream request context has not been set");return t}o(nq,"readUpstreamRequestContext");function oq(e,t){return t.some(r=>r===e)}o(oq,"requestContextMatchesKind");function aq(e){return typeof e=="string"?[e]:e}o(aq,"toExpectedKinds");function An(e,t){Bw.set(e,t)}o(An,"setUpstreamRequestContext");function Tn(e,t){let r=nq(e),n=aq(t);if(!oq(r.kind,n)){let a=rq[n[0]];throw new K(`${a} request context has not been set`)}return r}o(Tn,"requireUpstreamRequestContext");function Gw(e){return se`<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
60
+ configuration.</p><button class="button button--primary button--block form__submit" type="submit" >Connect</button></form>`}o(Gw,"renderAppPassword");function Vw(e){return se`<p data-gateway-error-code="${e.code}">${e.body}</p>`}o(Vw,"renderBrowserResult");var iq="text/html; charset=utf-8",sq="none";function cq(e){let t=Sr(e.host);return Mt({title:e.title,iconHref:t,styles:Ot,headerIcon:_r({iconHref:t,fallbackIconHref:yr}),heading:e.title,subhead:"",body:Vw({body:e.body,code:e.code??sq}),footer:""})}o(cq,"browserResultHtml");function uq(e,t=200){return new Response(Wt(e),{status:t,headers:{"content-type":iq,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(uq,"browserResultResponse");function uc(e){return uq(cq(e))}o(uc,"browserConnectionSuccessResponse");function Co(e,t){let r=Fm(t);return Rt({host:e,kind:dq(t),detail:r.body,code:t})}o(Co,"browserConnectionFailureResponse");function dq(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed"}}o(dq,"readCallbackFailureBrowserErrorKind");var lq="text/html; charset=utf-8",pq=16*1024;function mq(e,t=200){return new Response(Wt(e),{status:t,headers:{"content-type":lq,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(mq,"htmlResponse");function fq(e,t){return Response.redirect(new URL(t,e).toString(),302)}o(fq,"safeRedirect");function hq(e){if(!e)throw new E({message:"App password capture requires a signed browser ticket.",extensionMembers:{[T]:"oauth_state_invalid"}});return e}o(hq,"requireBrowserTicket");function gq(e,t){return[e.ownerMode!=="user"||e.upstreamServerId!==t.upstreamServerId||t.virtualServerId!==void 0&&e.virtualServerId!==t.virtualServerId].every(n=>!n)}o(gq,"appPasswordTicketMatchesTarget");async function Fw(e){let t=hq(e.browserTicket),r=await Gi(t);if(!gq(r,e))throw new E({message:"App password capture ticket did not match the requested upstream flow.",extensionMembers:{[T]:"oauth_callback_mismatch"}});return{upstreamServerId:e.upstreamServerId,authProfileId:r.authProfileId,virtualServerId:r.virtualServerId,browserTicket:t,ticket:r}}o(Fw,"readAppPasswordTarget");function yq(e,t){let r=ad(e.upstreamServerId,e.authProfileId),n=`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`,a=Sr(t),i=r.kind==="basic_auth_app_password"?se`<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">`:se`<label class="form__label" for="token">${r.label}</label><input class="form__input" id="token" name="token" type="password" required autocomplete="off">`;return mq(Mt({title:"Connect upstream",iconHref:a,styles:Ot,headerIcon:_r({iconHref:a,fallbackIconHref:yr}),heading:"Connect upstream",subhead:se`<p class="card__subtitle">Enter the per-user credential for this approved upstream.</p>`,body:Gw({action:n,browserTicket:e.browserTicket,fields:i}),footer:""}))}o(yq,"renderCaptureForm");function dc(e,t){let r=e.get(t);if(typeof r!="string"||r.length===0)throw new E({message:`Missing form field: ${t}`,extensionMembers:{[T]:"invalid_request"}});return r}o(dc,"readRequiredFormValue");function Sq(e){return{upstreamServerId:e.upstreamServerId,...e.virtualServerId===void 0?{}:{virtualServerId:e.virtualServerId},...e.browserTicket===void 0?{}:{browserTicket:e.browserTicket}}}o(Sq,"readCaptureFormTargetInput");async function _q(e,t){return yq(await Fw(Sq(e)),t)}o(_q,"handleCaptureFormRequest");async function vq(e){let t=await ec(e.request,{maxBytes:pq,label:"App password request body"});return{form:t,target:await Fw({upstreamServerId:e.upstreamServerId,browserTicket:dc(t,"browserTicket")})}}o(vq,"readSubmittedAppPasswordTarget");async function wq(e){let t=Bn(e.target.ticket);if(await Vi(e.target.ticket),ad(e.target.upstreamServerId,e.target.authProfileId).kind==="bearer_token"){await Fi({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,token:dc(e.form,"token")});return}await hg({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,username:dc(e.form,"username"),appPassword:dc(e.form,"appPassword")})}o(wq,"saveSubmittedAppPasswordCredential");function bq(e,t){return t.ticket.returnTo?fq(e,t.ticket.returnTo):uc({host:Yt(e),title:"Connection complete",body:"The upstream credential was saved. Return to your MCP client and retry the request."})}o(bq,"appPasswordSuccessResponse");async function Rq(e){let t=await vq({request:e.request,upstreamServerId:e.appPasswordRequest.upstreamServerId});return await wq(t),bq(e.request.url,t.target)}o(Rq,"handleAppPasswordSubmission");function Cq(){return new Response(null,{status:405,headers:{Allow:"GET, POST"}})}o(Cq,"methodNotAllowedResponse");function Iq(e,t,r,n){let a=n instanceof E?n.extensionMembers?.[T]:void 0;if(!Si(a)){if(a==="invalid_request")return Rt({host:r,kind:"invalid_request",title:"Connection failed",detail:n instanceof Error?n.message:"The upstream credential request was invalid.",code:a});throw n}return Co(r,a)}o(Iq,"appPasswordFailureResponse");async function Pq(e){let t=Yt(e.request.url);switch(e.request.method){case"GET":return _q(e.appPasswordRequest,t);case"POST":return Rq(e);default:return Cq()}}o(Pq,"handleAppPasswordMethod");async function Wp(e,t){let r=Tn(t,"app_password");try{return await Pq({request:e,appPasswordRequest:r})}catch(n){return Iq(e,t,Yt(e.url),n)}}o(Wp,"appPasswordHandler");var xq=["callback_authorization_code","callback_provider_error","callback_invalid"];function kq(e){return"cause"in e?e.cause:void 0}o(kq,"readErrorCause");function Aq(e){return e.stack?.split(`
61
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}o(Aq,"readFirstStackFrame");function Zw(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=Aq(r))}o(Zw,"addErrorAttributes");function Yp(e){if(!(e instanceof E))return;let t=e.extensionMembers?.[T];return ar(t)?t:void 0}o(Yp,"readRuntimeGatewayCode");function Tq(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"),J(e,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),Co(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"),Co(r,"oauth_state_invalid");case"callback_authorization_code":return t}}o(Tq,"requireAuthorizationCallbackRequest");function Eq(e,t){J(e,{eventType:F.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(Eq,"emitCallbackReceivedAnalyticsEvent");function Uq(e,t){J(e,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(Uq,"emitTokenExchangeSucceededAnalyticsEvent");function Oq(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return uc({host:Yt(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(Oq,"buildSuccessfulCallbackResponse");function Mq(e){let t={detail:e instanceof Error?e.message:void 0};return Zw(t,"error",e),e instanceof Error&&Zw(t,"cause",kq(e)),t}o(Mq,"buildTokenExchangeFailureAttributes");function zq(e){J(e.context,{eventType:F.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Yp(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:Mq(e.error)})}o(zq,"emitTokenExchangeFailedAnalyticsEvent");function $q(e,t){let r=Yp(t);return Co(e,Si(r)?r:"upstream_token_exchange_failed")}o($q,"tokenExchangeFailureResponse");async function Xp(e,t){let r=Tn(t,xq),n=Yt(e.url),a=Tq(t,r,n);if(a instanceof Response)return a;Eq(t,a);try{let i=await Gg({request:e,callbackRequest:a});return Uq(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"),Oq(e,i)}catch(i){let s={event:"upstream_oauth_token_exchange_failed",code:Yp(i)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return Xe(s,"error",i),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),zq({context:t,callbackRequest:a,error:i}),$q(n,i)}}o(Xp,"callbackHandler");function qq(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(qq,"clientMetadataProblemDetail");async function Kw(e,t){let r=Tn(t,"connect"),n=await Bg({request:e,connectRequest:r});if(J(t,{eventType:F.MCP_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 Lt({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(Kw,"connectHandler");async function Jw(e,t){let r=Tn(t,"client_metadata");try{let n=Ag(e.url),a=Tg(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){if(!(n instanceof q))throw n;let a=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:a},"Failed to serve OAuth client metadata document for upstream connection"),Ae.notFound(e,t,{code:"not_found",detail:qq(n)})}}o(Jw,"oauthClientMetadataHandler");function vr(e){if(typeof e=="string"&&e.length!==0)return e}o(vr,"readOptionalQueryString");function Nq(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new K(`Validated path parameter ${t} is missing`);return r}o(Nq,"requirePathString");function Ww(e){let t=vr(e);return t?Ue.parse(t):void 0}o(Ww,"readOptionalVirtualServerId");function Dq(e,t){let r=vr(e);return r?tt.parse(r):Zn(t,"user-oauth")}o(Dq,"readOptionalAuthProfileId");function jq(e){let t=Ww(e);if(!t)throw new E({message:"virtualServerId query parameter is required.",extensionMembers:{[T]:"invalid_request"}});return t}o(jq,"readRequiredVirtualServerId");function Hq(e){let t=vr(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(Hq,"readOptionalBrowserTicket");function Lq(e){let t=ki(vr(e));return t===void 0?{}:{returnTo:t}}o(Lq,"readOptionalReturnTo");function Bq(e){let t=Ww(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(Bq,"readOptionalVirtualServerIdContext");function Gq(e){let t=vr(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o(Gq,"readOptionalProviderErrorDescription");function Vq(e){let t=jt(e.authMode);if(t.connectSupport!=="none")return e;throw new E({message:t.connectUnsupportedDetail??"This upstream does not support browser connection flows.",extensionMembers:{[T]:"invalid_request"}})}o(Vq,"requireConnectableRouteAuth");function Fq(e,t,r,n){let a=Xs(e,t);if(a.ownerMode==="none"||a.authMode==="shared-secret")throw new K("Static-secret upstreams do not support browser connection flows.");return{kind:"connect",...a,...n===void 0?{}:{returnTo:n},redirect:r}}o(Fq,"buildConnectContextForPrincipal");function Zq(e,t,r){let n=Bn(t),a=jt(e.authMode);if(n.mode!==a.ownerMode)throw new E({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[T]:"oauth_callback_mismatch"}});return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:n,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}o(Zq,"buildConnectContextForTicket");async function Kq(e,t){let r=Vq(bv(t,jq(e.query.virtualServerId))),n=e.query.redirect==="true",a=vr(e.query.browserTicket);if(e.user){if(a)throw new E({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[T]:"invalid_request"}});let s=jn(e.user,e.url);return Fq(r,s,n,Lq(e.query.returnTo).returnTo)}if(!a)throw new E({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[T]:"authentication_required"}});let i=await Gi(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.virtualServerId!==r.virtualServerId)throw new E({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[T]:"oauth_callback_mismatch"}});return await Vi(i),Zq(r,i,n)}o(Kq,"resolveConnectContext");async function Jq(e,t,r){let n=et.parse(Nq(e,"connection"));switch(r){case"connect":An(t,await Kq(e,n));return;case"app_password":An(t,{kind:"app_password",upstreamServerId:n,...Bq(e),...Hq(e)});return;case"callback":{let a=vr(e.query.error);if(a){An(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...Gq(e)});return}let i=vr(e.query.code),s=vr(e.query.state);if(i&&s){An(t,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:s});return}An(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":An(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:Dq(e.query.authProfileId,n)});return}}o(Jq,"resolveUpstreamRequestInbound");async function Wq(e,t,r){try{await Jq(e,t,r);return}catch(n){let a=n instanceof E?n.extensionMembers?.[T]:void 0,i=n instanceof Error?n.message:void 0;switch(a){case"invalid_request":case"oauth_callback_mismatch":return Ae.badRequest(e,t,{code:a,detail:i});case"authentication_required":return Ae.unauthorized(e,t,{code:a,detail:i});default:throw n}}}o(Wq,"applyUpstreamRequestContext");function Wa(e,t){return o(async(n,a)=>{let i=await Wq(n,a,e);return i||t(n,a)},"wrapped")}o(Wa,"withUpstreamRequestContext");var Yq={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function Xq(){return new Response(null,{status:204,headers:Yq})}o(Xq,"buildWellKnownPreflightResponse");function Qq(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(Qq,"withWellKnownCorsHeaders");function Qp(e){return async(t,r)=>t.method==="OPTIONS"?Xq():Qq(await e(t,r))}o(Qp,"wrapWellKnownHandler");var eN=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Qp(Uw),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Qp(Ow),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Qp(af),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:Mw},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:zw},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:$w},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:qw},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:Nw},{routeName:"oauth_api_key_login",path:"/oauth/api-key-login",methods:["GET","POST"],handler:Dw},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:jw},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:Hw},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:Lw},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Wa("client_metadata",Jw)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Wa("connect",Kw)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Wa("callback",Xp)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:Wa("app_password",Wp)}];function Yw(e){return e?.some(Du)??!1}o(Yw,"shouldRegisterMcpGatewayInternalRoutes");function tN(e){let t=Sh(e.policies);if(!t){let r=[...Nu].map(n=>`\`${n}\``).join(", ");throw new q(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return Th(Zu({routes:e.routes,policies:e.policies})),t.config}o(tN,"initializeMcpGatewayState");function rN(e,t,r){return async(n,a)=>{let i=a;Nn(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(rN,"wrapInternalHandler");function Xw(e,t){let r,n=o(()=>(r===void 0&&(r=tN(t)),r),"readOAuthConfig");for(let a of eN){let i=rN(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(Xw,"registerMcpGatewayInternalRoutes");function Qw(e){Ah(e)}o(Qw,"configureLazyMcpGatewayState");var em=class extends dm{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!Yw(r.policies))return;let n={routes:r.routes,policies:r.policies};Qw(n),Xw(t.router,n)}};export{zu as McpAuth0OAuthInboundPolicy,em as McpGatewayPlugin,$u as McpOAuthInboundPolicy,kp as McpUpstreamConnectionInboundPolicy,HM as McpVirtualServerHandler,gk as mcpUpstreamHandler};
62
62
  //# sourceMappingURL=index.js.map